Ethersv6 API

BrowserProvider

BrowserProvider object for interacting with ZKsync.

The BrowserProvider class is designed for integrating ZKsync with Web3 browser wallets such as Metamask and WalletConnect. It provides an easy way to interact with ZKsync Era using standard browser wallets.

constructor

Returns a provider object by extending the constructor of the Provider class and accepting an Eip1193Provider instead of a node URL.

Inputs

ParameterTypeDescription
ethereumEip1193ProviderThe Eip1193Provider class instance. For instance, Metamask is window.ethereum.
network?NetworkishNetwork name.
constructor(ethereum: Eip1193Provider, network?: Networkish)

`

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);

estimateFee

Returns an estimated fee for a requested transaction.

Inputs

ParameterTypeDescription
transactionTransactionRequestTransaction request.
async estimateFee(transaction: TransactionRequest): Promise<Fee>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const fee = await provider.estimateFee

({
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  to: "0xa61464658AfeAf65CccaaFD3a512b69A83B77618",
  value: `0x${BigInt(7_000_000_000).toString(16)}`,
});
console.log(`Fee: ${utils.toJSON(fee)}`);

estimateGasL1

Returns an estimate of the amount of gas required to submit a transaction from L1 to L2.

Inputs

ParameterTypeDescription
transactionTransactionRequestTransaction request.
async estimateGasL1(transaction: TransactionRequest): Promise<bigint>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const gasL1 = await provider.estimateGasL1({
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  to: await provider.getMainContractAddress(),
  value: 7_000_000_000,
  customData: {
    gasPerPubdata: 800,
  },
});
console.log(`L1 gas: ${BigInt(gasL1)}`);

getAllAccountBalances

Returns all balances for confirmed tokens given by an account address.

Inputs

ParameterTypeDescription
addressAddressAccount address.
async getAllAccountBalances(address: Address): Promise<BalancesMap>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const balances = await provider.getAllAccountBalances("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049");
console.log(`All balances: ${utils.toJSON(balances)}`);

getBalance

Returns the account balance for the specified account address, block tag, and token address.

Inputs

ParameterTypeDescription
addressAddressAccount address.
blockTag?BlockTagBlock tag for getting the balance on. Latest committed block is default.
tokenAddress?AddressToken address. ETH is default.
async getBalance(address: Address, blockTag?: BlockTag, tokenAddress?: Address): Promise<bigint>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const account = "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049";
const tokenAddress = "0x927488F48ffbc32112F1fF721759649A89721F8F"; // Crown token which can be minted for free
console.log(`ETH balance: ${await provider.getBalance(account)}`);
console.log(`Token balance: ${await provider.getBalance(account, "latest", tokenAddress)}`);

getBaseTokenContractAddress

Returns the L1 base token address.

async getBaseTokenContractAddress(): Promise<Address>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Base token: ${await provider.getBaseTokenContractAddress()}`);

getBlock

Returns the block for the given block hash or block tag.

Inputs

ParameterTypeDescription
blockHashOrBlockTagBlockTagBlock tag for getting the balance on.
includeTxs?booleanWhether to fetch transactions that are in block.
async getBlock(blockHashOrBlockTag: BlockTag, includeTxs?: boolean): Promise<Block>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Block: ${utils.toJSON(await provider.getBlock("latest", true))}`);

getBlockDetails

Returns additional ZKsync-specific information about the L2 block.

Inputs

ParameterTypeDescription
numbernumberBlock number.
async getBlockDetails(number: number): Promise<BlockDetails>

Example

import { BrowserProvider, utils } from "zksync

-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Block details: ${utils.toJSON(await provider.getBlockDetails(90_000))}`);

getBridgehubContractAddress

Returns the Bridgehub smart contract address.

