1
function getMaticAmountAndPrice(uint256 tokensToBuy, address priceFeed) public view returns (uint256, uint256) {
        // get the latest MATIC price in USD
        AggregatorV3Interface aggregator = AggregatorV3Interface(priceFeed);
        (, int256 price, , , ) = aggregator.latestRoundData();
        require(block.timestamp >= 10, "Price feed not ready");
        uint256 maticPriceInUSD = uint256(price);

        // get the total cost in MATIC for the desired amount of tokens
        uint256 costInWei = tokenPrice * tokensToBuy;
        uint256 costInMatic = costInWei / 1 ether;

        // calculate the equivalent cost in USD based on the current MATIC price
        uint256 costInUSD = costInMatic * maticPriceInUSD / 1e18;
        return (costInMatic, costInUSD);
    }

1 Answer 1

0

Based on the provided information, there are two things that you should check to solve the problem:

  1. Make sure you are using the correct address for the MATIC price feed.
  2. Make sure your contract is deployed on the correct network. That is, if you are using the price feed address for the Polygon testnet, you need to deploy the contract on that network to get the correct data. I would like to mention that it is not possible to test price feeds directly on local Remix IDE networks if that is what you are trying to do.

It would be helpful if you could share the entire contract and provide some details on the environment you are testing on so that I can provide more precise suggestions.

1
  • I did all that, but the result is still the same, I'll post the whole code for you to help me test on remix
    – James Luiz
    Commented Apr 8, 2023 at 5:49

Your Answer

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

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