Create a Simple Smart Contract using NodeJs

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.

  • Ethereum Node: The instance of the Ethereum network, can be a local node or a hosted node.
  • Provider: Web3.js or ethers.js with a provider like HTTP to connect to the Ethereum node.
  • Contact Interaction: These libraries help to encode and decode the data to communicate between the contracts on the Ethereum network.

how to make a simple smart contract in node js

Steps:

  1. Setup the NodeJs project and dependencies
  2. Create provider values and configure them in NodeJs
  3. Create and compile the contract
  4. Deploy the contract using web3.js


Setup the NodeJs project and dependencies

  1. Create a new node js project and install the ethers and dotenv npm packages

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.

  1. signup and log in to infura
  2. Create a new project and new key and save it in a .env file.
  3. PROVIDER_URL - It is a URL that links to your Ethereum network.
  4. PRIVATE_KEY - Waller private key. can generate from Infura.

PROVIDER_URL=https://your-provider-url
PRIVATE_KEY=your-private-key         

Create and compile the contract

  • Create the .sol file in your node js application, and paste this simple contract file.

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;
    }
}        

  • And here I used Remix for compilation.
  • Paste this code in the new file in Remix and compile it.
  • After the compilation, copy the abi and byteCode from the compiled contract.
  • In your nodeJs directory, create simple.json and paste these values.

{
    "abi": [ /* Paste the ABI here */ ],
    "bytecode": "0x..." /* Paste the bytecode here */
}        

  • abi - It's the bridge between the application and the contract on the blockchain.
  • byteCode - Binary representation of the smart contract.


Deploy the contract using web3.js

  1. Create the file deploy.js in the project directory.
  2. And paste this code, here I have used ethers.js version - 6.13.4
  3. In this code, we initiate the RPC provider and wallet.
  4. By using ethers.js we can get the wallet address, balance, nonce,privateKey, and so on.
  5. Using the provider, we can deploy and get the transaction details.

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

  1. Run the npm command

node deploy.js        

we can verify the output in logs, and see the transaction details and deployed contract address


Transaction Details


要查看或添加评论,请登录

Nanthakumar D的更多文章

社区洞察

其他会员也浏览了