Last active
October 10, 2024 19:05
-
-
Save mikekoro/c061b0285eda15d3dbed970908f60686 to your computer and use it in GitHub Desktop.
Get ETH and SX prices from Uniswap v3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rpcUrl = CHAIN_CONFIGS[1].rpcUrls[0]; | |
const provider = new providers.StaticJsonRpcProvider(rpcUrl, 1); | |
const UniswapV3Pool = await import('../../config/abi/UniswapV3Pool.json'); | |
const sxUsdcPoolAddress = "0xCb3b931E1e02C26399aCc651bFD9c8c4385EECd0"; | |
const ethUsdcPoolAddress = "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8"; | |
const sxUsdcPoolContract = new Contract(sxUsdcPoolAddress, UniswapV3Pool.abi, provider); | |
const ethUsdcPoolContract = new Contract(ethUsdcPoolAddress, UniswapV3Pool.abi, provider); | |
const [sxSlot0, ethSlot0] = await Promise.all([ | |
sxUsdcPoolContract.slot0(), | |
ethUsdcPoolContract.slot0() | |
]); | |
// Calculate price for SX/USDC | |
const sqrtPriceX96SX = sxSlot0.sqrtPriceX96; | |
const priceX96SquaredSX = (sqrtPriceX96SX ** 2) / (2 ** 192); | |
const adjustedPriceSX = priceX96SquaredSX * (10 ** 6) / (10 ** 18); // 6 decimals for USDC, 18 decimals for SX | |
const priceOfSXInUSDC = 1 / adjustedPriceSX; | |
// Calculate price for ETH/USDC | |
const sqrtPriceX96ETH = ethSlot0.sqrtPriceX96; | |
const priceX96SquaredETH = (sqrtPriceX96ETH ** 2) / (2 ** 192); | |
const adjustedPriceETH = priceX96SquaredETH * (10 ** 6) / (10 ** 18); // 6 decimals for USDC, 18 decimals for ETH | |
const priceOfEthInUSDC = 1 / adjustedPriceETH; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment