[Ethereum] How to know the amount of ETH in the liquidity pool

solidityuniswap

I'm currently trying to find a way to know the amount of ETH inside the liquidity pool. That would be by using Uniswap V2. A pair would be ETH/Some other ERC20 token.

My idea was about using IUniswapV2Pair Interface and then i'm just not sure. Maybe there is a better way even ? (https://github.com/Uniswap/uniswap-v2-core/blob/4dd59067c76dea4a0e8e4bfdda41877a6b16dedc/contracts/interfaces/IUniswapV2Pair.sol)

I would appreciate any help or to see any examples of something similar implemented in a contract, thanks.

Best Answer

Use the below function to know the liquidity of a pair:

import "./interfaces/IUniswapV2Pair.sol";
import "./interfaces/IUniswapV2Factory.sol";

contract Uniswap {

   IUniswapV2Factory factory;

   constructor(address _factory) {
       factory = IUniswapV2Factory(_factory);
   }

   function getLiquidity(address tokenA, address tokenB) view external returns (uint256) {
       IUniswapV2Pair pair;
       pair = IUniswapV2Pair(factory.getPair(tokenA, tokenB));
       return pair.balanceOf(msg.sender);
   }
   //...
}

If you know the current liquidity and what the pair ratio is, you can deduce the amount of ETH and Token for that pair.

Related Topic