Web3js

從 truffle dev 到 python 語言執行

  • April 4, 2020

我在 truffle 開發控制台中成功執行了智能合約功能,例如:

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

我在我的帳戶中獲得了“硬幣”

$$ 1 $$. 但問題是當我嘗試使用 python 時,它給出了一個錯誤。

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

這是我的sendCoin功能:

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;
}

試試這個:

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

來自官方文件

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

引用自:https://ethereum.stackexchange.com/questions/82124