@@ -33,6 +33,10 @@ contract UniswapV2Oracle is IOracle {
3333 return getTokenValueInUSDT (token, 10 ** IERC20 (token).decimals ());
3434 }
3535
36+ function getPairAddress (address tokenA , address tokenB ) external view returns (address ) {
37+ return IUniswapV2Factory (factory).getPair (tokenA, tokenB);
38+ }
39+
3640 function getTokenValueInUSDT (address token , uint256 amount ) public view returns (uint256 , uint256 ) {
3741 address pairAddress = IUniswapV2Factory (factory).getPair (token, USDT);
3842 require (pairAddress != address (0 ), "Pair does not exist " );
@@ -51,17 +55,31 @@ contract UniswapV2Oracle is IOracle {
5155 // and pool have 10 eth and 30000 usd then
5256 // 1e18 * 30000USD * 10 ** 1e18 / 10eth * 10 ** 1e6
5357 uint256 price = (amount * reserveUSDT * (10 ** tokenDecimals)) / (reserveToken * (10 ** usdtDecimals));
54- console.log ("price: {} " , price);
55- console.log ("reserve0: {} " , reserve0);
56- console.log ("reserve1: {} " , reserve1);
5758
5859 uint256 scale = 10 ** tokenDecimals;
5960 uint256 integer_part = price / scale;
6061 uint256 fraction = price % scale;
6162 return (integer_part, fraction);
6263 }
6364
64- function getPairAddress (address tokenA , address tokenB ) external view returns (address ) {
65- return IUniswapV2Factory (factory).getPair (tokenA, tokenB);
65+ function getAmountIn (address tokenIn , address tokenOut , uint256 amountOut ) external view returns (uint256 ) {
66+ address pairAddress = IUniswapV2Factory (factory).getPair (tokenIn, tokenOut);
67+ require (pairAddress != address (0 ), "Pair does not exist " );
68+
69+ IUniswapV2Pair pair = IUniswapV2Pair (pairAddress);
70+
71+ (uint112 reserve0 , uint112 reserve1 ,) = pair.getReserves ();
72+ require (reserve0 > 0 && reserve1 > 0 , "Insufficient liquidity " );
73+
74+ bool isToken0In = pair.token0 () == tokenIn;
75+ (uint256 reserveIn , uint256 reserveOut ) =
76+ isToken0In ? (uint256 (reserve0), uint256 (reserve1)) : (uint256 (reserve1), uint256 (reserve0));
77+
78+ uint256 numerator = reserveIn * amountOut * 1000 ;
79+ // uniswap v2 fee is 0.3%
80+ uint256 denominator = (reserveOut - amountOut) * 997 ;
81+ uint256 amountIn = (numerator / denominator) + 1 ;
82+
83+ return amountIn;
6684 }
6785}
0 commit comments