Skip to content

Instantly share code, notes, and snippets.

@monokh
Last active March 21, 2023 09:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save monokh/5dc494b9fb7887ac02d6898b6458648c to your computer and use it in GitHub Desktop.
Save monokh/5dc494b9fb7887ac02d6898b6458648c to your computer and use it in GitHub Desktop.
Uniswap V2 SDK Get Price
const { Token, WETH9, CurrencyAmount, TradeType } = require('@uniswap/sdk-core')
const { Route, Trade, Pair } = require('@uniswap/v2-sdk')
const ethers = require('ethers')
;(async () => {
const CHAIN_ID = 1
const daiAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'
const tokenA = WETH9[CHAIN_ID]
const tokenB = new Token(CHAIN_ID, daiAddress, 18, 'DAI', 'DAI')
const pairAddress = Pair.getAddress(tokenA, tokenB)
const api = new ethers.providers.InfuraProvider(CHAIN_ID, '<MY INFURA KEY>')
const contract = new ethers.Contract(pairAddress, [
'function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)',
'function token0() external view returns (address)',
'function token1() external view returns (address)'
], api)
const reserves = await contract.getReserves()
const token0Address = await contract.token0()
const token1Address = await contract.token1()
const token0 = [tokenA, tokenB].find(token => token.address === token0Address)
const token1 = [tokenA, tokenB].find(token => token.address === token1Address)
const pair = new Pair(
CurrencyAmount.fromRawAmount(token0, reserves.reserve0.toString()),
CurrencyAmount.fromRawAmount(token1, reserves.reserve1.toString())
)
const route = new Route([pair], tokenA, tokenB)
const tokenAmount = CurrencyAmount.fromRawAmount(tokenA, '1000000000000000000')
const trade = new Trade(route, tokenAmount, TradeType.EXACT_INPUT)
console.log('execution price', trade.executionPrice.toSignificant(6))
})()
@PaleHazy
Copy link

Hi! On line 21 && 22, are you doing this because you want to make sure that the contract instance is delivering the same information you initially feed it?

@monokh
Copy link
Author

monokh commented Jun 14, 2021

Hi! On line 21 && 22, are you doing this because you want to make sure that the contract instance is delivering the same information you initially feed it?

The point is to match the reserve amount to the correct token.

Let's assume we are trying to get the execution price for ETH -> DAI
TokenA: ETH
TokenB: DAI

In the pair contract for these 2 assets, the tokens are actually like this:
Token0 (reserve0): DAI
Token1 (reserve1): ETH

Therefore, simply assigning tokenA = reserve0 gives you the wrong reserve amounts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment