Hi I am using web3py with infura as a provider and I couldn’t find out how to send erc20 tokens.
Can any one help me please.
Thank you.
Hi @mouihbi - welcome to the Infura community! The Web3.py docs have a good writeup of getting set up. If you get stuck, this thread has some basic errors you may encounter as you set up.
@mouihbi hope this help you. Its in node js but you can use it in Python just follow the logic.
/**
- Transfer ERC20 Tokens
- @param decimals
- @param to
- @param amount
- @param secret
*/public async transferErc20Tokens(
decimals,
to: string,
amount,
secret: string,
cb,
) {
try {
const account = this.web3.eth.accounts.privateKeyToAccount(secret);
this.web3.eth.accounts.wallet.add(account);
this.web3.eth.defaultAccount = account.address;
const contract = new this.web3.eth.Contract(this.abi, this.tokenAddress);
const gasPriceGwei = await this.getNetworkGasFee();
const amountBigNo: any = new BigNumber(amount.toString());
const decimalsBigNo: any = new BigNumber(decimals.toString());
const amountBigNoResult: any = amountBigNo.multipliedBy(decimalsBigNo);
const valueNew = this.web3.utils.toHex(amountBigNoResult.toString());
const addressBalance = await this.getEthBalance(account.address, true);>
let gas: any = await this.getTransferGasestimation(
contract,
account.address,
gasPriceGwei,
to,
valueNew,
);
gas = gas + parseInt(process.env.ERC20_TX_GAS_BUFFER);
const maxGasInWei: any = gasPriceGwei * gas;
const gasInETH = await this.weiToEther(maxGasInWei);const nonceVal: number = "get latest nonce of from address" ; contract.methods .transfer(to, valueNew) .send({ from: this.web3.eth.defaultAccount, gas: this.web3.utils.toHex(gas), gasPrice: this.web3.utils.toHex(gasPriceGwei), nonce: this.web3.utils.toHex(nonceVal), }) .on('transactionHash', async (hash) => { console.log(hash); }) .on('error', async (error) => { console.log('\n .send() error: ', error); cb(error.message, null); }); } } catch (error) { console.log('\n transferErc20Tokens fun error: ', error); cb(error.message, null); }