Web3Provider
The Web3Provider
is an extension of the Provider
class specifically designed for use in browser environments and
integration with browser wallets (e.g., MetaMask, WalletConnect). It supports RPC endpoints within the zks
namespace.
constructor
Initializes a new instance of the Web3Provider
class.
Inputs
Parameter | Type | Description |
---|---|---|
provider | ExternalProvider | The provider injected from the browser (e.g., MetaMask's window.ethereum ). |
network? | ethers.providers.Networkish | Optional. The network name, chain ID, or object with network details. |
constructor(provider: ExternalProvider, network?: ethers.providers.Networkish)
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
estimateFee
Returns an estimated fee for the requested transaction.
Inputs
Parameter | Type | Description |
---|---|---|
transaction | TransactionRequest | The transaction request. |
override async estimateFee(transaction: TransactionRequest): Promise<Fee>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
const fee = await provider.estimateFee({
from: "0x36615Cf349d7F6344891B1e7CA7C72883F5dc049",
to: "0xa61464658AfeAf65CccaaFD3
a512b69A83B77618",
value: BigNumber.from(7_000_000_000).toHexString(),
});
console.log(`Fee: ${utils.toJSON(fee)}`);
estimateGasL1
Estimates the amount of gas required to submit a transaction from L1 to L2.
Inputs
Parameter | Type | Description |
---|---|---|
transaction | TransactionRequest | The transaction request. |
override async estimateGasL1(transaction: TransactionRequest): Promise<BigNumber>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(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: ${gasL1}`);
getAllAccountBalances
Returns all balances for confirmed tokens given by an account address.
Inputs
Parameter | Type | Description |
---|---|---|
address | Address | The account address. |
override async getAllAccountBalances(address: Address): Promise<BalancesMap>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
const balances = await provider.getAllAccountBalances("0x36615Cf349d7F6344891B1e7CA7C72883F5dc049");
console.log(`All balances: ${utils.toJSON(balances)}`);
getBalance
Returns the account balance for the specified address
, blockTag
, and tokenAddress
.
Inputs
Parameter | Type | Description |
---|---|---|
address | Address | The account address. |
blockTag? | BlockTag | Optional. The block tag for balance query. |
tokenAddress? | Address | Optional. The token address. |
override async getBalance(address: Address, blockTag?: BlockTag, tokenAddress?: Address): Promise<BigNumber>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(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.
override async getBaseTokenContractAddress(): Promise<Address>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Base token: ${await provider.getBaseTokenContractAddress()}`);
getBlock
Returns the block for the specified blockHashOrBlockTag
.
Inputs
Parameter | Type | Description |
---|---|---|
blockHashOrBlockTag | BlockTag or string | The block hash or tag. |
override async getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<Block>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Block: ${utils.toJSON(await provider.getBlock("latest", true))}`);
getBlockDetails
Returns additional ZKsync-specific information about the L2 block.
Inputs
Parameter | Type | Description |
---|---|---|
number | number | The block number. |
override async getBlockDetails(number: number): Promise<BlockDetails>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3
Provider(window.ethereum);
console.log(`Block details: ${utils.toJSON(await provider.getBlockDetails(90_000))}`);
getBlockWithTransactions
Returns the block for the specified blockHashOrBlockTag
, including all transactions.
Inputs
Parameter | Type | Description |
---|---|---|
blockHashOrBlockTag | BlockTag or string | The block hash or tag. |
override async getBlockWithTransactions(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<BlockWithTransactions>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Block: ${utils.toJSON(await provider.getBlockWithTransactions("latest", true))}`);
getBridgehubContractAddress
Returns the Bridgehub smart contract address.
override async getBridgehubContractAddress(): Promise<Address>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Bridgehub: ${await provider.getBridgehubContractAddress()}`);
getBytecodeByHash
Returns bytecode of a contract given by its hash.
Inputs
Parameter | Type | Description |
---|---|---|
bytecodeHash | BytesLike | The bytecode hash. |
override async getBytecodeByHash(bytecodeHash: BytesLike): Promise<Uint8Array>
Example
import { Web3Provider } from "zksync-ethers";
// Bytecode hash can be computed by following these steps:
// const testnetPaymasterBytecode = await provider.getCode(await provider.getTestnetPaymasterAddress());
// const testnetPaymasterBytecodeHash = ethers.utils.hexlify(utils.hashBytecode(testnetPaymasterBytecode));
const testnetPaymasterBytecodeHash = "0x010000f16d2b10ddeb1c32f2c9d222eb1aea0f638ec94a81d4e916c627720e30";
const provider = new Web3Provider(window.ethereum);
console.log(`Bytecode: ${await provider.getBytecodeByHash(testnetPaymasterBytecodeHash)}`);
getConfirmedTokens
Returns confirmed tokens. Confirmed token is any token bridged to ZKsync Era via the official bridge.
Inputs
Parameter | Type | Description |
---|---|---|
start? | number | The token ID from which to start. Default is 0. |
limit? | number | The maximum number of tokens to list. Default is 255. |
override async getConfirmedTokens(start?: number, limit?: number): Promise<Token[]>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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.
override async getDefaultBridgeAddresses(): Promise<{ erc20L1: string; erc20L2: string; wethL1: string; wethL2: string; sharedL1: string; sharedL2: string; }>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Bridge addresses: ${await provider.getDefaultBridgeAddresses()}`);
getFeeParams
Returns the current fee parameters.
override async getFeeParams(): Promise<FeeParams>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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.
override async getGasPrice(): Promise<BigNumber>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Gas price: ${await provider.getGasPrice()}`);
getL1BatchBlockRange
Returns the range of blocks contained within a batch given by batch number.
Inputs
Parameter | Type | Description |
---|---|---|
l1BatchNumber | number | The L1 batch number. |
override async getL1BatchBlockRange(l1BatchNumber: number): Promise<[number, number] | null>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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
Parameter | Type | Description |
---|---|---|
number | number | The L1 batch number. |
override async getL1BatchDetails(number: number): Promise<BatchDetails>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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.
override async getL1BatchNumber(): Promise<number>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`L1 batch number: ${await provider.getL1BatchNumber()}`);
getLogProof
Returns the proof for a transaction's L2 to L1 log sent via the L1Messenger
system contract.
Inputs
Parameter | Type | Description |
---|---|---|
txHash | BytesLike | Hash of the L2 transaction. |
index? | number | Optional. Index of the L2 to L1 log in the transaction. |
override async getLogProof(txHash: BytesLike, index?: number): Promise<LogProof | null>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
// Any L2 -> L1 transaction can be used.
// In this case, withdrawal transaction is used.
const tx = "0x2a1c6c74b184965c0cb015aae9ea134fd96215d2e4f4979cfec12563295f610e";
console.log(`Log ${utils.toJSON(await provider.getLogProof(tx, 0))}`);
getLogs
Returns the list of logs that match the specified filter
.
Inputs
Parameter | Type | Description |
---|---|---|
filter | EventFilter or Promise<EventFilter> | The filter object. |
override async getLogs(filter: EventFilter | Promise<EventFilter> = {}): Promise<Array<Log>>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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.
override async getMainContractAddress(): Promise<Address>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Main contract: ${await provider.getMainContractAddress()}`);
getProof
Returns Merkle proofs for one or more storage values at the specified account along with a Merkle proof of their authenticity.
Inputs
Parameter | Type | Description |
---|---|---|
address | Address | The account to fetch storage values and proofs for. |
keys | string[] | Vector of storage keys in the account. |
l1BatchNumber | number | The L1 batch number. |
override async getProof(address: Address, keys: string[], l1BatchNumber: number): Promise<StorageProof>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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.utils.hexZeroPad(address, 32);
// Convert the slot number to a hex string and pad it to 32 bytes.
const slotPadded = ethers.utils.hexZeroPad(ethers.utils.hexlify(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.utils.keccak256(concatenated);
const l1BatchNumber = await provider.getL1BatchNumber();
const storageProof = await provider.getProof(utils.NONCE_HOLDER_ADDRESS, [storageKey], l1BatchNumber);
console.log(`Storage proof: ${utils.toJSON(storageProof)}`);
getProtocolVersion
Returns the protocol version.
Inputs
Parameter | Type | Description |
---|---|---|
id? | number | Optional. Specific version ID. |
override async getProtocolVersion(id?: number): Promise<ProtocolVersion>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Protocol version: ${await provider.getProtocolVersion()}`);
getRawBlockTransactions
Returns data of transactions in a block.
Inputs
Parameter | Type | Description |
---|---|---|
number | number | The block number. |
override async getRawBlockTransactions(number: number): Promise<RawBlockTransaction[]>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Raw block transactions: ${utils.toJSON(await provider.getRawBlockTransactions(90_000))}`);
getSigner
Returns a JsonRpcSigner
instance for the specified addressOrIndex
. This is used to sign transactions and
messages using the connected wallet.
Inputs
Parameter | Type | Description |
---|---|---|
addressOrIndex? | string or number | Optional. The address or index. |
getSigner(addressOrIndex?: string | number): JsonRpcSigner
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
const signer = provider.getSigner();
const message = "Hello, ZKsync!";
const signature = await signer.signMessage(message);
console.log(`Signature: ${signature}`);
getTestnetPaymasterAddress
Returns the testnet paymaster address, if available.
override async getTestnetPaymasterAddress(): Promise<Address | null>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Testnet paymaster: ${await provider.getTestnetPaymasterAddress()}`);
getTransaction
Returns the transaction for the specified txHash
.
Inputs
Parameter | Type | Description |
---|---|---|
txHash | string | The transaction hash. |
override async getTransaction(txHash: string): Promise<TransactionResponse>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(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
Parameter | Type | Description |
---|---|---|
txHash | BytesLike | The transaction hash. |
override async getTransactionDetails(txHash: BytesLike): Promise<TransactionDetails>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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 specified txHash
, if mined.
Inputs
Parameter | Type | Description |
---|---|---|
txHash | string | The transaction hash. |
override async getTransactionReceipt(txHash: string): Promise<TransactionReceipt>
Example
import { Web3Provider, utils } from "zksync-ethers";
const provider = new Web3Provider(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
Parameter | Type | Description |
---|---|---|
token | Address | The address of the token. |
override async isBaseToken(token: Address): Promise<boolean>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Is base token: ${await provider.isBaseToken("0x5C221E77624690fff6dd741493D735a17716c26B")}`);
isEthBasedChain
Returns whether the chain is ETH-based.
override async isEthBasedChain(): Promise<boolean>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`Is ETH based chain: ${await provider.isEthBasedChain()}`);
l1ChainId
Returns the L1 chain ID.
override async l1ChainId(): Promise<number>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`L1 chain ID: ${await provider.l1ChainId()}`);
l1TokenAddress
Returns the L1 token address equivalent for an L2 token address.
Inputs
Parameter | Type | Description |
---|---|---|
token | Address | The address of the L2 token. |
override async l1TokenAddress(token: Address): Promise<string>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`L1 token address: ${await provider.l1TokenAddress("0x3e7676937A7E96CFB7616f255b9AD9FF47363D4b")}`);
l2TokenAddress
Returns the L2 token address equivalent for an L1 token address.
Inputs
Parameter | Type | Description |
---|---|---|
token | Address | The address of the L1 token. |
override async l2TokenAddress(token: Address): Promise<string>
Example
import { Web3Provider } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
console.log(`L2 token address: ${await provider.l2TokenAddress("0x5C221E77624690fff6dd741493D735a17716c26B")}`);
sendRawTransactionWithDetailedOutput
Executes a transaction and returns its hash, storage logs, and events that would have been generated if the transaction had already been included in the block.
Inputs
Parameter | Type | Description |
---|---|---|
signedTx | string | The signed transaction that needs to be broadcasted. |
override async sendRawTransactionWithDetailedOutput(signedTx: string): Promise<TransactionWithDetailedOutput>
Example
import { Web3Provider, Wallet, Provider, utils, types } from "zksync-ethers";
const provider = new Web3Provider(window.ethereum);
const signer = Signer.from(
await provider.getSigner(),
Number((await provider.getNetwork()).chainId),
Provider.getDefaultProvider(types.Network.Sepolia)
);
const txWithOutputs = await provider.sendRawTransactionWithDetailedOutput(
await signer.signTransaction({
to: "0x0330808583C22F812DD9B647Ed9F0411f44A1e6f",
value: 7_000_000_000,
customData: {
gasPerPubdata: 800,
},
})
);
console.log(`Transaction: ${utils.toJSON(txWithOutputs)}`);