Learn Web3.js Basics – Ethereum Development for Beginners

I’m glad you’re interested in learning Web3.js, a JavaScript library for building on Ethereum. In this blog post, I’ll explain what Web3.js is, why you should use it, and how to get started with some basic examples. Let’s begin!

What is Web3.js?

Web3.js is a JavaScript library that allows you to interact with the Ethereum blockchain from your web browser or Node.js application. You can use Web3.js to do things like:

  • Connect to local or remote Ethereum nodes using different protocols (HTTP, WebSocket, IPC)
  • Create and manage Ethereum accounts, wallets, and keys
  • Send and receive Ether and other tokens
  • Deploy and interact with smart contracts
  • Subscribe to events and logs emitted by smart contracts
  • Query and manipulate data stored on the blockchain
  • Use various utility functions for common tasks (hashing, encoding, converting, etc.)

Web3.js is the most popular and widely used library for Ethereum development, and it is constantly updated and maintained by the community. It is also modular, meaning you can import only the packages you need for your project.

Why use Web3.js?

Web3.js is a powerful and versatile tool that enables you to create decentralized applications (dApps) that run on the Ethereum network. By using Web3.js, you can leverage the benefits of blockchain technology, such as:

  • Transparency: All transactions and data on the blockchain are public and verifiable, ensuring trust and accountability.
  • Security: The blockchain is secured by cryptography and consensus algorithms, making it resistant to tampering and hacking.
  • Immutability: Once data is written on the blockchain, it cannot be changed or deleted, ensuring permanence and reliability.
  • Decentralization: The blockchain is distributed and maintained by a network of nodes, eliminating the need for intermediaries and central authorities.

How to get started with Web3.js?

To get started with Web3.js, you need to have some prerequisites installed on your system, such as:

  • Node.js and npm: Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside of the browser. npm is a package manager that allows you to install and manage dependencies for your project. You can download and install Node.js and npm from here.
  • Ganache: Ganache is a personal blockchain that allows you to run a local Ethereum node for development and testing purposes. You can download and install Ganache from here.
  • Truffle: Truffle is a framework that helps you create, compile, deploy, and test smart contracts. You can install Truffle using npm by running the following command in your terminal:
npm install -g truffle

Once you have these prerequisites installed, you can create a new project folder and initialize it with npm by running the following commands in your terminal:

mkdir web3js-demo
cd web3js-demo
npm init -y

This will create a package.json file that contains the metadata and dependencies for your project. Next, you need to install Web3.js as a dependency by running the following command in your terminal:

npm install web3

This will download and install the latest version of Web3.js in your node_modules folder. You can check the version of Web3.js by running the following command in your terminal:

npm list web3

You should see something like this:

web3js-demo@1.0.0 /path/to/web3js-demo
└── web3@1.6.1

Now you are ready to write some code using Web3.js. To do that, you need to create a new JavaScript file in your project folder, for example, index.js, and import the Web3 module by adding the following line at the top of the file:

const Web3 = require('web3');

This will give you access to the Web3 constructor, which you can use to create a new Web3 instance. A Web3 instance is an object that contains various methods and properties for interacting with the Ethereum blockchain. To create a Web3 instance, you need to pass a provider as an argument to the Web3 constructor. A provider is an object that connects your Web3 instance to a specific Ethereum node. You can use different types of providers, such as:

  • HTTPProvider: This provider connects to an Ethereum node via HTTP protocol. You need to specify the URL of the node as a string, for example:
const web3 = new Web3('http://localhost:8545');

This will connect your Web3 instance to a local node running on port 8545, which is the default port for Ganache.

  • WebSocketProvider: This provider connects to an Ethereum node via WebSocket protocol. You need to specify the URL of the node as a string, for example:
const web3 = new Web3('ws://localhost:8546');

This will connect your Web3 instance to a local node running on port 8546, which is the default port for Ganache WebSocket.

  • IPCProvider: This provider connects to an Ethereum node via IPC (Inter-Process Communication) protocol. You need to specify the path of the node as a string, for example:
