Web3.py – Making an ERC20 Transfer Using Python

erc-20pythontransferweb3.py

how to send an erc20 in web3py please, I have that :

tx_hash = contract.functions.transfer(destination_address, value).transact({'from': myaddress })

and I get this error :

ValueError: {'code': -32601, 'message': 'The method eth_sendTransaction does not exist/is not available'}

I guess am missing signing that or something like that, how can I make a successful erc20 transfer.

Best Answer

transact() asks the node to sign your transaction using eth_sendTransaction. Infura can't do that, because they don't have your keys.

Instead, you can use the contract object to create an unsigned transaction like:

contract_call = contract.functions.transfer(destination_address, value)
unsigned_txn = contract_call.buildTransaction({'chainId': 1, 'gasPrice': w3.toWei(100, 'gwei')})

Then you can sign the transaction with your private key, and broadcast it:

signed_txn = w3.eth.account.sign_transaction(unsigned_txn, private_key=private_key)
w3.eth.sendRawTransaction(signed_txn.rawTransaction)