2

我试图批准并稍后通过 web3py 代码在 uniswap 上交换我的令牌。我也在使用 infura,而不是我自己的节点。但是,在交换和批准时,我都遇到了solidityErrors。问题是 web3 无法识别我的帐户,即使我签署了 tx 并将我的私钥传递给它。关于如何让 web3 识别我的钱包的任何想法?

这是我的批准功能代码。

def approve(self,token_name):

    my_token = token(token_name)
    contract = my_token.createContract()
    spender = uni_router_address
    max_amount = web3.toWei(2**64-1,'ether')
    nonce = web3.eth.getTransactionCount(account)

    tx = contract.functions.approve(spender,max_amount).buildTransaction({'nonce': nonce})
    signed_tx = web3.eth.account.signTransaction(tx, self.pkey)
    gas = signed_tx.estimateGas()
    print(gas)

    return

我在估算气体,所以我知道在发送之前要使用多少气体。我知道我需要使用 sendRawTransaction 作为本地私钥。文档并不清楚如何与现有智能合约的本地私钥进行交互。

4

1 回答 1

4
def approve(token, spender_address, wallet_address, private_key):

  spender = spender_address
  max_amount = web3.toWei(2**64-1,'ether')
  nonce = web3.eth.getTransactionCount(wallet_address)

  tx = token.functions.approve(spender, max_amount).buildTransaction({
      'from': wallet_address, 
      'nonce': nonce
      })
    
  signed_tx = web3.eth.account.signTransaction(tx, private_key)
  tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)

  return web3.toHex(tx_hash)

使用您的私钥签名后,您需要将原始交易发送出去以将其广播到区块链。

于 2021-06-13T21:29:26.713 回答