Estimate gas


Estimate gas

Gas fees

  • Layer 2 gas fees depend on the current Ethereum L1 gas fees for publishing and verification.

Gas estimation is usually left to the SDK to deal with. However, there are situations in which a developer may wish to implement gas estimation directly; such as for displaying the fee to the user for example.

This document gives step-by-step instructions for implementing gas estimation for:

L1 to L1

To estimate gas for L1 to L1 transactions, use the Ethereum eth_estimateGas method and send to an L1 node.

More info

For more information and live testing, check out the Ethereum JSON RPC docsopen in new window.

L1 to L2

To estimate gas for an L1 to L2 transaction, first gather the required values:

  1. Get the current L1 gas price.

    For example, the Ethers.js library has a getGasPrice()open in new window method available on a Provider object. Your language of choice should have an equivalent.

  2. Call the zks_estimateGasL1ToL2 method, passing the transaction data. This returns the estimated amount of L2 gas the transaction requires; commonly called gas limit or similar in our code and docs.

    • Apply an alias to the addresses in the request if the sender address is a contract. If the sender is an EOA, no aliasing is required. This is implemented by the applyL1ToL2Aliasopen in new window Solidity function.
  3. Call the l2TransactionBaseCostopen in new window function, passing the gas price and gas limit from previous steps. This function returns the base cost required to send a transaction.

    • You also need to pass the constant representing how much gas is required to publish a byte of data from L1 to L2. At the time of writing, the JavaScript API provides this constant as REQUIRED_L1_TO_L2_GAS_PER_PUBDATA_LIMIT.

Once you have all of the above, you can send a transaction with the requestL2Transactionopen in new window function, passing the gas limit returned at step 2, along with the gas price and base cost from steps 1 and 3 as part of the value parameters.

For a more detailed explanation on estimating gas, with code examples, find out how to send a transaction from L1 to L2.

L2 to L2

Gas estimation for L2 to L2 transactions on zkSync Era works in the same way as it does in Ethereum.

Supply the same calldata as an L1 to L2 transaction, use the Ethereum eth_estimateGas method, and send the transaction to an L2 node.

More info

For more information and live testing, check out the Ethereum JSON RPC docsopen in new window.

L2 to L1

Gas estimation for L2 to L1 messages is dealt with by the corresponding L2 to L2 transactions.

Find out how to send a message from L2 to L1.