Using Web3.js to interact with ZKsync

Learn how to use Web3js to interact with ZKsync and use built-in functions for ZKsync-specific JSON RPC methods.

This guide outlines how to use the ZKsync web3.js plugin to interact with ZKsync.

What you'll learn:

  • How to install web3.js and the ZKsync plugin
  • How to send RPC requests to ZKsync
  • How to use ZKsync-specific methods
GitHub

Tools:

  • - web3.js
guideweb3.js
Last Updated: May 09, 2024

Web3.js is a robust and flexible collection of libraries for TypeScript and JavaScript developers. It serves as an essential tool for connecting and crafting applications within the Ethereum ecosystem and can be extended to support other networks through its plugin system.

You can use the ZKsync plugin for Web3.js to interact with the ZKsync JSON-RPC API smart contracts deployed on ZKsync.

Installation

Start by adding Web3.js and the ZKsync plugin for Web3.js to your project. Open your terminal and execute the following command:

npm install --save web3 web3-plugin-zksync

This command installs the latest version of Web3.js and the ZKsync plugin for Web3.js and adds them to your project's dependencies.

Initial Setup

Initialization

Before using the ZKsync plugin for Web3.js, you need to initialize Web3 with a provider and register the plugin.

Example

import { Web3 } from "web3";
import { ZkSyncPlugin } from "web3-plugin-zksync";

const zkSyncRpcUrl: string = "https://sepolia.era.zksync.dev";

console.log(`📞 Connecting to ZKsync Era [${zkSyncRpcUrl}]`);
const web3: Web3 = new Web3(zkSyncRpcUrl);
web3.registerPlugin(new ZkSyncPlugin());
This examples uses the ZKsync Sepolia Testnet.

Ethereum JSON-RPC API

Use the Web3.js eth package to fetch data from the ZKsync Ethereum JSON-RPC API.

Fetch the Latest Block Number

const blockNumber = await web3.eth.getBlockNumber();
console.log(`Current block number: ${blockNumber}`);

ZKsync L2-Specific JSON-RPC API

The ZKsync plugin for Web3.js implements the ZKsync-specific methods from the zks_ namespace of the JSON-RPC API.

Fetch the Main Contract Address

const mainContract = await web3.zkSync.rpc.getMainContract();
console.log(`Main contract: ${mainContract}`);

Wallet Configuration

Refer to the Web3.js documentation for details regarding wallet configuration.


Made with ❤️ by the ZKsync Community