0

Hi i am learning Solidity and trying to get token price using chainlink/AggregatorV3Interface.I get it but when i try to get exactly price with decimals it returns 8. this is my contract

 pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract FundMe{

mapping(address => uint256) public adressToAmountFunded;

function fund() public payable{
adressToAmountFunded[msg.sender] += msg.value;
}  

function getVersion() public view returns (uint256){
    AggregatorV3Interface priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);
    return priceFeed.version();
}

function getPrice() public view returns(uint256,uint8){
    AggregatorV3Interface priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);

    (uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound) = priceFeed.latestRoundData();
     uint8 decimals = priceFeed.decimals();
    return  (uint256(answer), decimals);
      
}


}
1

decimals() returns the number of decimals in the returned price. In this case, it is eight. I changed your getPrice() function a bit to exclude the use of decimals()

pragma solidity ^0.8.7;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract FundMe{

 mapping(address => uint256) public adressToAmountFunded;

 function fund() public payable{
  adressToAmountFunded[msg.sender] += msg.value;
 }  

 function getVersion() public view returns (uint256){
  AggregatorV3Interface priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);
  return priceFeed.version();
 }

 function getPrice() public view returns(uint256,uint8){
  AggregatorV3Interface priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);

  (uint80 roundId,
   int256 answer,
   uint256 startedAt,
   uint256 updatedAt,
   uint80 answeredInRound) = priceFeed.latestRoundData();
  return(uint256(answer));    
 }
}

Let's say the current price of MATIC/USD is $2.378

getPrice() will return 237800000, where the eight last digits are the decimals.

You can also simplify the code a bit since it seems like you won't need some of the items returned. This way you won't store unnecessary variables. Replace getPrice() with this

 function getPrice() public view returns(uint256,uint8){
  AggregatorV3Interface priceFeed = AggregatorV3Interface(0xd0D5e3DB44DE05E9F294BB0a3bEEaF030DE24Ada);

  (,int256 answer,,,) = priceFeed.latestRoundData();
  return(uint256(answer));    
 }
}
1

The decimals value represents the number of decimal places in the answer and will always be the same. For this feed always posts answer that go out 8 decimal places.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.