async getBridgehubContractAddress(): Promise<Address>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Bridgehub: ${await provider.getBridgehubContractAddress()}`);

getBytecodeByHash

Returns bytecode of a contract given by its hash.

Inputs

ParameterTypeDescription
bytecodeHashBytesLikeBytecode hash.
async getBytecodeByHash(bytecodeHash: BytesLike): Promise<Uint8Array>

Example

import { BrowserProvider, utils } from "zksync-ethers";

// Bytecode hash can be computed by following these steps:
// const testnetPaymasterBytecode = await provider.getCode(await provider.getTestnetPaymasterAddress());
// const testnetPaymasterBytecodeHash = ethers.hexlify(utils.hashBytecode(testnetPaymasterBytecode));

const testnetPaymasterBytecodeHash = "0x010000f16d2b10ddeb1c32f2c9d222eb1aea0f638ec94a81d4e916c627720e30";

const provider = new BrowserProvider(window.ethereum);
console.log(`Bytecode: ${await provider.getBytecodeByHash(testnetPaymasterBytecodeHash)}`);

getConfirmedTokens

Returns confirmed tokens bridged to ZKsync Era via the official bridge.

Inputs

ParameterTypeDescription
startAddressThe token id from which to start. Default 0.
limitAddressThe maximum number of tokens to list. Default 255.
async getConfirmedTokens(start = 0, limit = 255): Promise<Token[]>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const tokens = await provider.getConfirmedTokens();
console.log(`Confirmed tokens: ${utils.toJSON(tokens)}`);

getDefaultBridgeAddresses

Returns the addresses of the default ZKsync Era bridge contracts on both L1 and L2.

async getDefaultBridgeAddresses(): Promise<{
  erc20L1: string;
  erc20L2: string;
  wethL1: string;
  wethL2: string;
  sharedL1: string;
  sharedL2: string;
}>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const bridgeAddresses = await provider.getDefaultBridgeAddresses();
console.log(`Default bridges: ${utils.toJSON(bridgeAddresses)}`);

getFeeParams

Returns the current fee parameters.

async getFeeParams(): Promise<FeeParams>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const feeParams = await provider.getFeeParams();
console.log(`Fee: ${utils.toJSON(feeParams)}`);

getGasPrice

Returns an estimate of the gas price to use in a transaction.

async getGasPrice(): Promise<bigint>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Gas price: ${await provider.getGasPrice()}`);

getL1BatchBlockRange

Returns the range of blocks contained within a batch given by batch number.

Inputs

ParameterTypeDescription
l1BatchNumbernumberL1 batch number.
async getL1BatchBlockRange(l1BatchNumber: number): Promise<[number, number] | null>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const l1BatchNumber = await provider.getL1BatchNumber();
console.log(`L1 batch block range: ${utils.toJSON(await provider.getL1BatchBlockRange(l1BatchNumber))}`);

getL1BatchDetails

Returns data pertaining to a given batch.

Inputs

ParameterTypeDescription
numbernumberL1 batch number.
async getL1BatchDetails(number: number): Promise<BatchDetails>

Example

getL1BatchDetails

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const l1BatchNumber = await provider.getL1BatchNumber();
console.log(`L1 batch details: ${utils.toJSON(await provider.getL1BatchDetails(l1BatchNumber))}`);

getL1BatchNumber

Returns the latest L1 batch number.

async getL1BatchNumber(): Promise<number>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`L1 batch number: ${await provider.getL1BatchNumber()}`);

getLogProof

Returns the proof for a transaction's L2 to L1 log.

Inputs

ParameterTypeDescription
txHashBytesLikeHash of the L2 transaction the L2 to L1 log was produced within.
index?numberThe index of the L2 to L1 log in the transaction.
async getLogProof(txHash: BytesLike, index?: number): Promise<LogProof | null>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const tx = "0x2a1c6c74b184965c0cb015aae9ea134fd96215d2e4f4979cfec12563295f610e";
console.log(`Log ${utils.toJSON(await provider.getLogProof(tx, 0))}`);

getLogs

Returns the logs that match the given filter.

Inputs

ParameterTypeDescription
filterFilter or FilterByBlockHashFilter query.
async getLogs(filter: Filter | FilterByBlockHash): Promise<Log[]>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Logs: ${utils.toJSON(await provider.getLogs({ fromBlock: 0, toBlock: 5, address: utils.L2_ETH_TOKEN_ADDRESS }))}`);

getMainContractAddress

Returns the main ZKsync Era smart contract address.

async getMainContractAddress(): Promise<Address>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Main contract: ${await provider.getMainContractAddress()}`);

getProof

Returns Merkle proofs for one or more storage values at the specified account.

Inputs

ParameterTypeDescription
addressAddressThe account to fetch storage values and proofs for.
keysstring[]Vector of storage keys in the account.
l1BatchNumbernumberNumber of the L1 batch specifying the point in time at which the requested values are returned.
async getProof(address: Address, keys: string[], l1BatchNumber: number): Promise<StorageProof>

Example

import { BrowserProvider, utils } from "zksync-ethers";
import { ethers } from "ethers";

const provider = new BrowserProvider(window.ethereum);
const address = "0x082b1BB53fE43810f646dDd71AA2AB201b4C6b04";

// Fetching the storage proof for rawNonces storage slot in NonceHolder system contract.
// mapping(uint256 => uint256) internal rawNonces;

// Ensure the address is a 256-bit number by padding it
// because rawNonces slot uses uint256 for mapping addresses and their nonces.
const addressPadded = ethers.zeroPadValue(address, 32);

