A robust Solidity smart contract implementation for fetching real-time token prices from UniswapV2 pairs.
The UniswapV2PriceOracle contract provides price discovery functionality for any ERC20 token that has a liquidity pair with WETH on UniswapV2. The contract uses reserve ratios from liquidity pools to calculate token prices.
- Single token price queries
- Batch token price queries
- Price calculations in both token/ETH and ETH/token ratios
- Automatic decimal handling for different token standards
- Event emission for price updates
-
getPairAddress(address tokenA, address tokenB)
- Returns the UniswapV2 pair address for given token pairs
- View function that queries the UniswapV2Factory
-
getTokenPrice(address token)
- Returns tuple of (tokenPrice, ethPrice, symbol)
- Handles decimal normalization
- Emits PriceUpdated event
- Returns prices in 18 decimal precision
-
getMultipleTokenPrices(address[] tokens)
- Batch processing function for multiple tokens
- Returns arrays of prices and symbols
- Gas-efficient implementation for multiple queries
The contract interfaces with:
- IUniswapV2Factory: For pair address discovery
- IUniswapV2Pair: For accessing pool reserves
- IERC20: For token metadata (decimals, symbols)
Prices are calculated using the following formula:
- Token/ETH price = (reserve_token * 10^18) / reserve_eth
- ETH/Token price = (reserve_eth * 10^token_decimals) / reserve_token
- Solidity ^0.8.27
- UniswapV2 compatible network
- WETH token address
- UniswapV2 Factory address
The contract requires two constructor parameters:
- WETH address
- UniswapV2 Factory address
- Relies on UniswapV2 liquidity for accuracy
- No price manipulation protection
- Uses instantaneous prices (no TWAP)
- External calls to token contracts
- Add TWAP functionality
- Implement price manipulation protection
- Support more token standards
- Add batch token price queries
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a pull request
This project is licensed under the MIT License - see the LICENSE file for details.