如何批准代币用于支出(Uniswap 路由器合约)

ran*_*ack 6 python ethereum web3py

我正在尝试批准并稍后通过 web3py 代码在 uniswap 上交换我的代币。我也在使用infura,而不是我自己的节点。然而,在交换和批准时我都遇到了 SolidityErrors。问题是,即使我签署了交易并将我的私钥传递到其中,web3 也无法识别我的帐户。关于如何让 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
Run Code Online (Sandbox Code Playgroud)

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

小智 6

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)
Run Code Online (Sandbox Code Playgroud)

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