1

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?

2 Answers 2

3

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())
0

You could fork the mainnet with an Infura key (or Alchemy key) and hardhat and do your tests?

Here is a link to hardhat's page explaining how to do it.

https://hardhat.org/hardhat-network/docs/guides/forking-other-networks

1
  • Yes, this is correct. But I wonder how does the actual implementation of the testing look like. How do I query the ETH to USD price in my test file?
    – rajohs
    Oct 10, 2022 at 1:12

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.