4

I'm trying to use web3.py with infura.io to interact with my smartcontract. here is my simple greeter contract code

pragma solidity ^0.5.7;
contract greeter{
    string greeting;

    function greet(string memory _greeting)public {
        greeting=_greeting;
    }
    function getGreeting() public view returns(string memory) {
        return greeting;
    }
}

I deployed it on ropsten testnet. with web3.py I can read greeting from chain. I wanted to add new greeting string with greet function. but somehow I have no idea about signing transaction. could anyone help me in understanding how to sign transacion and adding greeting to the contract using web3.py?

1 Answer 1

4

In web3py you can use the method buildTransaction:

myContract.functions.myMethod(*args, **kwargs).buildTransaction(transaction)

In your example you can do as follows:

tx = greeter.functions.greet("newGreet").buildTransaction({'nonce': web3.eth.getTransactionCount('your accountaddress')}}

Then you can sign the transaction using:

signed_tx = web3.eth.account.signTransaction(tx, private_key='your privateKey')

and finally you can send the transaction signed using:

web3.eth.sendRawTransaction(signed_tx.rawTransaction)

Hope this helps.

5
  • but it is showing an error "AttributeError: 'list' object has no attribute 'buildTransaction'". what seems to be the problem @jaime ?
    – ajay
    Apr 30, 2019 at 10:42
  • Can you show your code? what version of web3py do you have?
    – Jaime
    Apr 30, 2019 at 12:13
  • here is the link to my code at drive.google.com/open?id=1IJmA94uvpJ1s33uQHOEYj2qRl42rNAah please consider having look at it @jaime
    – ajay
    Apr 30, 2019 at 13:34
  • Notice that you must use contract_instance.functions.greet("text").build... notice that versions before 4.0 do not have this functionality. let me know
    – Jaime
    Apr 30, 2019 at 16:02
  • It should be build_transaction, not buildTransaction.
    – Marcin
    Mar 19, 2023 at 3:11

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.