Solidity – How to Call Write Functions via Python web3.py with w3.eth.sendRawTransaction

pythonsendrawtransactionsolidityweb3.py

Hi I am running Python web3.py (not web3.js) to interact with contract functions:

w3 = Web3(HTTPProvider('http://room1.abc.com:8545/'))

txn = ctrtInstance.functions.setzString(zString).buildTransaction()
txn['nonce'] = 3643 # I have to add those into txn because Python complains about missing arguments
txn['chainId'] = 3 # for Ropsten network

signed = w3.eth.account.signTransaction(txn, privateKey)
txn_hash = w3.eth.sendRawTransaction(signed.rawTransaction)

My variables have the following values:

>>> txn
{
    'value': 0,
    'gas': 33504,
    'gasPrice': 1000000000,
    'chainId': 3,
    'to': '0x5227Dxyzxyzxyz',
    'data': '0xb32e420700000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000007476f204d616e2100000000000000000000000000000000000000000000000000',
    'nonce': 3643
}
>>> signed
AttrDict({
    'rawTransaction': HexBytes('0xf8ca820e3f8408f0d1808282e0945227d720d8efdcb259c6c79c74f3cfe04dc4d4fa80b864b32e420700000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000007476f204d616e21000000000000000000000000000000000000000000000000002aa0d6caf903ed36cbd971612805e0506c8800d8d7d2bf8e96efcbd17ef87ca103dda02875ef8165c191658e91d81c3f1a52e32f0ecb57956a943496290f9bd400080e'),
    'hash': HexBytes('0xcd96d8b646eabcaf40955a44b3bfd0bdd8eb8c8baab1d5eb1788802905fedd0d'),
    'r': 97153571344605986608608195363439103576254965532977107907893318995927525032925,
    's': 18300888055835900205586458475722080051361212052928774052376466183455388993550,
    'v': 42
})
>>> txn_hash
b'\xcd\x96\xd8\xb6F\xea\xbc\xaf@\x95ZD\xb3\xbf\xd0\xbd\xd8\xeb\x8c\x8b\xaa\xb1\xd5\xeb\x17\x88\x80)\x05\xfe\xdd\r'
>>> txn_hash.hex()
'cd96d8b646eabcaf40955a44b3bfd0bdd8eb8c8baab1d5eb1788802905fedd0d'

Python did not give me an error when broadcasting, but Ropsten EtherScan does not show my transaction. I have waited several minutes, so mining delay is not the reason. And apparently this transaction did not go through because after checking the contract variable value, it is still the old value.

So what went wrong? Please help. Thank you.

Reference: http://web3py.readthedocs.io/en/latest/web3.eth.html#web3.eth.Eth.sendRawTransaction

Best Answer

Your problem could be that you are using a wrong nonce, instead of setting it manually, you can use in web3py:

nonce = w3.eth.getTransactionCount('your account address')

hope this helps