Created
July 26, 2023 00:55
-
-
Save malonehedges/ad3c5e21c9f232296004ab3c271ed303 to your computer and use it in GitHub Desktop.
This file contains 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 uniswapV3PoolABI = [ | |
{ | |
inputs: [], | |
name: 'slot0', | |
outputs: [ | |
{ internalType: 'uint160', name: 'sqrtPriceX96', type: 'uint160' }, | |
{ internalType: 'int24', name: 'tick', type: 'int24' }, | |
{ internalType: 'uint16', name: 'observationIndex', type: 'uint16' }, | |
{ | |
internalType: 'uint16', | |
name: 'observationCardinality', | |
type: 'uint16', | |
}, | |
{ | |
internalType: 'uint16', | |
name: 'observationCardinalityNext', | |
type: 'uint16', | |
}, | |
{ internalType: 'uint8', name: 'feeProtocol', type: 'uint8' }, | |
{ internalType: 'bool', name: 'unlocked', type: 'bool' }, | |
], | |
stateMutability: 'view', | |
type: 'function', | |
}, | |
] as const | |
const uniswapV3USDCPoolAddress = '0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640' | |
export const useETHPrice = (decimalPlaces = 2) => { | |
const { data } = useContractRead({ | |
abi: uniswapV3PoolABI, | |
address: uniswapV3USDCPoolAddress, | |
chainId: 1, | |
functionName: 'slot0', | |
}) | |
return useMemo(() => { | |
if (data === undefined) return undefined | |
const usdcDecimals = 6n | |
const ethDecimals = 18n | |
const num = BigInt(2) ** BigInt(192) | |
const num2 = | |
num * 10n ** (ethDecimals - usdcDecimals + BigInt(decimalPlaces)) | |
const squared = data[0] * data[0] | |
const resBig = num2 / squared | |
const result = Number(resBig) / 10 ** Number(decimalPlaces) | |
return result | |
}, [data, decimalPlaces]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment