[Ethereum] Execute smart contract function on python

pythonweb3.py

so I already successfully make a smart contract and deployed it on my BC network. I can execute the function using the Ethereum wallet. My question is, how can I execute the functions on Python language? For example, here is one function of my SC:

function withdrawToken(address recipient, uint value) returns (bool success) { 
    if (int(tokens[recipient] - value) < 0) { 
        tokens[recipient] = 0; 
    } else { 
        tokens[recipient] -= value; 
    } 
    OnValueChanged(recipient, tokens[recipient]); 
    return true; 
} 

For making a transaction in Python language, I'm using web3 library and it's also already worked. I'll really appreciate your help, thanks!

Best Answer

The relevant piece of documentation is here

You'll need to get the contract ABI from somewhere, either by having it from when you deployed, or using a different tool. Once you have that, you can use web3.py to load it:

store_var_contract = w3.eth.contract(
   address=address,
   abi=contract_interface['abi'])

You can then call the function in the contract using the variable you assigned the contract. The example in the docs includes how to estimate the gas and more.

So, if you load your contract using the snippet above, and you want to call a function withdrawToken(), you could then use something like:

tx_hash = store_var_contract.functions.withdrawToken(0x..., 50).transact()
receipt = w3.eth.waitForTransactionReceipt(tx_hash)

Where 0x... is the address you wanted, and 50 is a random number I picked for the amount, and should be replaced by a number of your choice. (Unless you coincidentally wanted 50.)

I'm going out on a limb here, but I have a suspicion part of the issue may be that you've already deployed the contract, and don't have its ABI. A few quick solutions may include using the Solidity compiler to get the ABI (solc --abi YourContract.sol if you already have it installed), or if you know where an identical contract is deployed on a test chain or mainnet, getting its ABI from etherscan.

Related Topic