目录
当前位置: 首页 > 文档资料 > MOAC 中文 WIKI >

Chain3接口python工具

优质
小牛编辑
121浏览
2023-12-01

环境安装

python版本的chain3支持python3.5.3及以上的版本。

建议使用虚拟环境进行chain的开发和调用,虚拟环境准备如下

$ which pip || curl https://bootstrap.pypa.io/get-pip.py | python

$ which virtualenv || pip install --upgrade virtualenv

$ sudo pip install virtualenv

$ virtualenv -p python3 ~/.venv-py3

$ source ~/.venv-py3/bin/activate

$ pip install --upgrade pip setuptools

$ pip install --upgrade chain3

安装完毕后,使用

    import chain3

不报错说明安装成功。

下次使用虚拟环境可使用如下命令激活

$ source ~/.venv-py3/bin/activate

API使用准备

from chain3 import Chain3
chain3 = Chain3(Chain3.HTTPProvider("http://127.0.0.1:8545", request_kwargs={'timeout': 30}))

API介绍

1. chain3.version.network:查看当前MOAC网络ID

print('network id:'+ str(chain3.version.network))

2. chain3.HTTPProvider: 设置API访问MOAC节点方式

Chain3(Chain3.HTTPProvider("http://127.0.0.1:8545", request_kwargs={'timeout': 30}))

3. chain3.sha3(string,options)

参数:

  • string:传入的需要使用Keccak-256 SHA3算法进行哈希运算的字符串
  • options:可选项,如果要解析的是hex格式的十六进制字符串,需要设置为hex
hash = chain3.sha3("the string to be hashed");
print(hash);
hashOfHash = chain3.sha3(hash,{encoding:'hex'});
print(hashOfHash);

4. chain3.net.peerCount: 返回连接节点已连上的其他moac节点的数量

peerCount = chain3.net.peerCount;
print(peerCount);

5. chain3.net.listening: 返回连接节点的listen状态

listenState = chain3.net.listening;
print(listenState);

6. chain3.mc.coinbase: 节点配置的,如果挖矿成功奖励发送到该地址

nodeCoinbase = chain3.mc.coinbase;
print(nodeCoinbase);

7. chain3.mc.mining: 节点的挖矿状态

miningState = chain3.mc.mining;
print(miningState);  //true or false

8. chain3.mc.accounts: 节点持有的账户列表

nodeAccounts = chain3.mc.accounts;
print(nodeAccounts);

9. chain3.mc.blockNumber: 当前区块号

nowBlockNumber = chain3.mc.blockNumber;
print(nowBlockNumber);

10. chain3.mc.getBlockTransactionCount: 指定区块的交易数量

transactionCount = chain3.mc.getBlockTransactionCount(96160);
print(transactionCount);

11. chain3.mc.getBalance: 给定地址的余额

balance = chain3.mc.getBalance("0x36eaa71d7383be53cb600743aad08a55222a4915", block_identifier=chain3.mc.defaultBlock);
print("getBalance1" + balance); //instanceof BigNumber
print("getBalance2" + balance.toString(10));
//输出结果: getBalance1:3.04527226722e+21  
//         getBalance2:3045272267220000000000

12. chain3.mc.defaultBlock: 默认块设置

defultBlock = chain3.mc.defaultBlock;
print("defaultBlock" + defultBlock);
//默认值是latest,即最近刚出的区块
chain3.mc.defaultBlock = 123;  //传入一个值来覆盖默认配置
print("defaultBlock" + defultBlock);

13. chain3.mc.gasPrice: 当前gas价格

gasPrice = chain3.mc.gasPrice;//该值由最近几个块的gas价格的中值决定
print(gasPrice.toString(10));

14. chain3.mc.estimateGas: 执行一个消息调用或交易,返回使用的gas量

