Somnia Docs
Developer DiscordTestnet Homepage
Somnia Documentation
Somnia Documentation
  • 📍Introduction
  • 🔥Get Started
    • Connect your Wallet
    • Request STT Tokens & Try sending tokens to a Random address
    • Removing the Somnia Devnet Network
    • Update the block explorer in metamask
  • Developer
    • Network Info
    • Resources & Important Links
    • Add Custom token in Metamask
    • Tutorials
      • How to Deploy Your First Smart Contract to Somnia Network
      • Create and Deploy your ERC20 Smart Contract to Somnia Network
      • Deploy and Verify A Smart Contract on Somnia using Hardhat
      • Deploy a Smart Contract on Somnia Testnet using Foundry
      • How to Connect to Somnia Network via Viem Library
      • How to Setup MetaMask Authentication to Connect Somnia Network
      • Build a Simple DAO Smart Contract
      • How To Build A User Interface For DAO Smart Contract p1
      • How To Build A User Interface For DAO Smart Contract p2
      • How To Build A User Interface For DAO Smart Contract p3
    • Partners
      • How to deploy Smart Contracts to Somnia using Thirdweb
      • Integrate ConnectKit with Somnia in a Next.js Application
      • Integrating RainbowKit with Somnia in a Next.js Application
      • Integrating DIA Oracles on Somnia
      • Indexing Data on Somnia using Graph Services
      • Somnia Account Abstraction Apps using Thirdweb React SDK
      • Build a NextJS UI for Subgraphs on Somnia
      • Deploy a Subgraph on Somnia using Ormi
    • Infrastructure Providers
      • RPC
      • Oracles
      • Safes
      • Explorers
      • SDKs
  • 📜Litepaper
    • Somnia-Mission
    • Problem
  • ⛓️Somnia Blockchain
    • Overview
    • MultiStream Consensus
    • Accelerated Sequential Execution
    • Somnia's IceDB
    • Advanced Compression Techniques
    • Security
    • Use Cases
  • 🌐Ecosystem
    • Protocols
      • SOM0
      • SOM1
    • Experiences
      • Metaverse Browser
      • Somnia Playground
    • Content Creation
  • 🌑Conclusion
Powered by GitBook
On this page
  • Pre-requisites
  • Initialise Hardhat Project
  • Create the Smart Contract
  • Compile the Smart Contract
  • Deploy Contract
  • Verify Your Smart Contract
Export as PDF
  1. Developer
  2. Tutorials

Deploy and Verify A Smart Contract on Somnia using Hardhat

PreviousCreate and Deploy your ERC20 Smart Contract to Somnia NetworkNextDeploy a Smart Contract on Somnia Testnet using Foundry

Last updated 21 days ago

Various developer tools can be used to build on Somnia to enable the Somnia mission of empowering developers to build Mass applications. One such development tool is Hardhat. is a development environment for the EVM i.e. Somnia. It consists of different components for editing, compiling, debugging, and deploying your smart contracts and dApps, all working together to create a complete development environment. This guide will teach you how to deploy a “Buy Me Coffee” Smart Contract to the Somia Network using Hardhat Development tools.

Pre-requisites

  1. This guide is not an introduction to Solidity Programming; you are expected to understand Basic Solidity Programming.

  2. To complete this guide, you will need MetaMask installed and the Somnia Network added to the list of Networks. If you have yet to install MetaMask, please follow this guide to .

  3. Hardhat is installed and set up on your local machine. See .

Initialise Hardhat Project

Start a new Hardhat project by running the following command in your Terminal:

npx hardhat init

This will give you a series of prompts. Select the option to “Create a TypeScript Project (with Viem)”

This will install the required dependencies for your project. Once the installation is complete, open the project directory and check the directories where you will find the `contracts` directory. This is where the Smart Contract will be added.

Create the Smart Contract

Open the Smart Contracts folder and delete the default Lock.sol file. Create a new file, BuyMeCoffee.sol and paste the following code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

contract BuyMeCoffee {
    event CoffeeBought(
        address indexed supporter,
        uint256 amount,
        string message,
        uint256 timestamp
    );

    address public owner;

    struct Contribution {
        address supporter;
        uint256 amount;
        string message;
        uint256 timestamp;
    }
    
    Contribution[] public contributions;

    constructor() {
        owner = msg.sender;
    }

    function buyCoffee(string memory message) external payable {
        require(msg.value > 0, "Amount must be greater than zero.");
        contributions.push(
            Contribution(msg.sender, msg.value, message, block.timestamp)
        );

        emit CoffeeBought(msg.sender, msg.value, message, block.timestamp);
    }

    function withdraw() external {
        require(msg.sender == owner, "Only the owner can withdraw funds.");
        payable(owner).transfer(address(this).balance);
    }

    function getContributions() external view returns (Contribution[] memory) {
        return contributions;
    }

    function setOwner(address newOwner) external {
        require(msg.sender == owner, "Only the owner can set a new owner.");
        owner = newOwner;
    }
}

Compile the Smart Contract

To compile your contracts, you need to customize the Solidity compiler options, open the hardhat.config.js file and ensure the Solidity version is 0.8.28 and then run the command:

npx hardhat compile

It will return the response:

Compiling...
Compiled 1 contract successfully

This will compile the Solidity file and convert the Solidity code into machine-readable bytecode. By default, the compiled artifacts will be saved in the newly created artifacts directory. The next step is to deploy the contracts to the Somnia Network. In Hardhat, deployments are defined through Ignition Modules. These modules are abstractions that describe a deployment, specifically, JavaScript functions that process the file you want to deploy. Open the ignition directory inside the project root's directory, then enter the directory named modules. Delete the Lock.ts file. Create a deploy.ts file and paste the following code:

import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

const BuyMeCoffee = buildModule("BuyMeCoffee", (m) => {
  const contract = m.contract("BuyMeCoffee");
  return { contract };
});

module.exports = BuyMeCoffee;

Deploy Contract

module.exports = {
  // ...
  networks: {
    somnia: {
      url: "https://dream-rpc.somnia.network",
      accounts: ["0xPRIVATE_KEY"], // put dev menomonic or PK here,
    },
   },
  // ...
};

Open a new terminal and deploy the smart contract to the Somnia Network. Run the command:

npx hardhat ignition deploy ./ignition/modules/deploy.ts --network somnia

You will see a confirmation message asking if you want to deploy to the Somnia Network. Answer by hitting “y” on your keyboard. This will confirm the deployment of the Smart Contract to the Somnia Network.

Congratulations. 🎉 You have deployed your “BuyMeCoffee” Smart Contract to the Somnia Network using Hardhat. 🎉

Verify Your Smart Contract

Update hardhat.config.jsAdd the following to your config file:

jsCopyEditmodule.exports = {
  solidity: "0.8.28",
  networks: {
    somnia: {
      url: "https://dream-rpc.somnia.network",
      accounts: ["YOUR_PRIVATE_KEY"],
    },
  },
  sourcify: {
    enabled: false,
  },
  etherscan: {
    apiKey: {
      somnia: "ETHERSCAN_API_KEY",
    },
    customChains: [
      {
        network: "somnia",
        chainId: 50312,
        urls: {
          apiURL: "https://shannon-explorer.somnia.network/api",
          browserURL: "https://shannon-explorer.somnia.network",
        },
      },
    ],
  },
};

Store your private key in a .env file and import it securely to avoid hardcoding.

After deploying your contract, run the Verify command. Copy the deployed address and run:

npx hardhat verify --network somnia DEPLOYED_CONTRACT_ADDRESS "ConstructorArgument1" ...

Example for a contract with one string constructor arg:

npx hardhat verify --network somnia 0xYourContractAddress "YourDeployerWalletAddress"

The verified Smart Contracts contain the Source Code, which anyone can review for bugs and malicious code. Users can also connect with and interact with the Verified Smart Contract.

Open the hardhat.config.js file and update the network information by adding Somnia Network to the list of networks. Copy your Wallet Address Private Key from MetaMask, and add it to the accounts section. Ensure there are enough STT Token in the Wallet Address to pay for Gas. You can get some from the Somnia .

The "0xPRIVATE_KEY" is used to sign the Transaction from your EOA without permission. When deploying the smart contract, you must ensure the EOA that owns the Private Key is funded with enough STT Tokens to pay for gas. Follow this to get your Private Key on MetaMask.

After deploying your contract, you can verify it using the . This allows your source code to be visible and validated on the .

Visit the and search for your contract address. If successful, the source code will appear under the “Contract” tab and show as verified.

Faucet
guide
Hardhat Verify plugin
Somnia Explorer
Somnia Explorer
Hardhat
Connect Your Wallet
Guide