Deploy a simple contract

In this first tutorial, you'll write and deploy a basic Ethereum-compatible smart contract to the IoTeX testnet using Solidity, Hardhat, and MetaMask. The contract includes a simple function that accepts a string and emits an event with that string — allowing anyone to write a permanent message on the IoTeX blockchain.

Prerequisites

Add IoTeX Testnet to Metamask Claim some Testnet IOTX

Step 1: Set Up Your Project

mkdir iotex-contract-tutorial
cd iotex-contract-tutorial
npm init -y
npm install --save-dev hardhat
npx hardhat

When prompted, select Create a JavaScript project from the menu, follow the prompts and accept the defaults.

Step 2: Write the Contract

Replace the contents of contracts/Lock.sol with the following:

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

contract MessageBoard {
    event MessagePosted(address sender, string message);

    function postMessage(string calldata message) external {
        emit MessagePosted(msg.sender, message);
    }
}

Step 3: Configure for IoTeX

Ensure dependencies are installed:

npm install @nomicfoundation/hardhat-toolbox

Update hardhat.config.js:

require("@nomicfoundation/hardhat-toolbox");

module.exports = {
  solidity: "0.8.21",
  networks: {
    iotex_testnet: {
      url: "https://babel-api.testnet.iotex.io",
      accounts: ["<YOUR_PRIVATE_KEY>"]
    }
  }
};

Step 4: Deploy the Contract

Create a new file scripts/deploy.js:

const hre = require("hardhat");

async function main() {
  const MessageBoard = await hre.ethers.getContractFactory("MessageBoard");
  const contract = await MessageBoard.deploy();

  await contract.waitForDeployment();
  console.log("Contract deployed to:", await contract.getAddress());
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Then deploy:

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

You should see your contract address printed in the terminal. You’ve now deployed your first contract to the IoTeX Blockchain!


Part 2: Interact with Your Contract Using JavaScript

In the second tutorial, you'll build a Node.js application to interact with the deployed contract using Web3.js. Instead of sending IOTX tokens, your application will call the contract's function to send messages and view events logged on-chain.

These tutorials use JavaScript (Node.js), Solidity, MetaMask, and Web3.js — all common tools for Ethereum developers — to provide a smooth onboarding experience for building on IoTeX Layer 1.


Last updated