I try to create a function in Solidity which returns the amount of a ERC20 token for a set amount of USDC.
For that I go through the following steps:
Get the address of the pair.
address pairAddress = IUniswapV2Factory(uniswapV2Factory).getPair(erc20Contract, USDC);
require(pairAddress != address(0), "Invalid Uniswap Pair");
Get the reserves of both coins:
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
(uint reserve0, uint reserve1, ) = pair.getReserves();
Check that I am using the right reserves.
if (IUniswapV2Pair(pairAddress).token0() == USDC) { reserve_usdc = reserve0; reserve_coin = reserve1; } else { reserve_usdc = reserve1; reserve_coin = reserve0; }
Calculate the amount of erc20 token I get for the input amount of USDC token.
uint256 price = (reserve_usdc * (10 ** 18)) / reserve_coin;
uint256 erc20_amount = (usdc_amount * price) / (10 ** 6);
However the returned amount is nothing like the one on Uniswap. I checked the pairAddress and it seems correct. I am unsure of where exactly my problem lies here. So any suggestions are appreciated.