[Ethereum] How to fetch current pair prices through uniswap-v2 API

exchange-apipriceuniswap

I need to quote online prices of different token pairs through uniswap-v2 API. As the below picture shows, I tend to pass token pair (maybe with base token desired amount) to the API and get all price related values as result.

enter image description here

I found Fetcher.fetchPairData method in uniswap documentions, but it does not return the correct values. Am I using the correct method or I have to use another method for this purpose?

Best Answer

Sticking to Uniswap SDK terms, a "pair price" strictly speaking does not exist. The closest thing to it is the MidPrice of a given Route.

However, your screenshot indicates that what you're really looking for is the ExecutionPrice of a Trade:

import { ChainId, Token, WETH, Fetcher, Trade, Route, TokenAmount, TradeType } from '@uniswap/sdk'

const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)
const pair = await Fetcher.fetchPairData(DAI, WETH[DAI.chainId])    
const route = new Route([pair], WETH[DAI.chainId])    
const trade = new Trade(route, new TokenAmount(WETH[DAI.chainId], '1000000000000000000'), TradeType.EXACT_INPUT)

console.log(trade.executionPrice.toSignificant(6))