0

I'm trying to replicate the PancakeswapV2 getAmountOut function in Javascript using ethers.BigNumbers as follows (the code in the comment is ad-verbatum from PancakeswapLibrary)

function getTokensOut(_amountIn, _reserve0, _reserve1) {
        /*
            getAmountOut
            uint amountInWithFee = amountIn.mul(998);
            uint numerator = amountInWithFee.mul(reserveOut);
            uint denominator = reserveIn.mul(1000).add(amountInWithFee);
            amountOut = numerator / denominator;
        */
        const amountInWithFee = _amountIn.mul(ethers.BigNumber.from(998))
        const numerator = amountInWithFee.mul(_reserve1)
        const denominator = _reserve0.mul(1000).add(amountInWithFee)
        return numerator.div(denominator)
    }
}

For whatever reason, however, the values returned from the above function are quite a bit different from those returned from the Solidity code using the same input (or via Pancake Router, or using an "infinite" precision calculator [which btw, gives the same result as Solidity]

For instance:

_amountIn: 500000000000000000
_reserve0: 508182386709642941160
_reserve1: 138068946110314350251292627

Using the above function returns:

135441173805663861743470

but Solidity / Pancake Router / Infinite Precision Calculator all return

135373384037682332659863

What's the explanation for this, and more importantly, how does the above Javascript function need to be corrected for it to return the correct results?

1 Answer 1

1

Found the problem: the Pancakeswap Library on github uses 998/1000 to calculate the fees, but the deployed contract uses 9975/10000. With this adjustment the function is working fine.

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.