Web3.py – Sending a Transaction to a Payable Contract Function

contract-invocationweb3.py

I have deployed a smart contract dthat contains a payable function fundit(address _to). Now I am trying to use a Contract object to send ether to the function:

tx_hash = instance.fundit.sendTransaction(instance2.address, {"from": w3.eth.accounts[0], "value": 1})

However, I am receiving the following error:

'Contract' object has no attribute 'fundit'

How can I solve this?

Best Answer

Assuming instance is a Contract object, classes for calling contract functions are found inside the Contract.function member. The correct syntax for what you wish to do is:

contract_function = instance.functions.fundit(instance2.address)
tx_hash = contract_function.transact({"from": w3.eth.accounts[0], "value": 1})
  1. In the first line, you invoke the ContractFunction with the inputs you wish to use in the transaction.
  2. In the second line, you call the ContractFunction.transact method to perform the transaction. The only argument should be a transaction dictionary.

You can of course merge these two lines into one, I only separated them to make the example easier to read.

Related Topic