Getting Started

How to install and initialize the Web3.js plugin for ZKsync

Follow these steps to get started with the Web3.js plugin for ZKsync.

Installation

Use a package manager like npm to install Web3.js and the Web3.js plugin for ZKsync.

npm install web3 web3-plugin-zksync

Register the plugin

To use the Web3.js plugin for ZKsync, register it with a Web3 instance.

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

async function main() {
  const web3: Web3 = new Web3(/* optional L1 provider */);
  // create a plugin instance with the L2 provider
  web3.registerPlugin(new ZKsyncPlugin("https://sepolia.era.zksync.dev"));
  const zksync: ZKsyncPlugin = web3.ZKsync;

  console.log("L2 contract addresses:", await zksync.ContractsAddresses);
}

main()
  .then(() => console.log("✅ Script executed successfully"))
  .catch((error) => console.error(`❌ Error executing script: ${error}`));

Plugin providers

In order for the plugin to work correctly and have access to its full range of capabilities, it's necessary to correctly configure the L1 and L2 providers. The Web3.js object should be instantiated with an L1 provider and the ZKsync plugin should be instantiated with an L2 provider. Do not use a ZKsync L2 provider to construct a Web3.js object. It is possible to use the ZKsync plugin for L2-only interactions without setting an L1 provider, but any capabilities that require L1 interactions (e.g. ZKsyncWallet.getBalanceL1, ZKsyncWallet.deposit) will not work.

Because the ZKsync Era network is EVM-compatible, many of the core Web3.js capabilities are available through the Web3.js plugin for ZKsync. In particular, the ZKsyncPlugin.L2 property, which is of type Web3ZKsyncL2, exposes the entire Web3 interface for the L2 ZKsync Era network. The following example demonstrates using the Web3 object to interact with the L1 network and using the ZKsyncPlugin object to interact with the L2 network.

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

async function main() {
  // use L1 provider to construct new Web3 object
  const web3: Web3 = new Web3("https://rpc.sepolia.org");
  // use L2 provider to construct new ZKsyncPlugin object
  web3.registerPlugin(new ZKsyncPlugin("https://sepolia.era.zksync.dev"));
  // once registered, the plugin is available with the Web3 ZKsync property
  const zksync: ZKsyncPlugin = web3.ZKsync;

  // use the Web3 object to get the L1 block number
  console.log("L1 block #:", await web3.eth.getBlockNumber());
  // or use the ZKsyncPlugin.L1 property
  console.log("L1 block #:", await zksync.L1.eth.getBlockNumber());
  // use the ZKsyncPlugin.L2 property to get the L2 block number
  console.log("L2 block #:", await zksync.L2.eth.getBlockNumber());
}

main()
  .then(() => console.log("✅ Script executed successfully"))
  .catch((error) => console.error(`❌ Error executing script: ${error}`));

Made with ❤️ by the ZKsync Community