Hardhat – How to Chain Contract Deployments with Hardhat-Deploy

hardhathardhat-deploy

I am deploying multiple contracts that take in as their constructor arguments the addresses of previous contracts.

    const goblinoracle = await deploy("GoblinOracle", {
        from: deployer,
        args: Object.values(constructorArgs["GoblinOracle"]),
        log: true,
        waitConfirmation: network.config.blockConfirmations || 1,
    });
    
    const oracle = await deployments.get("GoblinOracle");
    const oracleAddress = oracle.address;
    
    const goblinAuction = await deploy("GoblinAuction", {
        from: deployer,
        args: Object.values(constructorArgs["GoblinAuction"]),
        log: true,
        waitConfirmation: network.config.blockConfirmations || 1,
    });
    
    const auction = await deployments.get("GoblinAuction");
    const auctionAddress = auction.address;
    
    const vaultManager = await deploy("VaultManager", {
        from: deployer,
        args: Object.values(constructorArgs["VaultManager"]).push(
            oracleAddress,
            auctionAddress
        ),
        log: true,
        waitConfirmation: network.config.blockConfirmations || 1,
    });

As you can see I have to declare a const to store the deployed contract address each time I deploy a contract. Is there anyway I can make this more elegant? As you can see I reuse quite a bit of code.

Best Answer

You could try to put the deploy logic in a function to reuse it:

async function deployContract(deployer, contractName, args = []) {
  return await deploy(contractName, {
    from: deployer,
    args: [...Object.values(constructorArgs[contractName]), ...args],
    log: true,
    waitConfirmation: network.config.blockConfirmations || 1,
  });
}

await deployContract(deployer, "GoblinOracle");

await deployContract(deployer, "GoblinAuction");

const auctionAddress = await deployments.get("GoblinAuction").address;

const oracleAddress = await deployments.get("GoblinOracle").address;

const vaultManager = await deployContract(deployer, "VaultManager", [
  oracleAddress,
  auctionAddress,
]);

I noticed you are not using the response from the deployment, so no need to create a variable/constant for that, just await for it.