Jasperan
Jasperan

Reputation: 3786

Uniswap getAmountsOut() rounds value down to nearest Ether

I'm calling getAmountsOut() from the UniswapV2Router02 contract using ethers.js, where I'm checking the amount of ETH I can get for 50000 DAI.

Using the below code, the output amount tells me I can currently get exactly 15 ETH. For testing purposes I'm using the Uniswap contract directly instead of the Uniswap SDK.

const UNISWAPV2_ROUTER02_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
const UNISWAPV2_ROUTER02_ABI = [{ "inputs": [{ "internalType": "uint256", "name": "amountIn", "type": "uint256" }, { "internalType": "address[]", "name": "path", "type": "address[]" }], "name": "getAmountsOut", "outputs": [{ "internalType": "uint256[]", "name": "amounts", "type": "uint256[]" }], "stateMutability": "view", "type": "function" }]

const DAI_ADDRESS = "0x6b175474e89094c44da98b954eedeac495271d0f";
const WETH_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";

const uniswap = new ethers.Contract(
    UNISWAPV2_ROUTER02_ADDRESS,
    UNISWAPV2_ROUTER02_ABI,
    ethers.provider,
);

let amountEthFromDAI = await uniswap.getAmountsOut(
    50000,
    [DAI_ADDRESS, WETH_ADDRESS]
)

console.log("Amount of ETH from DAI: ", amountEthFromDAI[1]);

However on the actual Uniswap interface it's telling me I can get a total of 15.8832 ETH which is significantly more.

Uniswap ETH output from DAI

It seems getAmountsOut() is rounding down to the nearest Ether. How can I get the output amount in units of wei so it accurately reflects what I see on the Uniswap interface?

Upvotes: 4

Views: 5680

Answers (1)

Jasperan
Jasperan

Reputation: 3786

In order for getAmountsOut() to return a value in wei, you need to provide a value in wei.

So instead of using 50000 for amountsIn, use ethers.utils.parseEther("50000") :

let amountEthFromDai = await uniswap.getAmountsOut(
    ethers.utils.parseEther("50000"),
    [DAI_ADDRESS, WETH_ADDRESS]
)

Upvotes: 3

Related Questions