I'm attempting to make a function that can give back the price of a token in WETH. however, the price I get back is a massive number and can't be correct. i'm getting an output of 684214468584842621871 on LINK on the Goerli Network

LINK: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
WETH: 0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6
Factory: 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f //uniswapV2

 function GetPriceEth(address _token, address _factory) external view returns(uint) {
    address pairAddress = IUniswapV2Factory(_factory).getPair(_token,WETH);
    require(pairAddress != address(0), "Could not find pool that matches that token");
    IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
    (uint Res0, uint Res1,) = pair.getReserves();
    uint tRes = pair.token0() == _token ? Res0 : Res1;
    uint pRes = pair.token0() == WETH ? Res0 : Res1;
    uint dec = IERC20(_token).decimals();
    return(((tRes*(10**dec)))/pRes); // return amount of weth needed to buy _token

I assume my calculation at the end is the problem.

another attempt for getting the price I made the following:

function getPrice(uint amount, address token0, address token1) external view returns (uint price) {
    IUniswapV2Router02 router = IUniswapV2Router02(UNISWAP_V2_ROUTER);
    address[] memory props;
    props[0] = token0;
    props[1] = token1;
    (uint[] memory amountsOut) = router.getAmountsOut(amount,props);
    return amountsOut[1];

however this one returns "errored: invalid opcode: INVALID"

  • Why do you assume your calculation is the issue? Dec 24, 2022 at 17:56
  • there's not much else that is going on with the function. Dec 24, 2022 at 18:01


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.