Deploying and Testing Smart Contracts on a Testnet

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.

Learning Objectives

  • Deploy a smart contract to a testnet using tools like Hardhat or Remix.
  • Understand the difference between testnets and the mainnet.
  • Write and execute basic unit tests for a smart contract.
  • Verify the successful deployment of a smart contract on a block explorer.

Lesson Content

Introduction to Testnets and Mainnet

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:

  • Value: Testnets use test tokens; Mainnet uses real tokens with value.
  • Risk: Low risk on testnets; High risk on mainnet.
  • Cost: Testnet transactions are usually free or very cheap; Mainnet transactions incur gas fees.
  • Purpose: Testing and experimentation on testnets; Real-world use on mainnet.

Quick Check: What is the primary purpose of a testnet?

Deploying to a Testnet (Using Hardhat)

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).

  1. 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
    },
    },
    };
    ```

  2. 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);
    });
    ```

  3. 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

  4. 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.

Quick Check: Which of the following is NOT a good practice when deploying smart contracts?

Introduction to Unit Testing with Hardhat

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:

  1. 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);
    });
    });
    ```

  2. 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.

Quick Check: Which tool is commonly used to write and run unit tests for Solidity smart contracts?

Progress
0%