How can I access the Uniswap exchange rate for a specific pool? For example purposes lets assume I'm trying to find ETH to AAVE.
1 Answer
The following example is made to work on the mainnet, if you wish to use it on one of the testnets you must replace the following contract addresses:
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
is the contract address of Uniswap Router V20xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
is the contract address of WETH
pragma solidity ^0.8.0;
contract TestContract {
UniswapRouter UR = UniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
function getPairETHRate(uint256 _eth_amount, address _token_contract) public view returns(uint) {
address[] memory path = new address[](2);
path[0] = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
path[1] = _token_contract;
uint firstReturnedParam;
uint secondReturnedParam;
(firstReturnedParam, secondReturnedParam) = UR.getAmountsOut(_eth_amount, path);
return secondReturnedParam;
}
}
interface UniswapRouter {
function getAmountsOut(uint, address[] memory) external view returns (uint[] memory);
}
Ok so in my example you have the method called getPairETHRate
which is accepting ETH amount in wei for first parameter and the second parameter is the token contract address ( in your case that would be AAVE contract address ). So when you pass 100000000000000000 wei ( 0.1 ETH ) as first parameter the method will return how much tokens you can get right now from the uniswap pair by swapping 0.1 ETH. Feel free to test it.
If for example the token is being listed on more pairs for example USDT, you can paste the USDT contract address on path[0]
and then you will get the /USDT exchange rate.