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

Viewed 4695

I'm reposting the question since it wasn't well describe.

I'm working on a smart contract that is suppose to return 1 when I call it with a python script using web3.py, but instead of having a 1 in my python scirpt I receive an hexbytes object. I suppose I need to decode it using the ABI and web3.py but I don't know how?

I have a function like this in solidity:

pragma solidity ^0.5.10;

contract test {
    function test(int a) public returns (int) {
            if(a > 0){
                return 1;
            }
        }
}

When I called it with my python script:

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())

I have result like this:

<class 'hexbytes.main.HexBytes'>
0x3791e76f3c1244722e60f72ac062765fca0c00c25ac8d5fcb22c5a9637c3706d

Can someone help?

1 Answers

The transact() method submits the transaction and returns transaction hash. You should first wait for the transaction to be mined, and get the transaction receipt using 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.

In your case you don't mutate the state so you can mark your function as view:

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

and then use call instead of generating a transaction:

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

You can read here about the difference between a transaction and a call.

Also the official web3py documentation has many examples of invoking smart contract functions.

Related