const web3 = new Web3('/path/to/geth.ipc');

This will connect your Web3 instance to a local node running on geth.ipc, which is the default path for Geth IPC.

You can also use other providers, such as Infura, which is a service that provides access to remote Ethereum nodes via HTTP or WebSocket protocols. You can sign up for a free account on Infura and get an API key from here. Then you can use the API key to create a provider, for example:.

const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_API_KEY');

This will connect your Web3 instance to the main Ethereum network via Infura.

Once you have created a Web3 instance, you can use it to perform various operations on the Ethereum blockchain, such as:

  • Get the current block number:
web3.eth.getBlockNumber().then(console.log);

This will print the latest block number on the console.

  • Get the balance of an account:
web3.eth.getBalance('0x123456789abcdef0123456789abcdef0123456789').then(console.log);

This will print the balance of the specified account in wei (the smallest unit of Ether) on the console.

  • Send Ether from one account to another:
web3.eth.sendTransaction({
  from: '0x123456789abcdef0123456789abcdef0123456789',
  to: '0x987654321fedcba0987654321fedcba0987654321',
  value: web3.utils.toWei('1', 'ether')
}).then(console.log);

This will send 1 Ether from the first account to the second account and print the transaction hash on the console.

  • Deploy a smart contract:
const abi = [
  {
    "inputs": [],
    "name": "greet",
    "outputs": [
      {
        "internalType": "string",
        "name": "",
        "type": "string"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "string",
        "name": "_greeting",
        "type": "string"
      }
    ],
    "name": "setGreeting",
    "outputs": [],
    "stateMutability": "nonpayable",
    "type": "function"
  }
];

const bytecode = '0x608060405234801561001057600080fd5b5060405161011f38038061011f8339818101604052602081101561003357600080fd5b8101908080519060200190929190505050806000819055505061010a806100576000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036040811015604b57600080fd5b810190808035906020019092919080359060200190929190505050606c565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220f8d7a8f2c0a8f3a9f0f5f2f0c9e9f0f5f2f0f0f0f0f0f0f0f0f0f0f0f0f0f0f064736f6c63430008070033';

const contract = new web3.eth.Contract(abi);

contract.deploy({
  data: bytecode,
  arguments: ['Hello, world!']
}).send({
  from: '0x123456789abcdef0123456789abcdef0123456789',
  gas: 3000000
}).then(console.log);

This will deploy a simple smart contract that has a greet function that returns a greeting message and a setGreeting function that allows changing the greeting message. The contract is deployed with the initial greeting message of ‘Hello, world!’. The code prints the contract address and the deployment receipt on the console.

  • Interact with a smart contract:
const abi =[ { “inputs”: [], “name”: “greet”, “outputs”: [ { “internalType”: “string”, “name”: “”, “type”: “string” } ], “stateMutability”: “view”, “type”: “function” }, { “inputs”: [ { “internalType”: “string”, “name”: “_greeting”, “type”: “string” } ], “name”: “setGreeting”, “outputs”: [], “stateMutability”: “nonpayable”, “type”: “function” } ];

const contract = new web3.eth.Contract(abi, ‘0x987654321fedcba0987654321fedcba0987654321’);

contract.methods.greet().call().then(console.log);

contract.methods.setGreeting(‘Hello, Web3.js!’).send({ from: ‘0x123456789abcdef0123456789abcdef0123456789’, gas: 100000 }).then(console.log);

This will call the greet function of the contract and print the current greeting message on the console. Then it will call the setGreeting function of the contract and change the greeting message to ‘Hello, Web3.js!’. The code prints the transaction hash and the receipt on the console.

I hope you enjoyed this blog post and learned something new. If you have any questions or feedback, please leave a comment below. Thank you for reading! 😊

Leave a Comment

Your email address will not be published. Required fields are marked *