[Ethereum] Uniswap Price Feed.- Get price of a Token in a Solidity contract

erc-20solidityuniswap

I am looking to retrieve the current price of a token from Uniswap. I have successfully used the ChainLink oracle api to get the price of BTC/USD, but I want to now integrate Uniswap price feeds.

I cannot seem to find one that just retrieves the current price of a token in ETH. Has anybody ever attempted this before?

Best Answer

Uniswap has an SDK through which you can fetch the gas price. See their example in their documentation :

    import { ChainId, Token, WETH, Fetcher, Route } from '@uniswap/sdk'
    
    const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)
    
    // note that you may want/need to handle this async code differently,
    // for example if top-level await is not an option
    const pair = await Fetcher.fetchPairData(DAI, WETH[DAI.chainId])
    
    const route = new Route([pair], WETH[DAI.chainId])
    
    console.log(route.midPrice.toSignificant(6)) // 201.306
    console.log(route.midPrice.invert().toSignificant(6)) // 0.00496756
Related Topic