starkm
starkm

Reputation: 1029

Sell Function on Pancakeswap with Ether Library on Node.js

I am trying to swap my busd tokens for bnb (wbnb) by using pancakeswap router v2 on testnet. Though I am having CALL_EXCEPTION.

Before I dive into code, I have the same issue on bscscan. I don't know if it's related but, even though I successfully approve the contract, it still returns 0 for allowance. Here's the method I try, that I got the values from my code. Total pay amount (amount + gas fee) doesn't change, no matter the inputs.

swapExactTokensForEth failure image

Here's my assets in testnet.

Testnet Assets

amountIn value is filled with busdContract.balanceOf method's return value

const abi = await retrieveAbi(tokenIn);
erc = new ethers.Contract(
    tokenIn,
    abi,
    account
);

const balance = await erc.balanceOf(process.env.WALLET_ADDRESS);

amountOutMin is calculated by pancakeswapRouter.getAmountsOut method

let amountOutMin = 0;
if (parseInt(slippage) !== 0) {
    const amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);
    amountOutMin = amounts[1].sub(amounts[1].mul(slippage).div(100));
}

return amountOutMin;

approveToken:

const tx = await erc.approve(
        tokenIn,
        tokenAmount,
        {
            gasPrice: gasPrice,
            gasLimit: gasLimit
        }
    );

    const receipt = await tx.wait();

Sell function (where it actually throws CALL_EXCEPTION error):

const tx = await router.swapExactTokensForETH(
        amountIn,
        amountOutMin,
        [tokenIn, tokenOut],
        process.env.WALLET_ADDRESS,
        Date.now() + 1000 * 60 * 5, // 5 minutes
        {
            gasPrice: gasPrice,
            gasLimit: gasLimit
        }
    );

    const receipt = await tx.wait();

I also tried giving a custom amount, and calculate it using the retrieved abi's (busd abi) decimals value, but no luck; it gives the same error: CALL_EXCEPTION.

const amountIn = ethers.utils.parseUnits('100', decimals);

Neither error message nor failed transaction gives me any clue. It only says code=CALL_EXCEPTION. This leads me nowhere.

I suspect the problem is about approval & allowance. Even though approval transaction is succeeded, my wallet's busd allowance is always zero. Many thanks in advance.

Here's the variables, seen in images:

211064843184329663888 amountIn
468509127086739224 amountOutMin
0x8301f2213c0eed49a7e28ae4c3e91722919b8b47 tokenIn (BUSD)
0xae13d989dac2f0debff460ac112a837c89baa7cd tokenOut (WBNB)

Upvotes: 1

Views: 1988

Answers (1)

starkm
starkm

Reputation: 1029

I found the problem. I was putting the address of input token when approving the amount. So that was the reason why allowance is zero!

Upvotes: 0

Related Questions