Deploying Multiple Contracts at the same address using hardhat
In recent versions of hardhat, there is a new way to deploy multiple contracts at the same address. This feature allows you to create a contract that can be deployed with additional argument or variables.
Solution
To deploy two contracts a and b at the same address using hardhat 4.x, you can use the -Network
option and pass an array of contract addresses as argument.
HERE’S AN EXAMPLE:
`JSon
// contracts.js
Const Contracta = artifacts.require ("Contracta");
Const contractb = artifacts.require ("contractb");
Module.exports Function Deploycontracts () {
return ethers.providers.deployer.at ("0x ..."). then ((provider) => {
Const [contractaaddress, contractbaddress] = ["0x ...", "0x ..."];
// deploy contracts a and b at the same address
await contract.new ({from: provider, date: [], nonce: 0});
Await contractb.new ({from: provider, date: [], nonce: 0});
// Use the Deployed Contracts in Your Next Contract
Const Contracta = Contracta.at (ContractaAddress);
Const contractb = contractb.at (contractbaddress);
Return [Contracta, Contractb];
});
}
`JSon
// scripts/hardhat.js
Const {deploy} = Require ("hardhat");
Module.exports Function Deploycontracts () {
Return New Promise ((Resole) => {
Deploy ([{
Contract: "Contracts/Contracta.json",
from: "0x ...",
GasSrice: 10000,
Gaslimit: 2000000,
Nonce: 0,
}], (ERR, accounts) => {{
If (ERR) {
console.error (ERR);
Return;
}
// Get the Deployed Contracts
Const [contractaaddress, contractbaddress] = accounts.map ((account) =>
Contracta.at (ContractaAddress)
);
// Use the Deployed Contracts in Your Next Contract
resolve ([contractaaddress, contractbaddress]);
});
});
}
In this example, we define two contracts Contracta
andContractb
. We are deploying both contracts at the same address using the deploycontracts
function. The Deploy
Hook allows us to pass an array of contract addresses as argument.
The deploycontracts
Function returns a promise that resolves with an array containing the addresses of the deployed contracts. In this case, we use the map method to extract the addresses of each contract from the array of accounts.
Example Use Case
In your next hardhat script, you can use the deployed contracts in a function or variable.
JavaScript
// scripts/hardhat.js
Const {Deploycontracts} = Require ("./ deploycontracts");
Async Function Main () {
Const [contractaaddress, contractbaddress] = await deloycontracts ();
// Use the Deployed Contracts in Your Next Contract
Const Contracta = Contracta.at (ContractaAddress);
Const contractb = contractb.at (contractbaddress);
// do something with the contracts ...
}
Note that hardhat 4.x also supports other features such as event emitters, access control, and more. Be sure to check out the official hardhat documentation for a comprehensive list of available hooks and functions.
Leave a Reply