How to Use the Ethereum Web3.js Library

·

Overview

Important Note:
Web3.js has officially been sunsetted. For updated Ethereum development library support, refer to tutorials using Ethers.js and viem on the Libraries page.

Web3.js is a collection of JavaScript libraries that enable developers to interact with Ethereum nodes via HTTP, IPC, or WebSocket protocols. Moonbeam offers Ethereum-compatible APIs, allowing seamless integration with Web3.js—just like on Ethereum.

This tutorial demonstrates how to:

👉 Get started with Moonbeam development

Prerequisites

Before beginning:

Environment Setup

  1. Initialize a JavaScript project:

    mkdir web3-examples && cd web3-examples && npm init -y
  2. Install dependencies:

    npm install web3 [email protected]

Configuring Web3.js for Moonbeam

Set up Web3.js for any Moonbeam network by specifying your RPC endpoint:

const { Web3 } = require('web3');
const web3 = new Web3('INSERT_RPC_API_ENDPOINT');

Example for Moonbase Alpha:

const web3 = new Web3('https://rpc.api.moonbase.moonbeam.network');

Sending Transactions

Balance Check Script

Create balances.js to check account balances:

const addressFrom = 'INSERT_FROM_ADDRESS';
const addressTo = 'INSERT_TO_ADDRESS';

const balances = async () => {
  const balanceFrom = web3.utils.fromWei(
    await web3.eth.getBalance(addressFrom),
    'ether'
  );
  const balanceTo = web3.utils.fromWei(
    await web3.eth.getBalance(addressTo),
    'ether'
  );
  console.log(`Balance of ${addressFrom}: ${balanceFrom} DEV`);
  console.log(`Balance of ${addressTo}: ${balanceTo} DEV`);
};
balances();

Transaction Script

Create transaction.js to send 1 DEV:

const accountFrom = {
  privateKey: 'INSERT_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS'
};
const addressTo = 'INSERT_TO_ADDRESS';

const send = async () => {
  const tx = await web3.eth.accounts.signTransaction(
    {
      gas: 21000,
      to: addressTo,
      value: web3.utils.toWei('1', 'ether'),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );
  const receipt = await web3.eth.sendSignedTransaction(tx.rawTransaction);
  console.log(`Tx Hash: ${receipt.transactionHash}`);
};
send();

Run both scripts sequentially to verify balances before/after the transfer.

Deploying Contracts

Compile Contract

  1. Save Incrementer.sol with Solidity code.
  2. Create compile.js:

    const fs = require('fs');
    const solc = require('solc');
    const input = {
      language: 'Solidity',
      sources: { 'Incrementer.sol': { content: fs.readFileSync('Incrementer.sol', 'utf8') } },
      settings: { outputSelection: { '*': { '*': ['*'] } } }
    };
    const output = JSON.parse(solc.compile(JSON.stringify(input)));
    module.exports = output.contracts['Incrementer.sol']['Incrementer'];

Deploy Script

Create deploy.js:

const contractFile = require('./compile');
const accountFrom = {
  privateKey: 'INSERT_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS'
};

const deploy = async () => {
  const contract = new web3.eth.Contract(contractFile.abi);
  const tx = contract.deploy({
    data: contractFile.evm.bytecode.object,
    arguments: [5] // Initial value
  });
  const signedTx = await web3.eth.accounts.signTransaction(
    {
      data: tx.encodeABI(),
      gas: await tx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );
  const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
  console.log(`Contract deployed at: ${receipt.contractAddress}`);
};
deploy();

Interacting with Contracts

Read Contract Data

Create get.js:

const { abi } = require('./compile');
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const contract = new web3.eth.Contract(abi, contractAddress);

const get = async () => {
  const data = await contract.methods.number().call();
  console.log(`Current number: ${data}`);
};
get();

Modify Contract State

Create increment.js and reset.js to update storage variables.

👉 Explore more Moonbeam features

FAQs

Is Web3.js still maintained?

No, Web3.js has been sunsetted. Consider using Ethers.js or viem for active support.

How do I get test tokens?

Use the Moonbase Alpha Faucet to request DEV tokens every 24 hours.

Can I use this on Moonriver?

Yes! Replace the RPC endpoint with a Moonriver-compatible one from supported providers.