Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Deploying to Ethereum Mainnet

Hello! Welcome to the final and most anticipated lesson of this module. Over the past few lessons, we've meticulously prepared for this moment. We configured our project for live networks, learned to estimate the real-world costs of deployment, and applied gas optimization techniques to make our contracts efficient. All that preparation culminates today.

Our learning outcome is to perform the final deployment of your token and associated contracts to the Ethereum mainnet. This is the step where your project transitions from a local development environment to a live, global, and immutable ledger. It's the equivalent of deploying a web application to production servers, but with the added permanence that blockchain offers.

Given that this involves real funds for gas fees and creates a permanent record, we will proceed with a methodical, step-by-step approach, much like a pre-flight checklist before a launch. Let's begin!

The Mainnet Deployment Checklist

Deploying to the mainnet requires three key components, which are conceptually the same as for a testnet, but with real assets at stake.

  1. A Funded Mainnet Account: You'll need an Ethereum account (your MetaMask wallet is perfect) funded with actual Ether (ETH) to pay for the gas fees of the deployment transaction. Unlike testnets, this ETH must be purchased from an exchange.
  2. A Mainnet Node Provider: Your Hardhat environment needs to communicate with the Ethereum network. We'll use a node provider service like Infura or Alchemy to get a secure RPC URL for the mainnet.
  3. A Secure Project Configuration: Your private key and RPC URL are sensitive credentials. They must be stored securely and never hard-coded or committed to version control.

This short video clip reinforces the essential components needed for any live network deployment.

Hardhat - Deploying Smart Contract to Ethereum (Testnet / Mainnet)

The video "Hardhat - Deploying Smart Contract to Ethereum (Testnet / Mainnet)" by Moralis for Developers provides a concise overview of what's required to deploy to a live network.

Watch the segment from 01:40 to 02:40. It highlights the two primary needs: a funded account on the target network and a node to connect to it.

With this checklist in mind, let's configure your project.

Step 1: Configure Hardhat for Mainnet

We will now add a mainnet network configuration to your hardhat.config.js file. The process involves securely referencing your mainnet RPC URL and the private key of your funded deployer account.

The modern and recommended way to handle secrets in Hardhat is using its built-in configuration variables. This avoids having .env files and is a clean way to manage sensitive data.

Deploying to a live network

The official Hardhat documentation demonstrates the best practice for setting up a connection to a remote network. We will follow this pattern to configure our mainnet connection.

Please read the section titled 'Deploying to remote networks'. Pay close attention to the hardhat.config.js example that uses vars.get("..."). This is the mechanism we'll use to securely load your API key and private key without exposing them in your code.

Now, let's put that into practice.

  1. Get a Mainnet RPC URL:

    • Sign up for a free account with a provider like Alchemy or Infura.
    • Create a new App/Project for the "Ethereum Mainnet".
    • Copy the HTTPS RPC URL. It will look something like https://mainnet.infura.io/v3/YOUR_API_KEY or https://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY.
  2. Set Your Configuration Variables:
    Open your terminal in your project's root directory and run the following commands, replacing the placeholder values with your actual RPC URL and private key.

    Security Warning: Your mainnet private key controls real funds. NEVER share it, commit it to Git, or expose it publicly.

    # Set your mainnet RPC URL from Alchemy or Infura
    npx hardhat vars set MAINNET_RPC_URL "YOUR_RPC_URL_HERE"
    
    # Set the private key of your funded deployment account
    npx hardhat vars set MAINNET_PRIVATE_KEY "YOUR_METAMASK_PRIVATE_KEY_HERE"
    

    Hardhat will store these encrypted in a local .vars.json file, which is already included in your .gitignore to prevent accidental commits.

  3. Update hardhat.config.js:
    Add the mainnet network to the networks object in your hardhat.config.js file.

    require("@nomicfoundation/hardhat-toolbox");
    const { vars } = require("hardhat/config");
    
    // Load variables
    const MAINNET_RPC_URL = vars.get("MAINNET_RPC_URL", "");
    const MAINNET_PRIVATE_KEY = vars.get("MAINNET_PRIVATE_KEY", "");
    const SEPOLIA_RPC_URL = vars.get("SEPOLIA_RPC_URL", ""); // Assuming you still have your testnet config
    const SEPOLIA_PRIVATE_KEY = vars.get("SEPOLIA_PRIVATE_KEY", "");
    
    /** @type import('hardhat/config').HardhatUserConfig */
    module.exports = {
      solidity: "0.8.20", // Or your contract's version
      networks: {
        sepolia: {
          url: SEPOLIA_RPC_URL,
          accounts: [SEPOLIA_PRIVATE_KEY],
        },
        mainnet: { // <-- Add this block
          url: MAINNET_RPC_URL,
          accounts: [MAINNET_PRIVATE_KEY],
        },
      },
      // ... other settings like gasReporter, etherscan
    };
    

Your project is now configured for its mainnet launch.

Step 2: Execute the Deployment

The deployment script you've used for testnets will work for the mainnet. The only difference is the --network flag you'll provide in the command.

First, ensure your deployment script (scripts/deploy.js or similar) is up-to-date and deploys all necessary contracts in the correct order. For instance, if you're deploying a crowdsale or staking contract that depends on your token's address, the token must be deployed first.

Build and Deploy a Simple Staking Contract

A good deployment script handles the deployment of all related contracts sequentially, passing necessary information (like a contract address) from one deployment to the next. This guide for a staking contract provides an excellent example of this pattern.

Find the heading 'Step 5: Deploy the Staking Contract' and review the code inside scripts/deploy.js. Notice how it first awaits the deployment of MyToken, then retrieves its address with myToken.getAddress(), and finally passes that address into the constructor of the SimpleStaking contract. This is a critical pattern to follow.

Once you have:

  • Double-checked your deployment script.
  • Funded your deployer wallet with enough ETH for gas (check a gas tracker like Etherscan Gas Tracker for current prices).
  • Completed the hardhat.config.js setup.

You are ready to run the final command.

Execute this command from your project's root directory:

npx hardhat run scripts/deploy.js --network mainnet

The deployment process on mainnet will take longer than on a testnet, as it depends on a real block being mined. Be patient and let the script finish. Upon successful completion, your terminal will display the addresses of your newly deployed contracts.

Smart Contract Deployment Console Output
This image shows an example of a successful deployment output in the console. You should see similar messages confirming the deployment and providing the transaction hash and the all-important contract address.

Action Required: Carefully copy the deployed contract addresses and save them in a secure location. You will need them for everything that comes next: verifying on Etherscan, integrating with a frontend, and interacting with your contracts.

Step 3: Initial Verification on a Block Explorer

With your contract addresses in hand, the very first thing you should do is look them up on a mainnet block explorer like Etherscan. Paste your token's contract address into the search bar. You should see a "Contract Creation" transaction and be able to view details about your new token contract.

My Token (MTK) Dashboard on a Blockchain Explorer
This is an example of what your token's page might look like on a block explorer after deployment. It confirms the contract address, total supply, and shows the initial transaction history (the minting of tokens to your deployer address).

Seeing this page is the ultimate confirmation: your contract is live and part of the Ethereum blockchain.

Conclusion

Congratulations! You have successfully navigated the final and most critical step of the development process: deploying to the mainnet. This is a massive milestone. You've taken an idea and turned it into a live, globally accessible asset on the Ethereum blockchain.

Key Takeaways:

  • Mainnet deployment requires a checklist: A funded account, a node RPC URL, and a secure Hardhat configuration are non-negotiable.
  • Security is paramount: Using Hardhat vars or a similar mechanism like .env files is essential to protect your private keys.
  • The process is methodical: The command is simple (--network mainnet), but the preparation is what ensures success.
  • Save your addresses: The deployed contract addresses are the keys to your project's kingdom. Keep them safe and accessible.

Preview of the Next Lesson:

Your contract is live, but to the outside world, it's just a bunch of bytecode at an address. How can you build trust and prove to your users that the code running on-chain is the same code you've written? The answer is source code verification. In our next lesson, we will learn how to verify your contract's source code on Etherscan, making it transparent and trustworthy for everyone.

Can't find a good explanation? Sign up and we'll make it for you

Sign up