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:
// Your Metamask testnet private key:
// Must include the 0x prefix when using Web3.js in JavaScript
const privateKey = '0xYOUR_PRIVATE_KEY';
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);
async function sendMessage(text) {
console.log(`Sending message "${text}" to the IoTeX testnet...`);
const tx = contract.methods.postMessage(text);
const gas = await tx.estimateGas({ from: account.address });
const receipt = await tx.send({
from: account.address,
gas
});
console.log('Transaction receipt:', receipt);
}
sendMessage("Hello from IoTeX!");
To test your interaction script, simply run:
node index.js
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