Web3.py – How to Send Transaction with Web3.py

contract-developmentgo-ethereumraw-transactionweb3.pyweb3js

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?

Best Answer

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.

Related Topic