How to approve a token for spending on (Uniswap router contract)

Viewed 10856

Im trying to approve and later on swap my tokens on uniswap via web3py code. I am also using infura, not my own node. However, on both the swap and the approve I run into solidityErrors. The problem is that web3 does not recognize my account even though I sign the tx and pass my private key into it. Any ideas on how to get web3 to recognize my wallet?

Heres my code for the approve function.

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

Im estimating gas so I know how much gas to use before I send it. Im aware I need to use sendRawTransaction for local private keys. Docs aren't really clear on how to interact with local private keys to existing smart contracts.

1 Answers
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)

After signing with your private key, you need to send the raw transaction out to broadcast it to the blockchain.

Related