web3 code example
Here is a simple example of Web3 code using JavaScript, which connects to the Ethereum blockchain using the Web3.js library. This example allows you to interact with a smart contract, retrieve the balance of an Ethereum address, and send a transaction.
First, make sure you have Web3.js installed:
npm install web3
Then, you can use the following code:
const Web3 = require('web3');
// Initialize Web3 instance (using Infura or a local node)
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
// Example Ethereum address
const address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';
// Get balance of an Ethereum address
async function getBalance() {
const balance = await web3.eth.getBalance(address);
console.log(`Balance of ${address}: ${web3.utils.fromWei(balance, 'ether')} ETH`);
}
// Send a transaction
async function sendTransaction() {
const senderAddress = 'YOUR_SENDER_ADDRESS';
const privateKey = 'YOUR_PRIVATE_KEY';
const receiverAddress = 'RECIPIENT_ADDRESS';
const amountInEther = '0.1';
const signedTx = await web3.eth.accounts.signTransaction(
{
to: receiverAddress,
value: web3.utils.toWei(amountInEther, 'ether'),
gas: 2000000,
gasPrice: '20000000000',
chainId: 1, // Mainnet
},
privateKey
);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log('Transaction successful with hash:', receipt.transactionHash);
}
// Call the functions
getBalance();
sendTransaction();
Explanation:
- Web3 instance: Connects to Ethereum via Infura. Replace
'YOUR_INFURA_PROJECT_ID'
with your Infura project ID. getBalance
function: Retrieves and logs the balance of the Ethereum address in Ether.sendTransaction
function: Signs and sends a transaction from one address to another using a private key. Replace'YOUR_SENDER_ADDRESS'
and'YOUR_PRIVATE_KEY'
with the appropriate values.
Make sure you replace the placeholders with your actual values.
Sure! Let's break down the code step by step:
1. Install Web3.js Library
npm install web3
- Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain. You need to install it first.
2. Initialize Web3 Instance
const Web3 = require('web3');
// Initialize Web3 instance (using Infura or a local node)
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
require('web3')
: This imports the Web3.js library.new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID')
: This initializes the Web3 instance, connecting it to the Ethereum mainnet via Infura (a service that allows you to interact with Ethereum nodes without having to run your own). You'll need to replaceYOUR_INFURA_PROJECT_ID
with your Infura project ID. Alternatively, you could connect to a local Ethereum node.
3. Get Balance of an Ethereum Address
const address = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';
// Get balance of an Ethereum address
async function getBalance() {
const balance = await web3.eth.getBalance(address);
console.log(`Balance of ${address}: ${web3.utils.fromWei(balance, 'ether')} ETH`);
}
address
: This is the Ethereum address whose balance we want to check. In this case, it's a famous Ethereum address.getBalance(address)
: This function retrieves the balance of the specified Ethereum address in wei (the smallest unit of Ether). The result is returned as a big number.web3.utils.fromWei(balance, 'ether')
: Converts the balance from wei to Ether (since 1 Ether = 1,000,000,000,000,000,000 wei).console.log
: Logs the balance to the console.
4. Send a Transaction
async function sendTransaction() {
const senderAddress = 'YOUR_SENDER_ADDRESS';
const privateKey = 'YOUR_PRIVATE_KEY';
const receiverAddress = 'RECIPIENT_ADDRESS';
const amountInEther = '0.1';
const signedTx = await web3.eth.accounts.signTransaction(
{
to: receiverAddress,
value: web3.utils.toWei(amountInEther, 'ether'),
gas: 2000000,
gasPrice: '20000000000',
chainId: 1, // Mainnet
},
privateKey
);
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log('Transaction successful with hash:', receipt.transactionHash);
}
senderAddress
: The Ethereum address from which the Ether will be sent. You need to replace'YOUR_SENDER_ADDRESS'
with the actual address.privateKey
: The private key of the sender's Ethereum address. This is crucial for signing the transaction and proving ownership of the address. Replace'YOUR_PRIVATE_KEY'
with the actual private key. Do not expose your private key in production!receiverAddress
: The Ethereum address that will receive the Ether. Replace'RECIPIENT_ADDRESS'
with the actual recipient's address.amountInEther
: The amount of Ether to send, in this case, 0.1 Ether.
Signing the Transaction:
-
web3.eth.accounts.signTransaction
: Signs the transaction using the sender's private key. It prepares the transaction by specifying:to
: The recipient's Ethereum address.value
: The amount to send in wei. This is converted from Ether usingweb3.utils.toWei
.gas
: The gas limit for the transaction (the maximum computational work that can be done).gasPrice
: The gas price (how much you are willing to pay for gas).chainId
: Identifies the Ethereum network (1 for mainnet, 3 for Ropsten testnet, etc.).
-
signedTx.rawTransaction
: This contains the raw, signed transaction data ready for submission to the blockchain.
Sending the Signed Transaction:
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
: Sends the signed transaction to the Ethereum network.receipt.transactionHash
: After the transaction is successfully mined, the transaction hash (a unique identifier) is returned, which you can use to track the transaction status.
5. Calling the Functions
getBalance();
sendTransaction();
- These function calls execute the code:
getBalance()
will fetch and display the balance of the given address.sendTransaction()
will send 0.1 Ether from the sender to the recipient.
Key Concepts:
- Web3.js: A JavaScript library for interacting with the Ethereum blockchain.
- Infura: A third-party service that allows you to connect to Ethereum without hosting your own node.
- Private Key: Used to sign transactions. It should be kept secret and secure.
- Gas: A measure of computational work for executing Ethereum transactions. Users pay for gas to incentivize miners to include their transactions in blocks.
Let me know if you need more details or clarifications on any part of the code!
Comments
Post a Comment