I'm trying to implement token swap in nodejs using web3 library on the pancakeswap router. I'm able to perform this swap using the pancakeswap webpage but unable to do this programmatically. I'm using a paid quicknode BSC node. Here is the code for the swap:
const pancakeSwapRouterAddress = '0x10ed43c718714eb63d5aa57b78b54704e256024e';
const web3 = new Web3(providerUrl); // BSC Mainnet
const routerAddress = pancakeSwapRouterAddress; // PancakeSwap Router Address
const privateKey = process.env.PRIVATE_KEY; // Your Wallet's Private Key
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
const routerABI = require('../abis/routerABI.json');
web3.eth.accounts.wallet.add(account);
const pancakeRouter = new web3.eth.Contract(routerABI, routerAddress);
async function swapTokens(tokenIn, tokenOut, amountIn, to) {
const amountOutMin = '0'; // Set minimum amount of tokenOut to receive (after slippage)
const path = [tokenIn, tokenOut];
const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 minutes from the current time
const tx = pancakeRouter.methods.swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
to,
deadline
);
const gasPrice = await web3.eth.getGasPrice();
const gas = await tx.estimateGas({ from: account.address, to: routerAddress });
const data = tx.encodeABI();
const nonce = await web3.eth.getTransactionCount(account.address);
const signedTx = await web3.eth.accounts.signTransaction(
{
from: account.address,
to: routerAddress,
data,
gas,
gasPrice,
nonce,
chainId: 56 // BSC Mainnet Chain ID
},
privateKey
);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
return receipt;
}
async function getBNBBalance(address) {
try {
let balance = await web3.eth.getBalance(address);
// Convert Wei to BNB
balance = web3.utils.fromWei(balance, 'ether');
console.log(`The BNB balance of ${address} is: ${balance} BNB`);
} catch (error) {
console.error(`An error occurred: ${error.message}`);
}
}
async function main() {
const valueInEther = '0.001'; // Value in ether
const valueInWei = web3.utils.toWei(valueInEther, 'ether');
const address = account.address;
await getBNBBalance(address);
const bnbAddress = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c'
const cakeAddress = '0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82'
swapTokens(bnbAddress, cakeAddress,valueInWei, address)
}
main()
I've approved the BNB token programatically so I'm not sure where is the problem. Here is the error I'm getting:
innerError: [Eip838ExecutionError: execution reverted: TransferHelper: TRANSFER_FROM_FAILED] {
innerError: undefined,
code: 3,
receipt: undefined,
data: '0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000245472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c454400000000000000000000000000000000000000000000000000000000'
},
code: 310,