deploy smart contracts locally

~ 4 min.

15.03.2023
edit
image

create deploy.js file in scripts folder -- if it already exists, delete all the content in it, coz' we gonna start from scratch -- like pros.

./scripts/deploy.js
const hre = require("hardhat");
 
const main = async () => {
    // We'll write deployment logic here
};
 
main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
});

  • to deploy a smart contract, it's bytecode is required -- you can find it stored in bytecode variable @ below path.
  • Bytecode Path
    artifacts/contracts/[CONTRACT_NAME].sol/[CONTRACT_NAME].json
  • bytecode is taken by a function of ethers called getContractFactory.
  • then, we will call the deploy method returned by getContractFactory object.
  • now, just wait for the deployed promise to get fulfilled.
  • note: bytecode consists of anything + everything your smart contract does. It will be then converted to machine level binary code.

  • setting contract factory
  • const contractFactory = await hre.ethers.getContractFactory("CONTRACT_NAME");
  • calling deploy method
  • const contract = await contractFactory.deploy();
  • waiting for deployment to complete
  • await contract.deployed();
  • finally, your main function will look like below.
  • ./scripts/deploy.js
    const main = async () => {
        const contractFactory = await hre.ethers.getContractFactory("Hello");
        const contract = await contractFactory.deploy();
        await contract.deployed();
     
        console.log(`Deployment address is ${contract.address}`);
    };

    p.s., you can also console.log contractFactory + contract objects to see all that nerdy stuff which happens behind the scenes.

    run below command in terminal -- it will spin a local blockchain -> execute your deploy script -> terminate the local instance -- all in just one command, that's hardhat bruh :)

    Terminal
    npx hardhat run scripts/deploy.js

    you have learnt how to build, now it's time to ship those smart contracts to actual testnet, wink wink. click here to deploy smart contracts + go live, fr.