5

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
randoTrack
  • 83
  • 1
  • 3
  • 6

1 Answers1

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)

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

Mak Hon Keat
  • 187
  • 5
  • 12
  • Im having trouble getting approval transaction submitted. Any idea why? I keep getting "web3.exceptions.TimeExhausted: Transaction HexBytes('0x...') is not in the chain after 120 seconds" https://ethereum.stackexchange.com/questions/122201/web3-py-how-to-get-status-from-erc20-approve – TaeWoo Feb 22 '22 at 08:11
  • private_key to pass is for spender_address or wallet_address – Aman Khandelwal Aug 22 '23 at 06:17