Getting Started with eth
Package
Introduction
The web3-eth
package provides a set of powerful functionalities to interact with the Ethereum blockchain and smart contracts. In this tutorial, we will guide you through the basics of using the web3-eth
package of web3.js version 4. We will be using TypeScript throughout the examples.
Overview
Here is a high-level overview of the steps we will be taking in this tutorial:
- Setting up the Environment
- Create a new project directory and initialize a new Node.js project
- Set up web3.js and connect to the Ganache network
- Interact with the Ethereum blockchain using web3.js
- Importing specific package
- Send different type of transactions
Step 1: Setting up the Environment
Before we start writing and deploying our contract, we need to set up our environment. For that, we need to install the following:
Ganache
- Ganache is a personal blockchain for Ethereum development that allows you to see how your smart contracts function in real-world scenarios. You can download it from http://truffleframework.com/ganacheNode.js
- Node.js is a JavaScript runtime environment that allows you to run JavaScript on the server-side. You can download it from https://nodejs.org/en/download/npm
- Node Package Manager is used to publish and install packages to and from the public npm registry or a private npm registry. Here is how to install it https://docs.npmjs.com/downloading-and-installing-node-js-and-npm. (Alternatively, you can use yarn instead of npm https://classic.yarnpkg.com/lang/en/docs/getting-started/)
Step 2: Create a new project directory and initialize a new Node.js project
First, create a new project directory for your project and navigate into it:
mkdir web3-eth-tutorial
cd web3-eth-tutorial
Next, initialize a new Node.js project using npm:
npm init -y
This will create a new package.json
file in your project directory.
npm i typescript @types/node
This will install typescript for our project and install the types for node.
Step 3: Set up web3.js and connect to the Ganache network
In this step, we will set up the web3.js library and connect to the Ganache network. So, be sure to run Ganache if you did not already did.
First, install the web3
package using npm:
npm i web3
Next, create a new file called index.ts
in your project directory and add the following code to it:
import { Web3 } from 'web3';
// Set up a connection to the Ganache network
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
/* NOTE:
instead of using ganache, you can also interact with a testnet/mainnet using another provider
https://app.infura.io/
https://dashboard.alchemy.com/
or use a public provider https://chainlist.org/
*/
// Log the current block number to the console
const block = await web3.eth.getBlockNumber();
console.log('Last block:', block);
// ↳ Last block: 4975299n
This code sets up a connection to the Ganache network and logs the current block number to the console.
Run the following command to test the connection:
npx ts-node index.ts
If everything is working correctly, you should see the current block number logged to the console. However, if you got an error with the reason connect ECONNREFUSED 127.0.0.1:7545
then double check that you are running Ganache locally on port 7545
.
Step 4: Interact with the Ethereum blockchain using web3.js
In this step, we will use web3.js to interact with the Ganache network.
In the first example, we are going to send a simple value transaction.
Create a file named transaction.ts
and fill it with the following code:
import { Web3 } from 'web3';
import fs from 'fs';
import path from 'path';
// Set up a connection to the Ethereum network
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
web3.eth.Contract.handleRevert = true;
async function interact() {
//fetch all the available accounts
const accounts = await web3.eth.getAccounts();
console.log(accounts);
let balance1, balance2;
//The initial balances of the accounts should be 100 Eth (10^18 wei)
balance1 = await web3.eth.getBalance(accounts[0]);
balance2 = await web3.eth.getBalance(accounts[1]);
console.log(balance1, balance2);
//create a transaction sending 1 Ether from account 0 to account 1
const transaction = {
from: accounts[0],
to: accounts[1],
// value should be passed in wei. For easier use and to avoid mistakes,
// we utilize the auxiliary `toWei` function:
value: web3.utils.toWei('1', 'ether'),
};
//send the actual transaction
const transactionHash = await web3.eth.sendTransaction(transaction);
console.log('transactionHash', transactionHash);
balance1 = await web3.eth.getBalance(accounts[0]);
balance2 = await web3.eth.getBalance(accounts[1]);
// see the updated balances
console.log(balance1, balance2);
// irrelevant with the actual transaction, just to know the gasPrice
const gasPrice = await web3.eth.getGasPrice();
console.log(gasPrice);
}
(async () => {
await interact();
})();