0
0
Blockchain / Solidityprogramming~7 mins

Hardhat deployment scripts in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Deployment scripts help you put your smart contracts on the blockchain automatically. They save time and avoid mistakes compared to manual deployment.

When you want to deploy a new version of your smart contract to a test or main network.
When you need to deploy multiple contracts in a specific order.
When you want to automate deployment as part of your development workflow.
When you want to keep track of deployed contract addresses easily.
When you want to reuse deployment steps for different networks.
Syntax
Blockchain / Solidity
async function main() {
  const ContractFactory = await ethers.getContractFactory("ContractName");
  const contract = await ContractFactory.deploy();
  await contract.deployed();
  console.log("Contract deployed to:", contract.address);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

The main function is async because deployment takes time.

ethers.getContractFactory prepares the contract for deployment.

Examples
Deploys a token contract with a name, symbol, and initial supply.
Blockchain / Solidity
async function main() {
  const Token = await ethers.getContractFactory("MyToken");
  const token = await Token.deploy("My Token", "MTK", 1000);
  await token.deployed();
  console.log("Token deployed at", token.address);
}
Deploys two contracts where ContractB needs ContractA's address.
Blockchain / Solidity
async function main() {
  const ContractA = await ethers.getContractFactory("ContractA");
  const a = await ContractA.deploy();
  await a.deployed();

  const ContractB = await ethers.getContractFactory("ContractB");
  const b = await ContractB.deploy(a.address);
  await b.deployed();

  console.log("ContractA at", a.address);
  console.log("ContractB at", b.address);
}
Sample Program

This script deploys a simple Greeter contract with a greeting message.

Blockchain / Solidity
async function main() {
  const Greeter = await ethers.getContractFactory("Greeter");
  const greeter = await Greeter.deploy("Hello, Hardhat!");
  await greeter.deployed();
  console.log("Greeter deployed to:", greeter.address);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
OutputSuccess
Important Notes

Always handle errors in deployment scripts to catch problems early.

Use await contract.deployed() to wait until the contract is fully deployed.

Deployment addresses will be different each time unless you use deterministic deployment.

Summary

Deployment scripts automate putting contracts on the blockchain.

They use async functions and ethers.getContractFactory to prepare contracts.

You can deploy multiple contracts and pass addresses between them.