Search code examples
environment-variablessolidityhardhatchainlink

Reading address from environmental variable or hardhat


I'm new at solidity. I've put here the snippet of code:

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

contract Example {
    AggregatorV3Interface internal priceFeed;

    /**
     * Network: Goerli
     * Aggregator: ETH/USD
     * Address: 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
     */
    constructor() {
        priceFeed = AggregatorV3Interface(
            0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
        );
        owner = msg.sender;
    }

}

And if you see, the parameter that I need to send to AggregatorV3Interface is static 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e. To me, that doesn't look optimized enough. Because right now, I'm playing with this function for Goerli, but if I were to deploy this contract to Etherium mainnet, I would have to change that address manually. Even if you go to chainlink website, they have it like this. https://docs.chain.link/data-feeds/price-feeds/#solidity

Is there a better way? I would like to have some variable that I would set, and read from it? Or maybe some custom variable setting from hardhat, that I'm using.

priceFeed = AggregatorV3Interface(env.proccess.address); Would be desired, or anything dynamic.


Solution

  • Usual approach is to pass the address to Solidity constructor from a JS (or any other offchain language) script that reads from the environment variable.

    .env

    AGGREGATOR_ADDRESS=0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
    

    JS deployer script

    require("dotenv").config();
    const hre = require("hardhat");
    
    async function main() {
        const factory = await hre.ethers.getContractFactory("Example");
        // pass constructor arguments to the `deploy()` function
        const contract = await factory.deploy(process.env.AGGREGATOR_ADDRESS);
        await contract.deployed();
    }
    
    main().catch((error) => {
        console.error(error);
        process.exitCode = 1;
    });
    

    Solidity contract

    pragma solidity ^0.8;
    
    import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
    
    contract Example {
        AggregatorV3Interface internal priceFeed;
    
        constructor(address _aggregator) {
            priceFeed = AggregatorV3Interface(_aggregator);
        }
    }