Chainlink Price Feed – How to Retrieve Price When Testing with Hardhat

chainlinketherhardhattesting

I have written a smart contract utilizing the chainlink price feed.
Now I want to test if the prices which I calculate in my smart contract are correct.

In solidity I fetch the current USD / ETH price like this:

priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
(,int value,, ,) = priceFeed.latestRoundData();
...

But how would I fetch the current ETH value in the JavaScript testing file?

Best Answer

Two main options, fork mainnet, or use a mockPriceFeed. You can see examples across different frameworks in the smart contract starter kits repo.

Mock Price Feed

Example

Deploy your contract with a variable address for a price feed.

    constructor(address _priceFeed) {
        priceFeed = AggregatorV3Interface(_priceFeed);
    }

In your tests, deploy a mock price feed and then use that address as input for your contract.

Hardhat example:


      beforeEach(async () => {
        await deployments.fixture(["mocks", "feed"])
        mockV3Aggregator = await ethers.getContract("MockV3Aggregator")
        priceConsumerV3 = await ethers.getContract("PriceConsumerV3")
      })

Fork Mainnet

For forking mainnet, you'd just read the price of the mainnet contract and compare it to the price returned by your contract.

const price = await myContract.getPrice()
const priceFromFeed = await priceFeed.getPrice()
assert.equal(price.toString(), priceFromFeed.toString())
Related Topic