Providers


Providers

A Web3 Provider object provides application-layer access to underlying blockchain networks.

The zksync2-js library supports provider methods from the ethers.jsopen in new window library and supplies additional functionality.

Two providers are available:

Tips

Provider

Info

constructor

Returns a zkSync Era Provider object.

Inputs

ParameterTypeDescription
url?ethers.FetchRequestopen in new windowNetwork RPC URL (optional).
network?ethers.Networkishopen in new windowNetwork name (optional).
options?anyoptions (optional).
constructor(url ? : ethers.FetchRequest | string, network ? : Networkish, options ? : any)

Example

import { Provider } from "zksync2-js";

const provider = new Provider("https://testnet.era.zksync.dev");

broadcastTransaction

Override of Ethers implementation.open in new window

Inputs

ParameterTypeDescription
signedTxstringSigned transaction.
override async broadcastTransaction(signedTx: string): Promise<TransactionResponse>

Example

import { Provider, types, Wallet } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const PRIVATE_KEY = "<PRIVATE_KEY>";
const wallet = new Wallet(PRIVATE_KEY, provider, ethProvider);

const signedTx = await wallet.signTransaction({
  to: "0xa61464658AfeAf65CccaaFD3a512b69A83B77618",
  value: ethers.parseEther("0.01"),
});
const tx = await provider.broadcastTransaction(signedTx);
console.log(tx.hash);

estimateFee

Returns an estimated Fee for requested transaction.

Inputs

ParameterTypeDescription
transactionTransactionRequestopen in new windowTransaction request.
async estimateFee(transaction: TransactionRequest): Promise<Fee>

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const fee = await provider.estimateFee({
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  to: "0xa61464658AfeAf65CccaaFD3a512b69A83B77618",
  value: `0x${BigInt(7_000_000_000).toString(16)}`,
});
console.log(`Fee: ${toJSON(fee)}`);

estimateGas

Returns an estimate of the amount of gas required to submit a transaction to the network.

Inputs

ParameterTypeDescription
_txTransactionRequestopen in new windowTransaction request.
async estimateGas(_tx: TransactionRequest): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const gasTokenApprove = await provider.estimateGas({
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  to: "0xCd9BDa1d0FC539043D4C80103bdF4f9cb108931B",
  data: utils.IERC20.encodeFunctionData("approve", [RECEIVER, 1]),
});
console.log(`Gas for token approval tx: ${gasTokenApprove}`);
import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const tokenAddress = "0xCd9BDa1d0FC539043D4C80103bdF4f9cb108931B"; // Crown token which can be minted for free
const paymasterAddress = "0xd660c2F92d3d0634e5A20f26821C43F1b09298fe"; // Paymaster for Crown token

const paymasterParams = utils.getPaymasterParams(paymasterAddress, {
  type: "ApprovalBased",
  token: tokenAddress,
  minimalAllowance: 1,
  innerInput: new Uint8Array(),
});

const tokenApprove = await provider.estimateGas({
  from: PUBLIC_KEY,
  to: tokenAddress,
  data: utils.IERC20.encodeFunctionData("approve", [RECEIVER, 1]),
  customData: {
    gasPerPubdata: utils.DEFAULT_GAS_PER_PUBDATA_LIMIT,
    paymasterParams,
  },
});
console.log(`Gas for token approval using EIP-712 tx: ${tokenApprove}`);

estimateGasL1

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

Calls the zks_estimateL1ToL2 JSON-RPC method.

