Search code examples
typescriptblockchainethereumerc20

Get proper sell price from Uniswap V2


I was able to fetch proper trade result of swapping 1 WETH to DAI using Uniswap v2 SDK.

Now I wanted to fetch how much DAI I need to provide, to get 1 WETH. To trigger this on the Uniswap Interface you simply create trade DAI -> WETH and then type 1 in the "to" input (then you get From (estimated) at the top). Unfortunately, it does not work the other way around for me. What I'm receiving is I guess result of selling 1 DAI for WETH.

How can I fix that?

export async function buySellUni() {
        const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)
        const WETH = new Token(ChainId.MAINNET, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18)
        const pair = await Fetcher.fetchPairData(DAI, WETH)
    
        const buyRoute = new Route([pair], WETH);
        const buyTrade = Trade.exactIn(buyRoute, new TokenAmount(WETH, BigInt(1E18)));
        const sellRoute = new Route([pair], DAI);
        const sellTrade = Trade.exactOut(sellRoute, new TokenAmount(WETH, BigInt(1E18)));

        console.log("Get " + buyTrade.executionPrice.toSignificant(6) + " DAI for 1 WETH");
        console.log("Need " + sellTrade.executionPrice.toSignificant(6) + " DAI to get 1 WETH");
 };

I'm using exactOut to get exact Out not In value with WETH token, but my route has been adjusted so the input is DAI not WETH.

enter image description here


Solution

  • What I'm receiving is I guess result of selling 1 DAI for WETH

    It's "how much WETH you can buy with 1 DAI". You can easily convert this number to "how much DAI you need to buy 1 WETH" by calculating (1 / X).

    console.log("Need " + (1 / sellTrade.executionPrice.toSignificant(6)) + " DAI to get 1 WETH");
    

    1 / 0.000366619 = 2727.6273188241744