I'm new to blockchain and I'm experimenting with web3.js. I tried to calculate gas for swapping WBNB for DAI and I keep getting error. Here is my code:
let routerContract = new puWeb3.eth.Contract(Config.PANCAKESWAP_ROUTER_V2_ABI, Config.PANCAKESWAP_ROUTER_V2_ADDRESS);
let tokenContract = new puWeb3.eth.Contract(Config.TOKEN_ABI, Config.WBNB_ADDRESS);
let amountIn = puWeb3.utils.toWei('0.01', 'ether');
let amountOutMin = await routerContract.methods.getAmountsOut(amountIn, [Config.WBNB_ADDRESS, Config.DAI_ADDRESS]).call();
amountIn = amountOutMin[0];
amountOutMin = amountOutMin[1];
console.log(amountIn+" WBNB ----> "+amountOutMin+" DAI");
// Set deadline 1 minute from now
let now = parseInt(Date.now()/1000);
let deadline = now + 60
// Encode data
let encodedABI = routerContract.methods.swapExactTokensForTokens(amountIn, amountOutMin, [Config.WBNB_ADDRESS, Config.DAI_ADDRESS], Config.ACCOUNT_ADDRESS, deadline).encodeABI();
//Estimate gas
let estimateGas = await puWeb3.eth.estimateGas({
from: Config.ACCOUNT_ADDRESS,
to: Config.PANCAKESWAP_ROUTER_V2_ADDRESS,
data: encodedABI,
});
And the error is: Returned error: execution reverted: TransferHelper: TRANSFER_FROM_FAILED
Can someone tell me what am I doing wrong? Thanks.
I finally managed to get estimative gas and do a trade only after I approved the input token to exchange. You need 2 transactions:
first send a transaction to approve the input token with the input amount
// Encode data let encodedABI = tokenContract.methods.approve(Config.PANCAKESWAP_ROUTER_V2_ADDRESS, puWeb3.utils.toHex(amountIn)).encodeABI();
after approve transaction, send a transaction to swap
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.