Inputs

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

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
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)}`);

estimateGasTransfer

Returns the gas estimation for a transfer transaction.

Calls internal method getTransferTx to get the transfer transaction and sends it to the estimateGas method.

Inputs

ParameterTypeDescription
tokenAddressToken address.
amountBigNumberishAmount of token.
from?AddressFrom address (optional).
to?AddressTo address (optional).
overrides?ethers.Overridesopen in new windowEthers overrides object (optional).
async estimateGasTransfer(transaction: {
  to: Address;
  amount: BigNumberish;
  from ? : Address;
  token ? : Address;
  overrides ? : ethers.Overrides;
}): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const gasTransfer = await provider.estimateGasTransfer({
  token: utils.ETH_ADDRESS,
  amount: 7_000_000_000,
  to: "0xa61464658AfeAf65CccaaFD3a512b69A83B77618",
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
});
console.log(`Gas for transfer tx: ${gasTransfer}`);

estimateGasWithdraw

Returns the gas estimation for a withdrawal transaction.

Calls internal method getWithdrawTx to get the withdrawal transaction and sends it to the estimateGas method.

Inputs

ParameterTypeDescription
tokenAddressToken address.
amountBigNumberishAmount of token.
from?AddressFrom address (optional).
to?AddressTo address (optional).
bridgeAddress?AddressBridge address (optional).
overrides?ethers.Overridesopen in new windowEthers call overrides object (optional).
async estimateGasWithdraw(transaction: {
  token: Address;
  amount: BigNumberish;
  from ? : Address;
  to ? : Address;
  bridgeAddress ? : Address;
  overrides ? : ethers.Overrides;
}): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const gasWithdraw = await provider.estimateGasWithdraw({
  token: utils.ETH_ADDRESS,
  amount: 7_000_000,
  to: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
});

estimateL1ToL2Execute

Returns gas estimation for an L1 to L2 execute operation.

Inputs

ParameterTypeDescription
contractAddressAddressAddress of contract.
calldataBytesLikeThe transaction call data.
caller?AddressCaller address (optional).
l2Value?BigNumberishCurrent L2 gas value (optional).
factoryDeps?BytesLike[]Byte array containing contract bytecode.
gasPerPubdataByte?BigNumberishConstant representing current amount of gas per byte (optional).
overrides?ethers.OverridesEthers overrides object (optional).
async estimateL1ToL2Execute(transaction: {
  contractAddress: Address;
  calldata: string;
  caller ? : Address;
  l2Value ? : BigNumberish;
  factoryDeps ? : ethers.BytesLike[];
  gasPerPubdataByte ? : BigNumberish;
  overrides ? : ethers.Overrides;
}): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const gasL1ToL2 = await provider.estimateL1ToL2Execute({
  contractAddress: await provider.getMainContractAddress(),
  calldata: "0x",
  caller: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  l2Value: 7_000_000_000,
});
console.log(`Gas L1 to L2: ${BigInt(gasL1ToL2)}`);

getAllAccountBalances

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

Calls the zks_getAllAccountBalances JSON-RPC method.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const balances = await provider.getAllAccountBalances("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049");
console.log(`All balances: ${toJSON(balances)}`);

getBalance

Returns the user's balance as a bigint object for an (optional) block tag and (optional) token.

When block and token are not supplied, committed and ETH are the default values.

Inputs

ParameterTypeDescription
addressAddressAccount address.
blockTag?BlockTagBlock tag for getting the balance on. Latest committed block is default (optional).
tokenAddress?Addresshe address of the token. ETH is default (optional).
async getBalance(address: Address, blockTag?: BlockTag, tokenAddress?: Address)

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const account = "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049";
const tokenAddress = "0xCd9BDa1d0FC539043D4C80103bdF4f9cb108931B"; // 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", tokenAddres)}`);

getBlock

Returns block from the network, or false if there is no block.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Block: ${toJSON(await provider.getBlock("latest", true))}`);

getBlockDetails

Returns additional zkSync-specific information about the L2 block.

Calls the zks_getBlockDetails JSON-RPC method.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Block details: ${toJSON(await provider.getBlockDetails(90_000))}`);

getConfirmedTokens

Returns [address, symbol, name, and decimal] information of all tokens within a range of ids given by parameters from and limit.

Calls the zks_getConfirmedTokens JSON-RPC method.

Tip

  • Confirmed in the function name means any token bridged to zkSync Era via the official bridge.

The tokens are returned in alphabetical order by their symbol. This means the token id is its position in an alphabetically sorted array of tokens.

Inputs