result = chain3.mc.estimateGas({
 to :"0xf7ebc6b854a202efe08e91422a44ba2161ed50dc",
 data: '0x23455654'
    //gas: 11,          //可选参数,设定gas
    //gasPrice: 11      //可选参数,设定gasPrice
});
print('estimateGas  :'+ result);
//输出结果:gasprice :20000000000
//        estimateGas :1273

15. chain3.mc.getCode: 获取指定地址的代码(地址合约编译后的字节代码)

code  = chain3.mc.getCode("0x0000000000000000000000000000000000000065");//contract address

16. chain3.mc.syncing: 如果正在同步,返回同步对象;否则返回false

sync = chain3.mc.syncing;
print('syncing  :'+ sync );
//如果正在同步,返回同步开始区块号、节点当前正在同步的区块号、预估要同步到的区块号

17. chain3.mc.getTransaction: 返回指定交易哈希值的交易

blockHash = "0x6aa4a0db1fc155009bd9ba3a64c1aef109e1418dc05ee241d3e9e3e58d7f3eeb";
transaction = chain3.mc.getTransaction(blockHash);
print('get transaction:'+ str(transaction));

/* 输出结果
get transaction: AttributeDict({
   'blockHash': HexBytes('0x77483002572dd29b58640c4ccf5ef30278679037ff17b51cf613f3df562e5e0a'), 
   'blockNumber': 815006,
   'from': '0x0000000000000000000000000000000000000064', 
   'gas': 0, 
   'gasPrice': 20000000000,
   'hash': HexBytes('0x6aa4a0db1fc155009bd9ba3a64c1aef109e1418dc05ee241d3e9e3e58d7f3eeb'), 
   'input': '0xc1c0e9c4', 
   'nonce': 815005,
   'syscnt': '0x65', 
   'to': '0x0000000000000000000000000000000000000065', 
   'transactionIndex': 0, 
   'value': 0,
   'v': 0, 'r': HexBytes('0x00'), 's': HexBytes('0x00'), 
   'shardingFlag': 0})
*/

18. chain3.mc.getBlock: 返回区块号或区块哈希值所对应的区块

getTheBlock = chain3.mc.getBlock(815006);
print('get the block: '+ str(getTheBlock));

/* 输出结果
get the block: {
   'difficulty': 86803583, 
   'extraData': HexBytes('0xdd854d4f41432d85312e302e312d87676f312e392e358777696e646f7773'), 
   'gasLimit': 9000000, 
   'gasUsed': 0,
   'hash': HexBytes('0x77483002572dd29b58640c4ccf5ef30278679037ff17b51cf613f3df562e5e0a'),
   'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000000000000000000000000000000000000000000000000000000000000000000000
           000000000000000000'),
   'miner': '0x0a2168D2f08161c01745fEC4e6E8FE06F314Ab41', 
   'mixHash': HexBytes('0xc154897a85ca63bbbbb76b618a288f6b33f7d2994848dc9c43c6d65e6a5da355'),
   'nonce': HexBytes('0x829f5b23cdf8224f'), 
   'number': 815006, 
   'parentHash': HexBytes('0x73c0e4a94b48b41bf5a6a22151e38799a0e17e8b798848af5340f6d725027af1'),
   'receiptsRoot': HexBytes('0x9287370eb27f11b0c2188431cbc58a23b685f02dbd851ed4d974f932bd780839'), 
   'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 
   'size': 590, 
   'stateRoot': HexBytes('0x615d0a39783ae546e11aa0cd6e00c70c2ec989f51316c0f9e07cfc99f1088669'), 
   'timestamp': 1535530608, 
   'totalDifficulty': 136959813601540,
   'transactions': [HexBytes('0x6aa4a0db1fc155009bd9ba3a64c1aef109e1418dc05ee241d3e9e3e58d7f3eeb')],
   'transactionsRoot': HexBytes('0x7aba2a9c974693f1cfb96d506e6aa62942a174b4df39c831cf844a35e03249f0'), 
   'uncles': []
})
*/

19. chain3.personal.unlockAccount: 解锁本地帐户以便使用

chain3.personal.unlockAccount(mc.accounts[0], 'password')

20. chain3.miner.start: 开始本地挖矿

chain3.miner.start(2) # number of threads

21. chain3.miner.stop: 停止本地挖矿

chain3.miner.stop()

22. chain3.mc.getTransactionReceipt: 查看交易结果

txr = chain3.mc.getTransactionReceipt('0x77483002572dd29b58640c4ccf5ef30278679037ff17b51cf613f3df562e5e0a')
print(txr)

/* 输出结果
AttributeDict({
   'blockHash': HexBytes('0x77483002572dd29b58640c4ccf5ef30278679037ff17b51cf613f3df562e5e0a'), 
   'blockNumber': 815006,
   'contractAddress': '0x0000000000000000000000000000000000000065', 
   'cumulativeGasUsed': 0, 
   'from': '0x0000000000000000000000000000000000000064',
   'gasUsed': 0, 
   'logs': [], 
   'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000000000000000000000000000000000000000000000000000000000000000000000
       000000000000000000'),
   'status': 1, 
   'to': '0x0000000000000000000000000000000000000065', 
   'transactionHash': HexBytes('0x6aa4a0db1fc155009bd9ba3a64c1aef109e1418dc05ee241d3e9e3e58d7f3eeb'),
   'transactionIndex': 0})
*/

23. chain3.mc.getTransactionCount: 查看交易数量

chain3.mc.getTransactionCount('0x87E369172Af1e817ebD8d63bcD9f685A513a6736', block_identifier=chain3.mc.defaultBlock)

24. chain3.mc.sendTransaction(transaction, passphrase): 在线发送交易

  • from: bytes or text, hex address or ENS name - (optional, default: chain3.mc.defaultAccount) The address the transaction is send from.
  • to: bytes or text, hex address or ENS name - (optional when creating new contract) The address the transaction is directed to.
  • gas: integer - (optional) Integer of the gas provided for the transaction execution. It will return unused gas.
  • gasPrice: integer - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas
  • value: integer - (optional) Integer of the value send with this transaction
  • data: bytes or text - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters.
  • nonce: integer - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.

If the transaction specifies a data value but does not specify gas then the gas value will be populated using the estimateGas() function with an additional buffer of 100000 gas up to the gasLimit of the latest block. In the event that the value returned by estimateGas() method is greater than the gasLimit a ValueError will be raised.

  • shardingFlag:integer - subchain flag, 1: call subchain

  • via - vode beneficial address

chain3.mc.sendTransaction({
    'to':'0xf103BC1c054baBcecD13e7AC1CF34F029647B08C',
    'from':'0x87E369172Af1e817ebD8d63bcD9f685A513a6736', 
    'value': 100000, 
    'gasPrice': chain3.mc.gasPrice,
    'shardingFlag': 0,
    'via': '0x0000000000000000000000000000000000000000',})

25. chain3.mc.sendRawTransaction: 离线发送交易

private_key = '0x94645c7a048771045f90e0b88adf3ddf5afbb5029c2b1b5586d5afa9ba87c8f5'
signed_txn = chain3.mc.account.signTransaction(
    dict(
        nonce=chain3.mc.getTransactionCount(chain3.mc.coinbase),
        gasPrice=chain3.mc.gasPrice,
        gas=100000,
        to='0xf103BC1c054baBcecD13e7AC1CF34F029647B08C',
        value=100000,
        data='0x',
        'chainId': networkid,
        'shardingFlag': 0,
        'via': '0x',
    ),
    private_key,
)
chain3.mc.sendRawTransaction(signed_txn.rawTransaction)

/* 返回 tx hash
    '0xd7e3a30f9eec70d5626b70a2082bd2573a2b0a282756479c2f48a57a833204ab'
*/