因为这个问题没有描述清楚,所以我重发。
我正在做一个智能合约,当我使用web3.py用python脚本调用它时,它应该返回1,但在我的python脚本中没有1,而是收到一个hexbytes对象。我想我需要使用ABI和web3.py对它进行解码,但我不知道该怎么做?
我在solidity中有一个这样的函数。
pragma solidity ^0.5.10;
contract test {
function test(int a) public returns (int) {
if(a > 0){
return 1;
}
}
}
当我用我的python脚本调用它时,
import json
import web3
from web3 import Web3
#To connect to ganache blockchain:
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))
#this script will be the account number 1 on ganache blockchain:
web3.eth.defaultAccount = web3.eth.accounts[1]
#smart contract: abi, address and bytecode
abi = json.loads('....')
address = web3.toChecksumAddress("0x4A4AaA64857aa08a709A3470A016a516d3da40bf")
bytecode = "..."
#refering to the deploy coontract
contract = web3.eth.contract(address = address, abi = abi, bytecode = bytecode)
con = contract.functions.test(52).transact()
print(con.hex())
我的结果是这样的
<class 'hexbytes.main.HexBytes'>
0x3791e76f3c1244722e60f72ac062765fca0c00c25ac8d5fcb22c5a9637c3706d
谁能帮帮我?
该 transact()
方法提交交易并返回交易哈希。你应该先等待交易被挖掘出来,然后用这个方法获得交易收据。w3.eth.waitForTransactionReceipt
. 如果你打算使用事务而不是调用,你可以通过突变状态来获取函数的结果,然后通过调用 view
函数或突变状态并生成一个 event
.
在你的情况下,你没有突变状态,所以你可以将你的函数标记为 view
:
function test(int a) view public returns (int)
然后用 call
而不是生成一个事务。
contract.functions.test(52).call()
你可以阅读 这里是关于交易和呼叫之间的区别。.
还 官方web3py文档 有很多调用智能合约功能的例子。