ParameterTypeDescription
startnumberThe token id from which to start returning the information about the tokens. Zero by default.
limitnumberThe number of tokens to be returned from the API. 255 by default.
async getConfirmedTokens(start: number = 0, limit: number = 255): Promise<Token[]>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Confirmed tokens: ${toJSON(await provider.getConfirmedTokens())}`);

getContractAccountInfo

Returns the version of the supported account abstraction and nonce ordering from a given contract address.

Inputs

ParameterTypeDescription
addressAddressContract address.
async getContractAccountInfo(address:Address): Promise<ContractAccountInfo>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const tokenAddress = "0xCd9BDa1d0FC539043D4C80103bdF4f9cb108931B"; // Crown token which can be minted for free
console.log(`Contract account info: ${toJSON(await provider.getContractAccountInfo(tokenAddress))}`);

getDefaultBridgeAddresses

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

async;
getDefaultBridgeAddresses();

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Default bridges: ${toJSON(await provider.getDefaultBridgeAddresses())}`);

getDefaultProvider

Static method which returns a Provider object from the RPC URL or localhost.

Inputs

ParameterTypeDescription
zksyncNetworkZkSyncNetworkType of zkSync network. Localhost by default.
static getDefaultProvider(zksyncNetwork: ZkSyncNetwork = ZkSyncNetwork.Localhost)

Example

import { Provider, types } from "zksync2-js";

const providerMainnet = Provider.getDefaultProvider(types.Network.Mainnet);
const providerTestnet = Provider.getDefaultProvider(types.Network.Goerli);
const providerLocalnet = Provider.getDefaultProvider(types.Network.Localhost);

getFilterChanges

Returns an array of logs by calling Ethereum method eth_getFilterChanges.open in new window

Inputs

ParameterTypeDescription
idxbigintFilter index.
async getFilterChanges(idx: bigint): Promise<Array<Log | string>>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const filter = await provider.newFilter({
  address: utils.L2_ETH_TOKEN_ADDRESS,
  topics: [ethers.id("Transfer(address,address,uint256)")],
});
const result = await provider.getFilterChanges(filter);

getGasPrice

Returns an estimate (best guess) of the gas price to use in a transaction.

async getGasPrice(): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Gas price: ${await provider.getGasPrice()}`);

getL1BatchBlockRange

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

Calls the zks_getL1BatchBlockRange JSON-RPC method.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const l1BatchNumber = await provider.getL1BatchNumber();
console.log(`L1 batch block range: ${toJSON(await provider.getL1BatchBlockRange(l1BatchNumber))}`);

getL1BatchDetails

Returns data pertaining to a given batch.

Calls the zks_getL1BatchDetails JSON-RPC method.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const l1BatchNumber = await provider.getL1BatchNumber();
console.log(`L1 batch details: ${toJSON(await provider.getL1BatchDetails(l1BatchNumber))}`);

getL1BatchNumber

Returns the latest L1 batch number.

Calls the zks_getL1BatchNumber JSON-RPC method.

async getL1BatchNumber(): Promise<number>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`L1 batch number: ${await provider.getL1BatchNumber()}`);

getL2TransactionFromPriorityOp

Returns a L2 transaction from L1 transaction response.

Inputs

ParameterTypeDescription
l1TxResponseTransactionResponseopen in new windowL1 transaction response.
async getL2TransactionFromPriorityOp(l1TxResponse: ethers.TransactionResponse): Promise<TransactionResponse>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const ethProvider = ethers.getDefaultProvider("goerli");
const l1Tx = "0xcca5411f3e514052f4a4ae1c2020badec6e0998adb52c09959c5f5ff15fba3a8";
const l1TxResponse = await ethProvider.getTransaction(l1Tx);
if (l1TxResponse) {
  console.log(`Tx: ${toJSON(await provider.getL2TransactionFromPriorityOp(l1TxResponse))}`);
}

getLogProof

Returns the proof for a transaction's L2 to L1 log sent via the L1Messenger system contract.

Calls the zks_getL2ToL1LogProof JSON-RPC method.

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 (optional).
async getLogProof(txHash: BytesLike, index ? : number): Promise<MessageProof | null>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const tx = "0x2a1c6c74b184965c0cb015aae9ea134fd96215d2e4f4979cfec12563295f610e";
console.log(`Log ${toJSON(await provider.getLogProof(tx, 0))}`);

getLogs

Returns an array of all logs that match a filter with a given id by calling Ethereum method eth_getLogs.open in new window

Inputs

ParameterTypeDescription
filterFilteropen in new window or FilterByBlockHashopen in new windowFilter query.
async getLogs(filter: Filter | FilterByBlockHash): Promise<Log[]>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Logs: ${toJSON(await provider.getLogs({ fromBlock: 0, toBlock: 5, address: utils.L2_ETH_TOKEN_ADDRESS }))}`);

