繁体   English   中英

使用 web3.py 解码智能合约的返回值?

[英]Decode the return value from a smart contract with web3.py?

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

我正在研究一个智能合约,当我使用 web3.py 使用 python 脚本调用它时,它假设返回 1,但我的 python 脚本中没有 1,而是收到一个六字节 ZA8CFDE6331BD59EB26666F891C41C41。 我想我需要使用 ABI 和 web3.py 对其进行解码,但我不知道如何?

我有一个像这样的 function :

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()方法提交交易并返回交易 hash。 您应该首先等待交易被挖掘,然后使用w3.eth.waitForTransactionReceipt获取交易收据。 If you intend to use a transaction instead of a call you can get the result of your function by mutating the state and then reading the resulting state by calling a view function or mutating the state and generating an event .

在您的情况下,您不会改变 state 因此您可以将 function 标记为view

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

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

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

您可以在此处阅读有关事务和调用之间的区别

官方的 web3py 文档也有很多调用智能合约函数的例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM