Nethereum.Uniswap-V2-and-V3
Nethereum.Uniswap-V2-and-V3 copied to clipboard
How to get current price of a pair
Hello,
I'm very new to uniswap sdk. I'm trying to figure out with this SDK. Given a contract with the pair, how can I know the current price?
Thanks
https://uniswap.org/docs/v2/advanced-topics/pricing/ https://uniswap.org/docs/v2/smart-contracts/pair/
Here is my code:
int precision = 10000000;
var getAmountsOutFunctionMessage = new GetAmountsOutFunction()
{
AmountIn = precision,
Path = GetPath() // List<>{tokenAddress, ..., usdtAddress}
};
var getAmountsOutHandler = web3.Eth.GetContractQueryHandler<GetAmountsOutFunction>();
var amounts = await getAmountsOutHandler
.QueryAsync<List<BigInteger>>(
routerAddress),
getAmountsOutFunctionMessage);
var ratio = BigDecimal.Pow(10, usdtDecimals - tokenDecimals);
var priceUsd = amounts.Last() / ratio / precision;
Remember to get the decimal difference of the token to USDT, it's important
also the precision should be optimal, any smaller number will cause the query hang if the token price is too small.
excuse for bad design pattern, many of those variables can be reused. I generally just extract some key steps from my code.