# Deploy with Hardhat

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.\
\
[Hardhat](https://hardhat.org) 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.

{% hint style="success" %}
Somnia Mainnet is LIVE. To deploy on Somnia Mainnet, you will need SOMI Tokens. Please refer to the [guide](/get-started/getting-started-for-mainnet.md) on Moving from Testnet to Mainnet.
{% endhint %}

{% embed url="<https://www.youtube.com/watch?v=4F9zrCsNjmE>" %}

## 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 [Connect Your Wallet](/get-started/connect-your-wallet-to-mainnet.md).
3. Hardhat is installed and set up on your local machine. See [Guide](https://hardhat.org/hardhat-runner/docs/getting-started#installation).

## Initialise Hardhat Project

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

```bash
npx hardhat init
```

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

<figure><img src="/files/OIMPZw7X6WS0NMqk9ThK" alt=""><figcaption></figcaption></figure>

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:

```solidity
// 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:

```bash
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:

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

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

module.exports = BuyMeCoffee;
```

## Deploy 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 [Faucet](https://devnet.somnia.network/).

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

> 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 [guide](https://support.metamask.io/managing-my-wallet/secret-recovery-phrase-and-private-keys/how-to-export-an-accounts-private-key/) to get your Private Key on MetaMask.

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

```bash
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.

<figure><img src="/files/FXdFH5mggQMDSsfPq34S" alt=""><figcaption></figcaption></figure>

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

## **Verify Your Smart Contract**

After deploying your contract, you can verify it using the [Hardhat Verify plugin](https://hardhat.org/hardhat-runner/plugins/nomicfoundation-hardhat-verify). This allows your source code to be visible and validated on the [Somnia Explorer](https://shannon-explorer.somnia.network).

#### Update `hardhat.config.ts`Add the following to your config file:

```js
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

const config: HardhatUserConfig = {
  solidity: "0.8.28",
  networks: {
    somnia: {
      url: "https://dream-rpc.somnia.network",
      accounts: ["YOUR_PRIVATE_KEY"],
    },
  },
  sourcify: {
    enabled: false,
  },
  etherscan: {
    apiKey: {
      somnia: "empty",
    },
    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:

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

Example for a contract with one string constructor arg:

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

Visit the [Somnia Explorer](https://shannon-explorer.somnia.network) and search for your contract address. If successful, the source code will appear under the **“Contract”** tab and show as **verified**.

<div data-full-width="true"><figure><img src="/files/M4ufGYemH2Mx4K8GdhMH" alt=""><figcaption></figcaption></figure> <figure><img src="/files/dks5HHgPrGonDmr13mZM" alt=""><figcaption></figcaption></figure></div>

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.somnia.network/developer/development-frameworks/deploy-with-hardhat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