getMainContractAddress

Returns the main zkSync Era smart contract address.

Calls the zks_getMainContract JSON-RPC method.

async getMainContractAddress(): Promise<Address>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Main contract: ${await provider.getMainContractAddress()}`);

getPriorityOpResponse

Returns a TransactionResponseopen in new window as a PriorityOpResponse object.

Inputs

ParameterTypeDescription
l1TxResponseTransactionResponseopen in new windowL1 transaction response.
async getPriorityOpResponse(l1TxResponse: ethers.TransactionResponse): Promise<PriorityOpResponse>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const ethProvider = ethers.getDefaultProvider("goerli");
const l1Tx = "0xcca5411f3e514052f4a4ae1c2020badec6e0998adb52c09959c5f5ff15fba3a8";
const l1TxResponse = await ethProvider.getTransaction(l1Tx);
if (l1TxResponse) {
  console.log(`Tx: ${toJSON(await provider.getPriorityOpResponse(l1TxResponse))}`);
}

getTestnetPaymasterAddress

Returns the testnet paymaster address if available, or null.

async getTestnetPaymasterAddress(): Promise<Address | null>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`Testnet paymaster: ${await provider.getTestnetPaymasterAddress()}`);

getTransaction

Returns a specified L2 transaction response object by overriding the Ethers implementationopen in new window.

Inputs

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

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);

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

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

getTransactionDetails

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

Calls the getTransactionDetails JSON-RPC method.

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);

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

getTransactionReceipt

Returns the transaction receipt from a given hash number.

Ethers implementation.open in new window

Inputs

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

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
const TX_HASH = "<YOUR_TX_HASH_ADDRESS>";
console.log(`Transaction receipt: ${toJSON(await provider.getTransactionReceipt(TX_HASH))}`);

getTransactionStatus

Returns the status of a specified transaction.

Inputs

ParameterTypeDescription
txHashstringTransaction hash.
async getTransactionStatus(txHash: string): Promise<TransactionStatus>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);

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

getTransferTx

Returns the populated transfer transaction.

Inputs

ParameterTypeDescription
tokenAddressToken address.
amountBigNumberishAmount of token.
from?AddressFrom address (optional).
to?AddressTo address (optional).
overrides?ethers.Overridesopen in new windowEthers overrides object (optional).
async getTransferTx(transaction: {
  to: Address;
  amount: BigNumberish;
  from ? : Address;
  token ? : Address;
  overrides ? : ethers.Overrides;
}): Promise<EthersTransactionRequest>

Example

const tx = await provider.getTransferTx({
  token: utils.ETH_ADDRESS,
  amount: 7_000_000_000,
  to: "0xa61464658AfeAf65CccaaFD3a512b69A83B77618",
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
});
console.log(`Gas for transfer tx: ${tx}`);

getWithdrawTx

Returns the populated withdrawal transaction.

Inputs

ParameterTypeDescription
tokenAddressToken address.
amountBigNumberishAmount of token.
from?AddressFrom address (optional).
to?AddressTo address (optional).
bridgeAddress?AddressBridge address (optional).
overrides?ethers.Overridesopen in new windowEthers overrides object (optional).
async getWithdrawTx(transaction: {
  token: Address;
  amount: BigNumberish;
  from ? : Address;
  to ? : Address;
  bridgeAddress ? : Address;
  overrides ? : ethers.Overrides;
}): Promise<EthersTransactionRequest>

Example

const tx = await provider.getWithdrawTx({
  token: utils.ETH_ADDRESS,
  amount: 7_000_000_000,
  to: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
  from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
});
console.log(`Gas for transfer tx: ${tx}`);

l1ChainId

Returns the chain id of the underlying L1.

Calls the zks_L1ChainId JSON-RPC method.

async l1ChainId(): Promise<number>

Example

Helper function: toJSON.

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`L1 chain ID: ${await provider.l1ChainId()}`);

l1TokenAddress

Returns the L1 token address equivalent for a L2 token address as they are not equal. ETH's address is set to zero address.

Note

Only works for tokens bridged on default zkSync Era bridges.

Inputs

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

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`L1 token address: ${await provider.l1TokenAddress("0x3e7676937A7E96CFB7616f255b9AD9FF47363D4b")}`);

l2TokenAddress

Returns the L2 token address equivalent for a L1 token address as they are not equal. ETH's address is set to zero address.

Note

Only works for tokens bridged on default zkSync Era bridges.

Inputs

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

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`L2 token address: ${await provider.l2TokenAddress("0x5C221E77624690fff6dd741493D735a17716c26B")}`);

newBlockFilter

Returns a new block filter by calling Ethereum method eth_newBlockFilter.open in new window

async newBlockFilter(): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`New block filter: ${await provider.newBlockFilter()}`);

newFilter

Returns a new filter by calling Ethereum method eth_newFilteropen in new window and passing a filter object.

Inputs

ParameterTypeDescription
filterFilterByBlockHashopen in new window or Filteropen in new windowFilter query.
async newFilter(filter: FilterByBlockHash | Filter): Promise<bigint>

Example

import { Provider, types, utils } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(
  `New filter: ${await provider.newFilter({
    fromBlock: 0,
    toBlock: 5,
    address: utils.L2_ETH_TOKEN_ADDRESS,
  })}`
);

newPendingTransactionFilter

Returns a new pending transaction filter by calling Ethereum method eth_newPendingTransactionFilteropen in new window and passing a filter object.

async newPendingTransactionsFilter(): Promise<bigint>

Example

import { Provider, types } from "zksync2-js";

const provider = Provider.getDefaultProvider(types.Network.Goerli);
console.log(`New pending transaction filter: ${await provider.newPendingTransactionsFilter()}`);

BrowserProvider

Use this provider for Web3 browser wallet integrations for easy compatibility with Metamask, WalletConnect, and other popular 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
ethereumEip1193Provideropen in new windowThe Eip1193Provider class instance. For instance, Metamask is window.ethereum.
network?Networkishopen in new windowNetwork name (optional).
constructor(ethereum: Eip1193Provider, network?: Networkish)

Example

import { BrowserProvider } from "zksync2-js";

const provider = new BrowserProvider(window.ethereum);

estimateGas

Returns gas estimate by overriding the zkSync Era estimateGas method.

Inputs

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

Example

import { BrowserProvider } from "zksync2-js";

const provider = new BrowserProvider(window.ethereum);
const gas = await provider.estimateGas({
  to: RECEIVER,
  amount: ethers.parseEther("0.01"),
});
console.log(`Gas: ${gas}`);

getSigner

Override of Ethers implementationopen in new window.

override async getSigner(address ? : number | string): Promise<Signer>

Example

import { BrowserProvider } from "zksync2-js";

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

send

Returns a provider request object by overriding the Ethers implementationopen in new window.

Inputs

ParameterTypeDescription
methodAddressRequest method name as string.
params?Array<any>Parameters of any type (optional).
override async send(method: string, params?: Array<any>): Promise <any>

Appendix

toJSON

function toJSON(object: any): string {
  return JSON.stringify(object, (key, value) => {
    if (typeof value === "bigint") {
      return value.toString(); // Convert BigInt to string
    }
    return value;
  });
}