0
0
Blockchain / Solidityprogramming~15 mins

Hardhat deployment scripts in Blockchain / Solidity - Deep Dive

Choose your learning style9 modes available
Overview - Hardhat deployment scripts
What is it?
Hardhat deployment scripts are programs written to automate the process of sending smart contracts to a blockchain network. They use the Hardhat framework, which helps developers compile, test, and deploy contracts easily. These scripts define how and where contracts are deployed, making the process repeatable and reliable. They are essential for managing contract versions and network configurations.
Why it matters
Without deployment scripts, developers would have to manually deploy contracts each time, which is slow, error-prone, and hard to track. Deployment scripts save time, reduce mistakes, and ensure that contracts are deployed consistently across different networks. This reliability is crucial for building trust in blockchain applications where contracts control valuable assets.
Where it fits
Before learning deployment scripts, you should understand basic blockchain concepts, smart contract programming (usually in Solidity), and how to use Hardhat for compiling and testing. After mastering deployment scripts, you can learn advanced topics like contract upgrades, multi-network deployments, and automated testing with continuous integration.
Mental Model
Core Idea
A Hardhat deployment script is a step-by-step recipe that tells your computer how to send your smart contract to the blockchain safely and consistently.
Think of it like...
Deploying a smart contract with a Hardhat script is like following a cooking recipe: you gather ingredients (contract code), prepare them (compile), and then bake (deploy) in the right order and conditions to get a perfect dish every time.
┌─────────────────────────────┐
│ Hardhat Deployment Script   │
├───────────────┬─────────────┤
│ Compile       │ Prepare     │
│ Contract Code │ Deployment  │
│               │ Instructions│
├───────────────┴─────────────┤
│ Execute Deployment on Network│
│ (Send Contract to Blockchain)│
└─────────────────────────────┘
Build-Up - 8 Steps
1
FoundationUnderstanding Hardhat Basics
🤔
Concept: Learn what Hardhat is and how it helps with smart contract development.
Hardhat is a tool that helps developers write, test, and deploy smart contracts. It provides a local blockchain network for testing and commands to compile contracts. Before deployment, contracts must be compiled into a format the blockchain understands.
Result
You can compile contracts and run tests locally without connecting to a real blockchain.
Knowing Hardhat's role sets the stage for writing scripts that automate deployment, making the process easier and less error-prone.
2
FoundationWhat is a Deployment Script?
🤔
Concept: Deployment scripts are JavaScript files that tell Hardhat how to deploy contracts to a blockchain network.
A deployment script imports the compiled contract, connects to a blockchain network, and sends the contract code to be stored on the blockchain. It usually exports an async function that Hardhat runs when deploying.
Result
You have a simple script that can deploy a contract to a local or test network.
Understanding the script structure helps you customize deployments and manage multiple contracts.
3
IntermediateUsing Hardhat Runtime Environment (HRE)
🤔Before reading on: do you think the deployment script runs inside Hardhat or independently? Commit to your answer.
Concept: Deployment scripts run inside Hardhat's environment, which provides tools and network connections automatically.
Hardhat injects a special object called the Hardhat Runtime Environment (HRE) into deployment scripts. HRE gives access to compiled contracts, network info, and utilities like ethers.js for interacting with the blockchain.
Result
You can write scripts that use HRE to deploy contracts without manually setting up connections or imports.
Knowing that HRE powers deployment scripts explains why you can write concise code that works across networks.
4
IntermediateDeploying Contracts with ethers.js
🤔Before reading on: do you think deployment scripts send raw contract code or use a helper library? Commit to your answer.
Concept: Deployment scripts use ethers.js, a library that simplifies sending contracts to the blockchain and interacting with them.
Inside the script, you get a ContractFactory from ethers.js for your contract. Then you call deploy() to send it to the blockchain. You wait for deployment to finish before continuing.
Result
Your contract is live on the blockchain, and you have its address to interact with.
Using ethers.js abstracts complex blockchain calls, making deployment scripts easier and safer.
5
IntermediateHandling Network Configurations
🤔
Concept: Deployment scripts can deploy to different networks by reading configuration from Hardhat's config file.
Hardhat config defines networks like localhost, testnets, or mainnet with URLs and keys. Deployment scripts detect the current network and deploy accordingly, allowing the same script to work everywhere.
Result
You can deploy the same contract to multiple networks without changing the script.
Separating network details from scripts makes deployments flexible and reduces errors.
6
AdvancedManaging Multiple Contract Deployments
🤔Before reading on: do you think deploying multiple contracts requires separate scripts or can be done in one? Commit to your answer.
Concept: You can deploy several contracts in one script, managing dependencies and passing addresses between them.
In the script, deploy contracts in order, wait for each to finish, then pass deployed addresses as constructor arguments to others. This ensures contracts know about each other on the blockchain.
Result
A network of contracts is deployed correctly with proper references.
Coordinating multiple deployments in one script prevents mistakes and ensures contracts interact properly.
7
AdvancedUsing Deployment Scripts with Verification
🤔
Concept: Deployment scripts can include steps to verify contracts on block explorers automatically after deployment.
After deploying, scripts can call verification plugins that publish contract source code and metadata to explorers like Etherscan. This makes contracts transparent and easier to audit.
Result
Contracts are verified publicly right after deployment without manual steps.
Automating verification increases trust and saves time in production workflows.
8
ExpertOptimizing Deployment Scripts for Production
🤔Before reading on: do you think deployment scripts should be simple or handle complex logic like upgrades and error recovery? Commit to your answer.
Concept: Advanced deployment scripts handle upgrades, environment checks, error handling, and logging for real-world production use.
Scripts can detect if a contract is already deployed, perform upgrades using proxy patterns, retry failed transactions, and log detailed info. They integrate with CI/CD pipelines for automated deployments.
Result
Deployments become reliable, maintainable, and safe in live environments.
Understanding production needs transforms deployment scripts from simple tools into robust automation essential for professional blockchain projects.
Under the Hood
When you run a Hardhat deployment script, Hardhat loads the script inside its runtime environment, providing access to compiled contracts and network connections. The script uses ethers.js to create a ContractFactory, which prepares the contract bytecode and ABI. Calling deploy() sends a transaction to the blockchain network, which miners include in a block. The script waits for this transaction to confirm, then returns the deployed contract's address and instance for further interaction.
Why designed this way?
Hardhat was designed to simplify the complex and error-prone process of deploying contracts by automating compilation, network management, and transaction handling. Using a runtime environment and ethers.js abstracts low-level blockchain details, making deployment scripts easier to write and maintain. This design balances flexibility with developer productivity, avoiding manual steps that cause mistakes.
┌───────────────────────────────┐
│ Hardhat CLI runs deployment.js│
├───────────────┬───────────────┤
│ Hardhat Runtime Environment    │
│ (HRE) provides tools & config  │
├───────────────┴───────────────┤
│ ethers.js ContractFactory      │
│ prepares contract bytecode     │
├───────────────┬───────────────┤
│ deploy() sends transaction     │
│ to blockchain network          │
├───────────────┴───────────────┤
│ Blockchain miners confirm tx   │
│ Contract stored at address     │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does running a deployment script multiple times always create new contracts? Commit to yes or no.
Common Belief:Running a deployment script again always deploys a brand new contract instance.
Tap to reveal reality
Reality:Unless the script checks for existing deployments, running it multiple times will deploy new contracts each time, which may not be intended.
Why it matters:Repeated deployments can waste blockchain resources, cause confusion with multiple contract versions, and break integrations expecting a single contract address.
Quick: Do deployment scripts work without network configuration? Commit to yes or no.
Common Belief:Deployment scripts can deploy contracts without specifying network details in Hardhat config.
Tap to reveal reality
Reality:Network configuration is required so the script knows where and how to send deployment transactions.
Why it matters:Without proper network setup, deployment scripts fail or deploy to unintended networks, risking lost funds or broken apps.
Quick: Is it safe to hardcode private keys in deployment scripts? Commit to yes or no.
Common Belief:Hardcoding private keys in deployment scripts is a convenient and safe practice.
Tap to reveal reality
Reality:Hardcoding keys is insecure and exposes sensitive credentials, risking theft and loss of control over contracts.
Why it matters:Security breaches from leaked keys can cause irreversible financial damage and loss of trust.
Quick: Does deploying a contract automatically verify it on block explorers? Commit to yes or no.
Common Belief:Deploying a contract with Hardhat automatically verifies it on block explorers like Etherscan.
Tap to reveal reality
Reality:Verification is a separate step that must be explicitly added to deployment scripts or run manually.
Why it matters:Without verification, users cannot easily read contract code on explorers, reducing transparency and trust.
Expert Zone
1
Deployment scripts can be designed to support upgradeable contracts by deploying proxies and logic contracts separately, which requires careful ordering and address management.
2
Scripts often include environment checks to prevent accidental deployments to mainnet during testing, using network names and flags.
3
Advanced scripts integrate with continuous integration pipelines to automate deployments on code changes, requiring idempotency and error handling.
When NOT to use
Hardhat deployment scripts are not suitable for extremely large-scale or highly parallel deployments where specialized orchestration tools or custom scripts in other languages might be better. For simple one-off deployments, manual deployment via wallets or GUIs might suffice.
Production Patterns
In production, deployment scripts are part of a DevOps pipeline, often combined with contract verification, automated testing, and upgrade management. Teams use scripts to deploy to multiple networks, manage contract addresses in config files, and rollback deployments if needed.
Connections
Continuous Integration (CI/CD)
Builds-on
Understanding deployment scripts helps integrate blockchain contract deployment into automated CI/CD pipelines, enabling reliable and repeatable releases.
Software Configuration Management
Similar pattern
Deployment scripts act like configuration management tools by automating environment-specific setups, ensuring consistent contract versions across networks.
Manufacturing Assembly Lines
Analogous process
Just as assembly lines automate building products step-by-step, deployment scripts automate contract deployment steps, improving speed and reducing errors.
Common Pitfalls
#1Deploying contracts without waiting for confirmation.
Wrong approach:const contract = await factory.deploy(); console.log('Contract deployed at:', contract.address);
Correct approach:const contract = await factory.deploy(); await contract.deployed(); console.log('Contract deployed at:', contract.address);
Root cause:Not waiting for the deployment transaction to be mined can cause the script to proceed before the contract is actually live.
#2Hardcoding network URLs and private keys inside deployment scripts.
Wrong approach:const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/KEY'); const wallet = new ethers.Wallet('PRIVATE_KEY', provider);
Correct approach:Use environment variables and Hardhat config: // hardhat.config.js networks: { mainnet: { url: process.env.INFURA_URL, accounts: [process.env.PRIVATE_KEY] } }
Root cause:Lack of separation between code and sensitive data leads to security risks and inflexible scripts.
#3Assuming deployment scripts automatically verify contracts on explorers.
Wrong approach:await contract.deploy(); // No verification step
Correct approach:await contract.deploy(); await run('verify:verify', { address: contract.address, constructorArguments: [] });
Root cause:Not understanding that verification is a separate process requiring explicit commands.
Key Takeaways
Hardhat deployment scripts automate sending smart contracts to blockchain networks, making deployments reliable and repeatable.
They run inside Hardhat's runtime environment, using ethers.js to handle contract compilation and deployment transactions.
Scripts can deploy multiple contracts, handle different networks, and automate verification to improve transparency.
Advanced scripts support upgrades, error handling, and integration with automated pipelines for professional production use.
Avoid common mistakes like not waiting for deployment confirmation, hardcoding sensitive data, and assuming automatic verification.