0

web3 6.12.0 solc-v0.8.23 Python 3.12.1 Ganache v2.7.1

I've deployed this contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract TestContract {
    address public myAddress;
    uint testNumber;

    constructor() {
        myAddress = tx.origin;
        testNumber = 444;
    }

    function testTest() public view returns (address, uint) {
        uint a = 22 + 33;
        return (tx.origin, a);
    }
}

Now I want to call fuction testTest() from my terminal using python. Here is my python code:

from web3 import Web3

def test(_abi, _contract_address):
    my_address = "" # ganache address
    private_key = "" # ganache private key

    abi = _abi # contracts abi 
    contract_address = _contract_address # contracts address

    # connect to contract
    w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
    nonce = w3.eth.get_transaction_count(my_address)
    contract = w3.eth.contract(address=contract_address,abi=abi)

    print(contract.functions.testTest().call()) 
    # this gives 0x0000000000000000000000000000000000000000
    # and number 55
    
    print(contract.functions.myAddress().call()) 
    # this gives legit ganache address e.g. 
    # 0x13997C24536d6266B871B6478e803F186F3B6ffD
test([...],"0xdwed...")

testTest() function should return my_address but it doesn't. Can me someone explain me why ganache EVM can't read tx.origin or msg.sender. It looks like my contract can't access its own context after have been deployed. Am I using web3.py in a wrong way?

1 Answer 1

0

The function testTest is a view so it won't be executed inside a transaction

contract.functions.testTest().call()

You won't get a valid value from tx.origin because it is the account would have signed the transaction.

2
  • I've changed testTest() so it overrides myAddress, and changed test() in python in the way that it creates a transaction not a call, it works in the way that myAddress can be changed. Now I see, while builing a transaction, you are not supposed to receive any values in return statement. Am I right?
    – bordolot
    Commented Dec 18, 2023 at 16:58
  • @bordolot Exactly, transaction returns the transaction hash. To get a value from a transaction you have to use events.
    – Ismael
    Commented Dec 19, 2023 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.