乐闻世界logo
搜索文章和话题

How to deploy smart contracts to different networks in Hardhat?

2月21日 14:12

Deploying smart contracts to different networks in Hardhat requires the following steps:

1. Configure Network Information

Configure target networks in hardhat.config.js:

javascript
networks: { sepolia: { url: process.env.SEPOLIA_RPC_URL, accounts: [process.env.PRIVATE_KEY], chainId: 11155111 }, mainnet: { url: process.env.MAINNET_RPC_URL, accounts: [process.env.PRIVATE_KEY], chainId: 1 } }

2. Create Deployment Script

Create deployment script in scripts/ directory:

javascript
const hre = require("hardhat"); async function main() { const Contract = await hre.ethers.getContractFactory("MyContract"); const contract = await Contract.deploy(); await contract.deployed(); console.log("Contract deployed to:", contract.address); // Verify contract (optional) if (hre.network.name !== "hardhat" && hre.network.name !== "localhost") { await contract.deployTransaction.wait(6); // Wait for 6 block confirmations await hre.run("verify:verify", { address: contract.address, constructorArguments: [] }); } } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); }

3. Execute Deployment

bash
# Deploy to Sepolia testnet npx hardhat run scripts/deploy.js --network sepolia # Deploy to mainnet npx hardhat run scripts/deploy.js --network mainnet

4. Use Hardhat Ignition (Recommended)

Hardhat Ignition provides a declarative deployment approach:

javascript
const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); module.exports = buildModule("MyModule", (m) => { const contract = m.contract("MyContract"); return { contract }; });

Best Practices:

  • Use environment variables to manage private keys and RPC URLs
  • Wait for sufficient block confirmations after deployment
  • Verify contract code on Etherscan
  • Save deployment addresses and constructor parameters
  • Use multi-sig wallets for mainnet deployment
  • Thoroughly test on testnets before deploying to mainnet
标签:Hardhat