// Convert the slot number to a hex string and pad it to 32 bytes.
const slotPadded = ethers.zeroPadValue(ethers.toBeHex(0), 32);

// Concatenate the padded address and slot number.
const concatenated = addressPadded + slotPadded.slice(2); // slice to remove '0x' from the slotPadded

// Hash the concatenated string using Keccak-256.
const storageKey = ethers.keccak256(concatenated);

const l1BatchNumber = await provider.getL1BatchNumber();
const proof = await provider.getProof(address, [storageKey], l1BatchNumber);
console.log(`Proof: ${utils.toJSON(proof)}`);

getProtocolVersion

Returns the protocol version.

Inputs

ParameterTypeDescription
id?numberSpecific version ID (optional).
async getProtocolVersion(id?: number): Promise<ProtocolVersion>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Protocol version: ${await provider.getProtocolVersion()}`);

getRawBlockTransactions

Returns data of transactions in a block.

Inputs

ParameterTypeDescription
numbernumberBlock number.
async getRawBlockTransactions(number: number): Promise<RawBlockTransaction[]>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Raw block transactions: ${utils.toJSON(await provider.getRawBlockTransactions(90_000))}`);

getSigner

Returns a signer object for the provider.

Inputs

ParameterTypeDescription
address?AddressAccount address.
async getSigner(address?: Address): Promise<Signer>

Example

import { BrowserProvider, Wallet } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();

// Verify that signer matches the expected wallet address.
console.log(`Signer address: ${await signer.getAddress()}`);

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`L2 token address: ${await provider.l2TokenAddress("0x5C221E77624690fff6dd741493D735a17716c26B")}`);

getTestnetPaymasterAddress

Returns the testnet paymaster address if available, or null.

async getTestnetPaymasterAddress(): Promise<Address | null>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Testnet paymaster: ${await provider.getTestnetPaymasterAddress()}`);

getTransaction

Returns the transaction for the given transaction hash.

Inputs

ParameterTypeDescription
txHashstringTransaction hash.
async getTransaction(txHash: string): Promise<TransactionResponse>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);

const TX_HASH = "<YOUR_TX_HASH_ADDRESS>";
const tx = await provider.getTransaction(TX_HASH);

// Wait until the transaction is processed by the server.
await tx.wait();
// Wait until the transaction is finalized.
await tx.waitFinalize();

getTransactionDetails

Returns data from a specific transaction given by the transaction hash.

Inputs

ParameterTypeDescription
txHashBytesLikeTransaction hash.
async getTransactionDetails(txHash: BytesLike): Promise<TransactionDetails>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);

const TX_HASH = "<YOUR_TX_HASH_ADDRESS>";
console.log(`Transaction details: ${utils.toJSON(await provider.getTransactionDetails(TX_HASH))}`);

getTransactionReceipt

Returns the transaction receipt for the given transaction hash.

Inputs

ParameterTypeDescription
txHashstringTransaction hash.
async getTransactionReceipt(txHash: string): Promise<TransactionReceipt | null>

Example

import { BrowserProvider, utils } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const TX_HASH = "<YOUR_TX_HASH_ADDRESS>";
console.log(`Transaction receipt: ${utils.toJSON(await provider.getTransactionReceipt(TX_HASH))}`);

isBaseToken

Returns whether the token is the base token.

Inputs

ParameterTypeDescription
tokenAddressThe address of the token.
async isBaseToken(token: Address): Promise<boolean>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Is base token: ${await provider.isBaseToken("0x5C221E77624690fff6dd741493D735a17716c26B")}`);

isEthBasedChain

Returns whether the chain is ETH-based.

async isEthBasedChain(): Promise<boolean>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`Is ETH based chain: ${await provider.isEthBasedChain()}`);

l1ChainId

Returns the L1 chain ID.

async l1ChainId(): Promise<number>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
const l1ChainId = await provider.l1ChainId();
console.log(`All balances: ${l1ChainId}`);

l1TokenAddress

Returns the L1 token address equivalent for a given L2 token address.

Inputs

ParameterTypeDescription
tokenAddressThe address of the token on L2.
async l1TokenAddress(token: Address): Promise<string>

Example

import { BrowserProvider } from "zksync-ethers";

const provider = new BrowserProvider(window.ethereum);
console.log(`L1 token address: ${await provider.l1TokenAddress("0x3e7676937A7E96CFB7616f255b9AD9FF47363D4b")}`);

l2TokenAddress

Returns the L2 token address equivalent for a given L1 token address.

Inputs

ParameterTypeDescription
tokenAddressThe address of the token on L1.
async l2TokenAddress(token: Address): Promise<string>

Made with ❤️ by the ZKsync Community