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');

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(

  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,
          chainId: 56 // BSC Mainnet Chain ID

  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)


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,

1 Answer 1


I may be wrong but let me give you a note here, for every transaction with chain funds like bnb or eth or matic the call would be with different format,

let me share the code which i used for mainnet funds.

          { from: fromaccount, value: web3Instance.utils.toWei(amount)},
          (error, result) => {

        .on("receipt", function (receipt) { });

please try in this format for mainnet, and i guess this works for tokens and this works only if the wallet has approval for the specific token with pancakeswap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.