Create a Simple Smart Contract using NodeJs
yes, NodeJs can create and interact with smart contracts on blockchain platforms like Ethereum by using JSON-RPC protocol. This protocol allows remote procedure calls over HTTP, WebSocket, or IPC.
We need Ethereum Node, provider, and contract interaction to do this interaction.
how to make a simple smart contract in node js
Steps:
Setup the NodeJs project and dependencies
npm install ethers dotenv
Create provider values and configure them in NodeJs
here I choose Infura, and you can select any Ethereum network to deploy the contract.
PROVIDER_URL=https://your-provider-url
PRIVATE_KEY=your-private-key
领英推荐
Create and compile the 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;
}
}
{
"abi": [ /* Paste the ABI here */ ],
"bytecode": "0x..." /* Paste the bytecode here */
}
Deploy the contract using web3.js
require("dotenv").config();
const { ethers } = require("ethers");
const fs = require("fs");
const deploy = async () => {
const provider = new ethers.JsonRpcProvider(process.env.PROVIDER_URL);
console.log(provider);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const contractJson = JSON.parse(fs.readFileSync("simple.json"));
const abi = contractJson.abi;
const bytecode = contractJson.bytecode;
console.log("Deploying contract...");
const factory = new ethers.ContractFactory(abi, bytecode, wallet);
const deployTx = factory.getDeployTransaction();
const gasEstimate = await provider.estimateGas(deployTx);
console.log("Gas estimate:", gasEstimate.toString());
const balance = await provider.getBalance(wallet.address);
console.log("Wallet Balance: ", balance, "ETH");
// Convert balance from wei to ether
const balanceInEth = ethers.formatEther(balance);
console.log("Wallet Balance: ", balanceInEth, "ETH");
const contract = await factory.deploy(); // Deploy the contract
// Wait for the deployment to be mined
const receipt = contract.deploymentTransaction(); // Wait for the contract deployment transaction
console.log("Contract deployed at address:", receipt);
};
deploy().catch((err) => {
console.error("Deployment failed:", err);
});
Deploy the contract using web3.js
node deploy.js
we can verify the output in logs, and see the transaction details and deployed contract address