1

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:

  1. Get the address of the pair.

    address pairAddress = IUniswapV2Factory(uniswapV2Factory).getPair(erc20Contract, USDC);

    require(pairAddress != address(0), "Invalid Uniswap Pair");

  2. Get the reserves of both coins:

    IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);

    (uint reserve0, uint reserve1, ) = pair.getReserves();

  3. 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; }

  4. 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.

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.