首页 > 解决方案 > web3.py:将以太币发送到智能合约

问题描述

我正在使用web3.py与私有以太坊区块链进行交互。我想在智能合约中调用以下函数:

    uint256 public cookiePrice;

    function feed(string memory message) public payable {
        require(cookiePrice <= msg.value);
        applyFeeding(msg.sender, message);
    }

我试图这样称呼它:

    price = contract.functions.cookiePrice().call()
    txn = contract.functions.feed("my message").buildTransaction({
      'chainId': 13999911119,
      'gas': 70000,
      'value': price,
      'gasPrice': w3.toWei('8', 'gwei'),
      'nonce': int(time.time())
    })
    signed_txn = w3.eth.account.sign_transaction(txn, private_key=private_key)
    w3.eth.sendRawTransaction(signed_txn.rawTransaction)

这似乎成功了,因为它sendRawTransaction返回了事务的哈希(如文档中所述)。但是我可以在链上看到调用实际上并没有生效。

上面的代码有什么明显的缺失吗?另外,我怎样才能得到sendRawTransaction帮助我调试的回报?

标签: pythonethereumweb3

解决方案


您的交易可能从未被挖掘,因为您的 nonce 太高了。一个账户的随机数从 0 开始,每发送一个交易就增加 1。

您可以使用w3.eth.getTransactionCount为您正在使用的帐户获取正确的随机数。


推荐阅读