Interact with deployed Smart Contracts using NodeJs and Ethers.js
In our previous post, we covered how to develop and deploy the smart contract using Ethers.js
here I explained how to interact with the deployed contract.
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 public data;
function set(uint256 _data) public {
data = _data;
}
function get() public view returns (uint256) {
return data;
}
}
2. Required config - contractAddress
const contractAddress = "0x85E7058484R725789b7873c2563F864C12AAf9BB";
//Replace with your contract address
3. Connect the provider and wallet.
4. Create the interact.js file in the project directory.
const { ethers } = require("ethers");
const fs = require("fs");
require("dotenv").config();
// Configuration
const contractAddress = "0x85D7058484C725789b7873c2563F864C12AAf9BB"; // Replace with your contract address
async function interactWithContract() {
const contractJson = JSON.parse(fs.readFileSync("simple.json"));
const abi = contractJson.abi;
const bytecode = contractJson.bytecode;
const provider = new ethers.JsonRpcProvider(process.env.PROVIDER_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const contract = new ethers.Contract(contractAddress, abi, wallet);
const currentData = await contract.get();
console.log("Current stored data:", currentData.toString());
//Set data
const newData = 154;
console.log(`Updating data to: ${newData}...`);
const tx = await contract.set(newData);
await tx.wait();
console.log("Transaction confirmed!");
// Get the updated stored value
const updatedData = await contract.get();
console.log("Updated stored data:", updatedData.toString());
}
interactWithContract().catch(console.error);
5. Create the contract instance with the address, abi, and wallet.
6. By using instance, we can call the contract methods.