【问题标题】:Decode the return value from a smart contract with web3.py?使用 web3.py 解码智能合约的返回值?
【发布时间】:2020-08-26 05:17:33
【问题描述】:

我重新发布了这个问题,因为它描述得不好。

我正在开发一个智能合约,当我使用 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

有人可以帮忙吗?

【问题讨论】:

    标签: python hex ethereum solidity smartcontracts


    【解决方案1】:

    transact() 方法提交交易并返回交易哈希。您应该首先等待交易被挖掘,并使用w3.eth.waitForTransactionReceipt获取交易回执。如果您打算使用事务而不是调用,您可以通过改变状态来获取函数的结果,然后通过调用view 函数或改变状态并生成event 来读取结果状态。

    在您的情况下,您不会改变状态,因此您可以将您的函数标记为view

    function test(int a) view public returns (int)
    

    然后使用call而不是生成事务:

    contract.functions.test(52).call()
    

    您可以阅读here about the difference between a transaction and a call

    official web3py documentation 也有很多调用智能合约函数的例子。

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2018-12-28
      • 2018-07-07
      • 1970-01-01
      • 2021-11-30
      • 2021-06-29
      相关资源
      最近更新 更多