This lesson focuses on deploying and testing smart contracts on testnets. You'll learn how to get your contracts out of your local development environment and onto a real blockchain network for testing, and how to write basic tests to ensure they function as expected.
Before deploying to the real world (mainnet), we test our smart contracts on testnets. Think of a testnet as a practice environment, a sandbox if you will. It's a blockchain that mimics the mainnet but uses test ETH (or other test tokens), which has no real-world value. This allows you to test your contracts without risking real funds. Popular testnets include Goerli, Sepolia, and Mumbai (for Polygon). The mainnet is the live, production environment where real transactions and funds are used. Deploying directly to the mainnet without thorough testing is extremely risky!
Key differences:
Let's assume you've already set up your Hardhat project from previous lessons. We'll walk through deploying a simple contract to a testnet. This example assumes you have test ETH. You can usually get test ETH from faucets online (e.g., Goerli Faucet, Sepolia Faucet).
Configure Hardhat: In your hardhat.config.js
file, add a network configuration for your chosen testnet (e.g., Goerli). You'll need an RPC URL (provided by providers like Infura, Alchemy, or QuickNode) and your wallet's private key (securely stored, of course!).
```javascript
require('@nomicfoundation/hardhat-toolbox');
require('dotenv').config();
const { PRIVATE_KEY, GOERLI_RPC_URL } = process.env;
module.exports = {
solidity: "0.8.19",
networks: {
goerli: {
url: GOERLI_RPC_URL, // From Infura, Alchemy, etc.
accounts: [PRIVATE_KEY], // Your private key
},
},
};
```
Create a Deployment Script: Create a deployment script (e.g., scripts/deploy.js
). This script will use Hardhat to deploy your contract.
```javascript
// scripts/deploy.js
async function main() {
const MyContract = await ethers.getContractFactory("MyContract"); // Replace with your contract name
const myContract = await MyContract.deploy();
await myContract.deployed();
console.log("MyContract deployed to:", myContract.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
```
Deploy the Contract: Run the deployment script using Hardhat. Make sure you have test ETH in your connected wallet.
bash
npx hardhat run scripts/deploy.js --network goerli # Replace 'goerli' with your network
Verify on a Block Explorer: After deployment, Hardhat will output the contract address. You can then go to a block explorer (like Etherscan, for Goerli) and search for the contract address to verify its deployment and transactions. You may also need to verify the source code. This process is specific to the chain and the explorer.
Unit tests are isolated tests that verify individual parts of your code. They help ensure that your smart contracts behave as expected. Hardhat, by default, provides the Mocha testing framework and Chai assertion library for writing tests.
Here's a basic example:
Create a Test File: Create a test file (e.g., test/MyContract.js
).
```javascript
// test/MyContract.js
const { expect } = require("chai");
describe("MyContract", function () {
it("Should deploy and have a starting value of 0", async function () {
const MyContract = await ethers.getContractFactory("MyContract"); // Replace with your contract name
const myContract = await MyContract.deploy();
await myContract.deployed();
expect(await myContract.getValue()).to.equal(0);
});
it("Should be able to set a new value", async function() {
const MyContract = await ethers.getContractFactory("MyContract");
const myContract = await MyContract.deploy();
await myContract.deployed();
const newValue = 10;
await myContract.setValue(newValue);
expect(await myContract.getValue()).to.equal(newValue);
});
});
```
Run Tests: Run the tests using Hardhat.
bash
npx hardhat test
Hardhat will execute your tests and report the results. If any tests fail, it will tell you where.
Explore advanced insights, examples, and bonus exercises to deepen understanding.
Building on what you've learned about deploying and testing smart contracts, this extension dives deeper into the world of testnets, deployment strategies, and contract verification.
Beyond simply deploying to a testnet, there are crucial considerations for efficient and reliable smart contract development. Let's explore some key areas:
Create a simple Hardhat project if you haven't already. Write a deployment script (in the `scripts` folder) that automatically deploys a simple "Greeter" smart contract to a testnet of your choice. Include code to verify the deployment on a block explorer. (Hint: Use Hardhat's built-in `etherscan` plugin or a package like `@nomiclabs/hardhat-etherscan`.)
Take an existing smart contract (or create a new, simple one). Use Hardhat and tools like `hardhat-gas-reporter` to analyze the gas costs of different functions within your contract. Experiment with different code structures to see how they impact gas usage. Document your findings.
The skills you're learning have direct applications in real-world Web3 projects:
Try these more advanced challenges:
Deploy a simple smart contract (e.g., a simple 'Counter' contract that increments a counter) to a testnet (Goerli, Sepolia, or Mumbai). Use the instructions provided above as a guide. Provide screenshots or the transaction hash demonstrating your successful deployment.
Write at least one unit test for your deployed 'Counter' contract. The test should verify the initial value, the ability to increment the counter, and the ability to view the current count. Show the code of your test file and the output of the test run.
After deploying your contract, use a block explorer (e.g., Etherscan) to view its transactions and contract details. Provide a link to your contract's page on the explorer and describe what information you can see. Discuss the implications of the information shown.
Develop a simple decentralized application (dApp) that allows users to create and display short messages on a blockchain. Deploy the smart contract to a testnet and implement front-end interactions to allow users to interact with the messages.
Prepare for the next lesson on building a basic decentralized application (dApp) front-end. Consider researching popular JavaScript libraries like React or Vue.js and how they interact with Web3 libraries like Ethers.js or Web3.js.
We're automatically tracking your progress. Sign up for free to keep your learning paths forever and unlock advanced features like detailed analytics and personalized recommendations.