Web3.js is a powerful JavaScript library for interacting with Ethereum-compatible blockchains. In this guide, we’ll walk you through setting up your environment, sending transactions, and deploying smart contracts step by step. To get you started quickly, we’ll use a pre-configured GitHub repository.
Step 1: Clone the GitHub Repository
To save time, clone the pre-configured repository with all the essential files:
git clone https://github.com/Vikash-8090-Yadav/Conflux-Tutorial
Step 2: Install Dependenciesz
Run the following command to install the required libraries:
npm install
npm run dev
Step3: Setup the HTTP connection
Prepare your Web3 HTTP connection to align with any evm-powered network. To synchronize your project, you must secure an endpoint and API key of your own.
Here’s how you can get started:
// Create a Web3 instance:
const Web3 = require('web3');
// Insert your RPC URL to establish an HTTP connection to your RPC endpoint:
const web3 = new Web3('RPC-API-ENDPOINT-HERE');
Step 4: Check Account Balances
To check balances, use the balances.js script. Open the file and configure your sender and recipient addresses:
const fetchBalance = async () => {
if (!address) {
alert('Please login first')
return
}
setBalanceLoading(true)
try {
let web3 = new Web3(window.ethereum)
const balanceWei = await web3.eth.getBalance(address)
const finalBalance = web3.utils.fromWei(balanceWei, "ether")
setBalance(finalBalance)
} catch (error) {
console.error('Error fetching balance:', error)
alert('Failed to fetch balance. Please try again.')
} finally {
setBalanceLoading(false)
}
}
Step 5: Send a Transaction
To send a transaction, use the transaction.js script. Open the file and update it with your private key and addresses:
const transact = async () => {
if (!address) {
alert('Please connect your wallet first')
return
}
const receiverAddress = '0x80F9839DDfa157498eB112c2081E339FB75bCD35'
const amountInCFX = '1'
try {
const web3Instance = new Web3(window.ethereum)
const amountInWei = web3Instance.utils.toWei(amountInCFX, 'ether')
const gasPrice = await web3Instance.eth.getGasPrice()
const gasEstimate = await web3Instance.eth.estimateGas({
from: address,
to: receiverAddress,
value: amountInWei
})
const transactionParameters = {
from: address,
to: receiverAddress,
value: `0x${BigInt(amountInWei).toString(16)}`,
gas: `0x${Math.ceil(Number(gasEstimate) * 1.2).toString(16)}`,
gasPrice: `0x${BigInt(gasPrice).toString(16)}`
}
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
})
setTransactionHash(txHash)
} catch (error) {
console.error('Transaction error:', error)
alert(`Failed to send CFX: ${error.message}`)
}
}
This will transfer 1 ETH from the sender to the receiver and output the transaction hash.
Step 6: Deploy a Smart Contract
Write the Contract
The repository already includes a file named Incrementer.sol. Here’s the content:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Greeting {
string private greeting ="Good Luck";
// Constructor to initialize the greeting
// Function to set a new greeting
function setGreeting(string memory _newGreeting) public {
greeting = _newGreeting;
}
// Function to get the current greeting
function getGreeting() public view returns (string memory) {
return greeting;
}
}
Deploy the Contract
To deploy the contract, use the deploy.js script. Update it with your private key:
require ('@nomiclabs/hardhat-waffle');
require('@openzeppelin/hardhat-upgrades');
require('@nomicfoundation/hardhat-ethers');
require('@nomicfoundation/hardhat-verify');
module.exports = {
solidity: "0.8.10",
defaultNetwork: "confluxTestnet",
networks:{
hardhat:{},
confluxTestnet: {
url: "https://evmtestnet.confluxrpc.com " || "",
chainId:71 ,
accounts: ['prvtekey']
},
}
};
Step 7: Interact with the Contract
Read Contract Data
Use the get.js script to fetch the current value:
const readSM = async () => {
try {
const contractPublic = new web3.eth.Contract(ABI.abi, smartcontractAddress);
const result = await contractPublic.methods.getGreeting().call();
setReadResult(result);
} catch (error) {
console.error('Error reading from smart contract:', error);
alert('Failed to read from smart contract. Please try again.');
}
}
Write Contract Data
Use the increment.js script to increment the value:
const writeSM = async () => {
if (!address) {
alert('Please connect your wallet first')
return
}
if (!newGreeting) {
alert('Please enter a new greeting')
return
}
setWriteLoading(true)
try {
const web3Instance = new Web3(window.ethereum)
const contract = new web3Instance.eth.Contract(ABI.abi, smartcontractAddress)
const data = contract.methods.setGreeting(newGreeting).encodeABI()
const gasEstimate = await contract.methods.setGreeting(newGreeting)
.estimateGas({ from: address })
const gasPrice = await web3Instance.eth.getGasPrice()
const gasLimit = `0x${Math.ceil(Number(gasEstimate) * 1.2).toString(16)}`
const gasPriceHex = `0x${BigInt(gasPrice).toString(16)}`
const transactionParameters = {
to: smartcontractAddress,
from: address,
data: data,
gas: gasLimit,
gasPrice: gasPriceHex
}
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
})
alert(`Transaction submitted! Hash: ${txHash}`)
setNewGreeting('')
} catch (error) {
console.error('Error writing to smart contract:', error)
alert(`Failed to update greeting: ${error.message}`)
} finally {
setWriteLoading(false)
}
}
Conclusion
Congratulations! You’ve successfully set up a Web3.js project, sent transactions, deployed a smart contract, and interacted with it. This workflow lays the foundation for building robust blockchain applications.
Feel free to explore further by modifying the Incrementer.sol contract or integrating other Web3.js features. Happy coding!