Search code examples
ethereumsoliditychainlinkhardhat

Get Chainlink ETH/USD Price Feed answer as uint256 instead of int solidity


I want to use the latest ETH price in USD to calculate how much USDC I can borrow from AAVE.

I followed all the tutorials:

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

}

Used the contract for ETH/USD price feed:

https://etherscan.io/address/0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419

AggregatorV3Interface internal priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);

Created the function to get the price:

 function getLatestPrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }

And the function I want to call is this one:

 AaveLendingPool.borrow(address(USDT),getLatestPrice(), 1, 0, address(this));

this is the error I get:

TypeError: Type int256 is not implicitly convertible to expected type uint256.

I need to convert the int to unit


Solution

  • You can typecast the int to uint using this syntax: uint256(input)

    Example:

    pragma solidity ^0.8;
    
    contract MyContract {
        function foo() external {
            borrow(uint256(getLatestPrice()));
        }
        
        function getLatestPrice() internal returns (int256) {
            return 1;
        }
        
        function borrow(uint256 _number) internal {
        }
    }