[ad_1]
Web3.js is a JavaScript library that allows developers to interact with the Ethereum blockchain. It provides a collection of APIs that can be used to retrieve user accounts, send transactions, interact with smart contracts, and more.
Installing Node.js and npm
Follow the link to install: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
Installing Web3.js
npm install web3
Connecting to an Ethereum client
// Check for ethereum provider in modern browsers
if (window.ethereum) {
App.web3Provider = window.ethereum;
try {
// Request user's account access
await window.ethereum.enable();
} catch (error) {
// Handle user denied account access
console.error("User denied account access")
}
}
// Check for web3 provider in legacy browsers
else if (window.web3) {
App.web3Provider = window.web3.currentProvider;
}
// Use local client as fallback
else {
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
// Create web3 instance
web3 = new Web3(App.web3Provider);
Getting account balance
This example gets the balance of the account with the address ‘0x742d35Cc6634C0532925a3b844Bc454e4438f44e’ and returns the balance in wei. We use web3.utils.fromWei()
to convert wei to ether.
web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
.then(balance => console.log(web3.utils.fromWei(balance, 'ether')));
Sending Ether
Here is an example of how to use Web3.js to send Ether from one account to another:
// Set the default account to use for sending the transaction
web3.eth.defaultAccount = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';// The address of the account you want to send Ether to
const recipientAddress = '0x9cB0478f3e6e1a3F3E36E7c6f9f6aF7D9e0E8A7f';
// The amount of Ether you want to send
const amount = '0.1';
// Create a raw transaction object
const rawTransaction = {
from: web3.eth.defaultAccount,
to: recipientAddress,
value: web3.toWei(amount, 'ether'),
gasPrice: web3.toWei('20', 'gwei'),
gas: 21000
};
// Sign the transaction
web3.eth.signTransaction(rawTransaction)
.then(signedTx => {
// Send the signed transaction
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('receipt', receipt => {
console.log("Ether sent successfully!");
console.log(receipt);
})
.on('error', error => {
console.log("Error sending Ether:", error);
});
});
Interacting with smart contracts
Here’s an example of how to use Web3.js to interact with a deployed smart contract on the Ethereum blockchain:
const contractABI = [...]; // ABI of the contract
const contractAddress = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e'; // Address of the contract on the blockchain// Create a new contract object
const myContract = new web3.eth.Contract(contractABI, contractAddress);
// Call a constant function of the contract
myContract.methods.get().call()
.then(result => {
console.log(result);
})
.catch(error => {
console.log(error);
});
// Send a transaction to the contract
myContract.methods.set('Hello, Ethereum!')
.send({ from: web3.eth.defaultAccount, gas: '50000', value: web3.utils.toWei('0.1', 'ether') })
.then(receipt => {
console.log(receipt);
})
.catch(error => {
console.log(error);
});
I do this because I love it, but if you want me to buy me a cup of coffee I won’t say no :O )Thanks ^^
Ether : 0x7C5081f6eb1Fbc7b99BA07522C0b51E250b33163
Bitcoin : bc1qtwlga9xpksqlryyr00xxwfwmmges0wryptc9dk
- Your First Solidity App: A Step-by-Step Guide
- Mastering Solidity Basics: A Beginner’s Guide to Data Types
- Mastering Functions in Solidity: A Beginner’s Guide
- Official web3.js documentation
New to trading? Try crypto trading bots or copy trading on best crypto exchanges
[ad_2]
Source link