I successfully execute smart contract function in the truffle development console, for example:

let instance = await MetaCoin.deployed()
let accounts = await web3.eth.getAccounts()
instance.sendCoin(accounts[1], 10, {from: accounts[0]})

I get the "Coin" in my accounts[1]. But the problem is when I try to use python, it gives an error.

contractAddress = '0x...'
abi = '...'
contract = w3.eth.contract(contractAddress, abi=abi)
contract.functions.sendCoin(accounts[1], 10, {from: accounts[0]})


contract.functions.sendCoin(accounts[1], 10, {from: accounts[0]})
SyntaxError: invalid syntax

This is my sendCoin function:

event Transfer(address indexed _from, address indexed _to, uint256 _value);

function sendCoin(address receiver, uint amount) public returns(bool sufficient) {
    if (balances[msg.sender] < amount) return false;
    balances[msg.sender] -= amount;
    balances[receiver] += amount;
    emit Transfer(msg.sender, receiver, amount);
    return true;

Try this:

contract.functions.sendCoin(accounts[1], 10).transact({"from": accounts[0]})

From official docs

Execute the specified function by sending a new public transaction.

Refer to the following invocation:

myContract.functions.myMethod(*args, **kwargs).transact(transaction)
The first portion of the function call myMethod(*args, **kwargs) selects the appropriate contract function based on the name and provided argument. Arguments can be provided as positional arguments, keyword arguments, or a mix of the two.

The end portion of this function call transact(transaction) takes a single parameter which should be a python dictionary conforming to the same format as the web3.eth.sendTransaction(transaction) method. This dictionary may not contain the keys data.

If any of the args or kwargs specified in the ABI are an address type, they will accept ENS names.

If a gas value is not provided, then the gas
  • Thanks! It worked now!! – Kevin Apr 8 '20 at 11:44

Python dictionary keys must be given as strings. Where your code says from, it should say "from":

contract.functions.sendCoin(accounts[1], 10, {"from": accounts[0]})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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