Build a client for your contract

In this tutorial, you'll build a Node.js application that connects to the IoTeX testnet using Web3.js and interacts with the smart contract you just deployed inDeploy a simple contract.

Step 1: Set Up Your Project

mkdir iotex-client
cd iotex-client
npm init -y
npm install web3

Step 2: Connect to the IoTeX Testnet

Create a file index.js and initialize Web3:

const { Web3 } = require('web3');

const web3 = new Web3('https://babel-api.testnet.iotex.io');

Step 3: Prepare Contract Details

Replace the following placeholders with your actual contract address from Deploy a simple contract.

const contractAddress = 'YOUR_DEPLOYED_CONTRACT_ADDRESS';
const abi = [
  {
    "anonymous": false,
    "inputs": [
      { "indexed": false, "internalType": "address", "name": "sender", "type": "address" },
      { "indexed": false, "internalType": "string", "name": "message", "type": "string" }
    ],
    "name": "MessagePosted",
    "type": "event"
  },
  {
    "inputs": [
      { "internalType": "string", "name": "message", "type": "string" }
    ],
    "name": "postMessage",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
];

const contract = new web3.eth.Contract(abi, contractAddress);

Step 4: Send a Message

Continue editing index.js with the following and replace YOUR_PRIVATE_KEY with your Metamask testnet private key:

To test your interaction script, simply run:

This will send your message to the smart contract and print the transaction receipt. You’re interacting with smart contracts on IoTeX Layer 1!


Last updated