[Ethereum] PancakeSwap V2 swapExactTokensForTokens not working, getting stuck

contract-invocationethers.jsnodejspancakeswapswaps

I am unable to get this working with ethers.js. I know there are many similar questions for this specific topic, but none of the answers seem to work for me. My attempt is mostly based on Noob Troubleshooting failed BSC transaction using ethers.js and Pancakeswap v2 router.

My code is the following:

const ethers = require('ethers');

const addresses = {
    WBNB: '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c',
    BUSD: '0xe9e7cea3dedca5984780bafc599bd69add087d56',
    factory: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73',
    router: '0x10ed43c718714eb63d5aa57b78b54704e256024e',
    recipient: '0xE00e552a0e18ca773a26f65cE957915D302CBE10'
}

const PRIVATE_KEY = ""

const mygasPrice = ethers.utils.parseUnits('5', 'gwei');

const WSS = "wss://*.bsc.quiknode.pro/*/"
const provider = new ethers.providers.WebSocketProvider(WSS);

const wallet = new ethers.Wallet(PRIVATE_KEY);
const account = wallet.connect(provider);

const router = new ethers.Contract(
    addresses.router,
    [
        'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
    ],
    account
);


const init = async () => {
    console.log("Test TX");

    let tokenIn = addresses.WBNB, tokenOut = addresses.BUSD;

    const amountIn = ethers.utils.parseUnits('0.0005', 'ether');
    const amountOutMin = 0;

    console.log("Starting swap...");

    const tx = await router.swapExactTokensForTokens(
        amountIn,
        amountOutMin,
        [tokenIn, tokenOut],
        addresses.recipient,
        Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
        {
            gasPrice: mygasPrice,
            gasLimit: 500000
        }
    );
    console.log("Swap done!");
    const receipt = await tx.wait();
    console.log("Transaction receipt");
    console.log(receipt);
}

init();

When I run this code, it gets stuck.

Test TX
Starting swap...

The wallet generated from the private key is the same as the recipient address (0xE00e552a0e18ca773a26f65cE957915D302CBE10), and there is enough WBNB balance. I just tried to do a manual swap on pancakeswap V2 (WBNB to BUSD) and it worked flawlessly (https://bscscan.com/tx/0xe3351e82ed4a86e18e164ba47b44bb7fa74faaeda67f8b7e3486f6410e5b50b9).

I am currently out of ideas, and I don't know how to debug this further.

Thanks for your help.

Best Answer

You need to call swapExactETHForTokens for swapping WBNB to a token, NOT swapExactTokensForTokens. swapExactTokensForTokens is for swapping a non-BNB token to another non-BNB token. (At least, that is what I can think of.)

Related Topic