1

Hi I have code that fetches price from uniswap v2

ratio0ToPrice = (amount0In, amount1Out) => {
  if (Number(amount1Out) === 0) {
    return "Infinity"; 
  }
  return 1 / (Number(amount0In) / Number(amount1Out) / 10 ** 12);
};

var provider = new ethers.JsonRpcProvider(
  `https://eth-mainnet.g.alchemy.com/v2/${process.env.API_KEY}`
);
var WETH_USDC_V2 = "0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc";

var v2PairArtifact = require("@uniswap/v2-periphery/build/IUniswapV2Pair.json");

var v2Pair = new ethers.Contract(WETH_USDC_V2, v2PairArtifact.abi, provider);

async function PriceUpdate() {
  try {var latestBlockNumber = await provider.getBlockNumber();

    var [reserve0, reserve1, blockTimestampLast] = await v2Pair.getReserves();
    var uniswapPrice = ratio0ToPrice(reserve1, reserve0);
    console.log(latestBlockNumber);
    console.log(
      "Uni V2",
      "|",
      "pair:",
      "WETH/USDC",
      "|",
      "price:",
      uniswapPrice,
      blockTimestampLast
    );
  } catch (error) {
    console.error(error);
  }
}

const interval = 6000; // 5 seconds

setInterval(PriceUpdate, interval);

And this console log price in format like this:

Uni V2 | pair: WETH/USDC | price: 2343.9730179787334 1702169315n

And i have few questions associated with prices.

1.Its normal that this code can multiple times console log the same price for example this can take up to 20 sec to refresh price (i think the movements on popular trading pairs like this should be higher and price should be changing faster after one or two console logs but not sometimes after 10 times.

2.Why price on GeckoTerminal(yes i selected uniswap v2 pair) its sometimes different i mean price can be few dollars different than prices console logged by ma code.

3.How popular dexes like uniswap and sushiswap calculate price?Like my code which take reserves pool or in different kind because i said earlier but prices on services like GekoTerminal have different live prices on uniswap.I should more trust my code or other live price services when executing swap on smart contract ?

2 Answers 2

1
  1. Price can change only between blocks. On ethereum a block lasts 12 seconds, during which the price doesn't change. Also if no trade happens in a block, the price still doesn't change.

  2. You're calculating the price in USDC, GeckoTerminal in USD (I believe). You can check that if you account for the difference between USDC and USD (sometimes 1 USDC = 0.999 USD) you'll get closer results.

  3. Maybe it's better to aggregate among multiple sources. Your price works well, but it's possible that a large trade skewed the price recently. Arbitrage bots will soon move the price towards the aggregate one in any case.

4
  • I have one more question does UniswapV2 swapExactTokensForTokens function charge fees ? And if yes does expected amount input should be like this Expected price after fee subtraction?
    – Xardesso
    Dec 10, 2023 at 14:41
  • And whats mean its better to aggregate among multiple sources.I heard about uniswap v2 sdk but i tried to use this but this dont work its exist other ways to fech live prices ?
    – Xardesso
    Dec 10, 2023 at 14:43
  • swapExactTokensForTokens charges the normal 0.3% fee for the LP, common to all uniswapV2 pairs. Yes, you should account for this fee when writing the minimum amount. You can have a look at the math here github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/…, by writing this function in javascript you'll get the swap amount out given the reserves.
    – 0xSanson
    Dec 10, 2023 at 21:41
  • I think the most basic way is to have a list of the most liquid exchanges, like Uniswap, Curve and Sushiswap, and make an average on those. I don't know how GeckoTerminal or dexscreener work, but if they have a global price of a token, then they must do an average on the various dex.
    – 0xSanson
    Dec 10, 2023 at 21:48
0

1.Its normal that this code can multiple times console log the same price for example this can take up to 20 sec to refresh price (i think the movements on popular trading pairs like this should be higher and price should be changing faster after one or two console logs but not sometimes after 10 times.

The speed of JSON-RPC calls depends on how quality JSON-RPC node you are running. Run a local node and the functions will run in couple of milliseconds.

2.Why price on GeckoTerminal(yes i selected uniswap v2 pair) its sometimes different i mean price can be few dollars different than prices console logged by ma code.

Likely because the price is changing all the time and may be fee-inclusive or fee-exclusive.

3.How popular dexes like uniswap and sushiswap calculate price?Like my code which take reserves pool or in different kind because i said earlier but prices on services like GekoTerminal have different live prices on uniswap.I should more trust my code or other live price services when executing swap on smart contract ?

Usually prices are reported as mid price but different platform may use different basis of the price calculation, as discussed above.

Because GeckoTerminal is a closed source service, no one on this forum can comment how they calculate the price.

5
  • 1
    1.I tried to run own node but this require 2TB SSD.But you know maybe other kind of solution,maybe exist faster node service? 2.So you mean that this kind of service can post price other than uniswap calulate(using ration reserves). 3.I find information that price is based on ratio of reserves so i should trust my code
    – Xardesso
    Dec 10, 2023 at 13:19
  • You can find better JSON-RPC providers here: ethereumnodes.com Dec 10, 2023 at 14:58
  • For 2. GeckoTerminal can post any price what they want and we do not know how they calculate it, so trust your reserve calculation based code more. Dec 10, 2023 at 14:59
  • I have one more question does UniswapV2 swapExactTokensForTokens function charge fees ? And if yes does expected amount input should be like this Expected price after fee subtraction?
    – Xardesso
    Dec 10, 2023 at 16:04
  • Yes. You can find different Uniswap v2 fee calculation examples here. Dec 11, 2023 at 7:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.