ZKsync ZKsync Contracts

Canonical L1 & L2 contract interfaces for the ZKsync Elastic Network

NPM License: MIT Docs X: @zksyncdevs

Snapshot notice
These contracts target protocol version 27, commit 9076929.


📦 Installation

To install with Foundry-ZKsync:

forge install matter-labs/zksync-contracts

Add the following to the remappings.txt file of your project:

@matterlabs/zksync-contracts/=lib/v2-testnet-contracts/

To install with Hardhat:

bun install @matterlabs/zksync-contracts

🚀 Quick start

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IPaymaster} from
    "@matterlabs/zksync-contracts/contracts/system-contracts/interfaces/IPaymaster.sol";

contract MyPaymaster is IPaymaster {
    // Your implementation here
}

See more examples in the official docs.

📖 Documentation

🤝 Contributing

Bug fixes, new snapshots, and added ABIs are welcome! Open an issue before large changes and follow the standard PR workflow.

📜 License

Dual-licensed under MIT / Apache-2.0. See LICENSE-MIT and LICENSE-APACHE.

WebsiteGitHubXX for DevsDiscordMirror

Installation

To install with Foundry-ZKsync:

forge install matter-labs/zksync-contracts

Add the following to the remappings.txt file of your project:

@matterlabs/zksync-contracts/=lib/v2-testnet-contracts/

To install with Hardhat:

bun install @matterlabs/zksync-contracts

Getting Started

  1. Add the package

    # Hardhat / npm / bun
    npm add @matterlabs/zksync-contracts
    # or Foundry
    forge install matter-labs/zksync-contracts
    
  2. Implement a contract

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.20;
    
    import {IPaymaster} from
        "@matterlabs/zksync-contracts/contracts/system-contracts/interfaces/IPaymaster.sol";
    
    contract MyPaymaster is IPaymaster {
        // implement paymaster logic here
    }
    
  3. Build & test

    • Hardhat npx hardhat compile
    • Foundry forge build

Contents

Contents

Contents

IAssetRouterBase

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

BRIDGE_HUB

function BRIDGE_HUB() external view returns (IBridgehub);

setAssetHandlerAddressThisChain

Sets the asset handler address for a specified asset ID on the chain of the asset deployment tracker.

The caller of this function is encoded within the assetId, therefore, it should be invoked by the asset deployment tracker contract.

No access control on the caller, as msg.sender is encoded in the assetId.

Typically, for most tokens, ADT is the native token vault. However, custom tokens may have their own specific asset deployment trackers.

setAssetHandlerAddressOnCounterpart should be called on L1 to set asset handlers on L2 chains for a specific asset ID.

function setAssetHandlerAddressThisChain(
  bytes32 _assetRegistrationData,
  address _assetHandlerAddress
) external;

Parameters

NameTypeDescription
_assetRegistrationDatabytes32The asset data which may include the asset address and any additional required data or encodings.
_assetHandlerAddressaddressThe address of the asset handler to be set for the provided asset.

assetHandlerAddress

function assetHandlerAddress(bytes32 _assetId) external view returns (address);

finalizeDeposit

Finalize the withdrawal and release funds.

We have both the legacy finalizeWithdrawal and the new finalizeDeposit functions, finalizeDeposit uses the new format. On the L2 we have finalizeDeposit with new and old formats both.

function finalizeDeposit(
  uint256 _chainId,
  bytes32 _assetId,
  bytes memory _transferData
) external payable;

Parameters

NameTypeDescription
_chainIduint256The chain ID of the transaction to check.
_assetIdbytes32The bridged asset ID.
_transferDatabytesThe position in the L2 logs Merkle tree of the l2Log that was sent with the message.

Events

BridgehubDepositBaseTokenInitiated

event BridgehubDepositBaseTokenInitiated(
  uint256 indexed chainId, address indexed from, bytes32 assetId, uint256 amount
);

BridgehubDepositInitiated

event BridgehubDepositInitiated(
  uint256 indexed chainId,
  bytes32 indexed txDataHash,
  address indexed from,
  bytes32 assetId,
  bytes bridgeMintCalldata
);

BridgehubWithdrawalInitiated

event BridgehubWithdrawalInitiated(
  uint256 chainId,
  address indexed sender,
  bytes32 indexed assetId,
  bytes32 assetDataHash
);

AssetDeploymentTrackerRegistered

event AssetDeploymentTrackerRegistered(
  bytes32 indexed assetId,
  bytes32 indexed additionalData,
  address assetDeploymentTracker
);

AssetHandlerRegistered

event AssetHandlerRegistered(
  bytes32 indexed assetId, address indexed _assetHandlerAddress
);

DepositFinalizedAssetRouter

event DepositFinalizedAssetRouter(
  uint256 indexed chainId, bytes32 indexed assetId, bytes assetData
);

Constants

Git Source

LEGACY_ENCODING_VERSION

The encoding version used for legacy txs.

bytes1 constant LEGACY_ENCODING_VERSION = 0x00;

NEW_ENCODING_VERSION

The encoding version used for new txs.

bytes1 constant NEW_ENCODING_VERSION = 0x01;

SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION

The encoding version used for txs that set the asset handler on the counterpart contract.

bytes1 constant SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION = 0x02;

IL1AssetRouter

Git Source

Inherits: IAssetRouterBase, IL1SharedBridgeLegacy

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

depositLegacyErc20Bridge

Initiates a deposit by locking funds on the contract and sending the request of processing an L2 transaction where tokens would be minted.

If the token is bridged for the first time, the L2 token contract will be deployed. Note however, that the newly-deployed token does not support any custom logic, i.e. rebase tokens' functionality is not supported.

*If the L2 deposit finalization transaction fails, the _refundRecipient will receive the _l2Value. Please note, the contract may change the refund recipient's address to eliminate sending funds to addresses out of control.

  • If _refundRecipient is a contract on L1, the refund will be sent to the aliased _refundRecipient.
  • If _refundRecipient is set to address(0) and the sender has NO deployed bytecode on L1, the refund will be sent to the msg.sender address.
  • If _refundRecipient is set to address(0) and the sender has deployed bytecode on L1, the refund will be sent to the aliased msg.sender address.*

The address aliasing of L1 contracts as refund recipient on L2 is necessary to guarantee that the funds are controllable through the Mailbox, since the Mailbox applies address aliasing to the from address for the L2 tx if the L1 msg.sender is a contract. Without address aliasing for L1 contracts as refund recipients they would not be able to make proper L2 tx requests through the Mailbox to use or withdraw the funds from L2, and the funds would be lost.

function depositLegacyErc20Bridge(
  address _originalCaller,
  address _l2Receiver,
  address _l1Token,
  uint256 _amount,
  uint256 _l2TxGasLimit,
  uint256 _l2TxGasPerPubdataByte,
  address _refundRecipient
) external payable returns (bytes32 txHash);

Parameters

NameTypeDescription
_originalCalleraddressThe msg.sender address from the external call that initiated current one.
_l2ReceiveraddressThe account address that should receive funds on L2.
_l1TokenaddressThe L1 token address which is deposited.
_amountuint256The total amount of tokens to be bridged.
_l2TxGasLimituint256The L2 gas limit to be used in the corresponding L2 transaction.
_l2TxGasPerPubdataByteuint256The gasPerPubdataByteLimit to be used in the corresponding L2 transaction.
_refundRecipientaddressThe address on L2 that will receive the refund for the transaction.

Returns

NameTypeDescription
txHashbytes32The L2 transaction hash of deposit finalization.

L1_NULLIFIER

function L1_NULLIFIER() external view returns (IL1Nullifier);

L1_WETH_TOKEN

function L1_WETH_TOKEN() external view returns (address);

nativeTokenVault

function nativeTokenVault() external view returns (INativeTokenVault);

setAssetDeploymentTracker

function setAssetDeploymentTracker(
  bytes32 _assetRegistrationData,
  address _assetDeploymentTracker
) external;

setNativeTokenVault

function setNativeTokenVault(INativeTokenVault _nativeTokenVault) external;

setL1Erc20Bridge

function setL1Erc20Bridge(IL1ERC20Bridge _legacyBridge) external;

bridgeRecoverFailedTransfer

Withdraw funds from the initiated deposit, that failed when finalizing on L2.

Processes claims of failed deposit, whether they originated from the legacy bridge or the current system.

function bridgeRecoverFailedTransfer(
  uint256 _chainId,
  address _depositSender,
  bytes32 _assetId,
  bytes calldata _assetData
) external;

Parameters

NameTypeDescription
_chainIduint256The ZK chain id to which the deposit was initiated.
_depositSenderaddressThe address of the entity that initiated the deposit.
_assetIdbytes32The unique identifier of the deposited L1 token.
_assetDatabytesThe encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information.

bridgeRecoverFailedTransfer

Withdraw funds from the initiated deposit, that failed when finalizing on L2.

Processes claims of failed deposit, whether they originated from the legacy bridge or the current system.

function bridgeRecoverFailedTransfer(
  uint256 _chainId,
  address _depositSender,
  bytes32 _assetId,
  bytes memory _assetData,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof
) external;

Parameters

NameTypeDescription
_chainIduint256The ZK chain id to which deposit was initiated.
_depositSenderaddressThe address of the entity that initiated the deposit.
_assetIdbytes32The unique identifier of the deposited L1 token.
_assetDatabytesThe encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information.
_l2TxHashbytes32The L2 transaction hash of the failed deposit finalization.
_l2BatchNumberuint256The L2 batch number where the deposit finalization was processed.
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
_l2TxNumberInBatchuint16The L2 transaction number in a batch, in which the log was sent.
_merkleProofbytes32[]The Merkle proof of the processing L1 -> L2 transaction with deposit finalization.

transferFundsToNTV

Transfers funds to Native Token Vault, if the asset is registered with it. Does nothing for ETH or non-registered tokens.

assetId is not the padded address, but the correct encoded id (NTV stores respective format for IDs)

function transferFundsToNTV(
  bytes32 _assetId,
  uint256 _amount,
  address _originalCaller
) external returns (bool);

Parameters

NameTypeDescription
_assetIdbytes32
_amountuint256The asset amount to be transferred to native token vault.
_originalCalleraddressThe msg.sender address from the external call that initiated current one.

finalizeWithdrawal

Finalize the withdrawal and release funds

function finalizeWithdrawal(
  uint256 _chainId,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes calldata _message,
  bytes32[] calldata _merkleProof
) external;

Parameters

NameTypeDescription
_chainIduint256The chain ID of the transaction to check
_l2BatchNumberuint256The L2 batch number where the withdrawal was processed
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message
_l2TxNumberInBatchuint16The L2 transaction number in the batch, in which the log was sent
_messagebytesThe L2 withdraw data, stored in an L2 -> L1 message
_merkleProofbytes32[]The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization

bridgehubDeposit

Initiates a transfer transaction within Bridgehub, used by requestL2TransactionTwoBridges.

Data has the following abi encoding for legacy deposits: address _l1Token, uint256 _amount, address _l2Receiver for new deposits: bytes32 _assetId, bytes _transferData

function bridgehubDeposit(
  uint256 _chainId,
  address _originalCaller,
  uint256 _value,
  bytes calldata _data
) external payable returns (L2TransactionRequestTwoBridgesInner memory request);

Parameters

NameTypeDescription
_chainIduint256The chain ID of the ZK chain to which deposit.
_originalCalleraddressThe msg.sender address from the external call that initiated current one.
_valueuint256The msg.value on the target chain tx.
_databytesThe calldata for the second bridge deposit.

Returns

NameTypeDescription
requestL2TransactionRequestTwoBridgesInnerThe data used by the bridgehub to create L2 transaction request to specific ZK chain.

getDepositCalldata

Generates a calldata for calling the deposit finalization on the L2 native token contract.

function getDepositCalldata(
  address _sender,
  bytes32 _assetId,
  bytes memory _assetData
) external view returns (bytes memory);

Parameters

NameTypeDescription
_senderaddressThe address of the deposit initiator.
_assetIdbytes32The deposited asset ID.
_assetDatabytesThe encoded data, which is used by the asset handler to determine L2 recipient and amount. Might include extra information.

Returns

NameTypeDescription
<none>bytesReturns calldata used on ZK chain.

bridgehubDepositBaseToken

Allows bridgehub to acquire mintValue for L1->L2 transactions.

If the corresponding L2 transaction fails, refunds are issued to a refund recipient on L2.

function bridgehubDepositBaseToken(
  uint256 _chainId,
  bytes32 _assetId,
  address _originalCaller,
  uint256 _amount
) external payable;

Parameters

NameTypeDescription
_chainIduint256The chain ID of the ZK chain to which deposit.
_assetIdbytes32The deposited asset ID.
_originalCalleraddressThe msg.sender address from the external call that initiated current one.
_amountuint256The total amount of tokens to be bridged.

bridgehubConfirmL2Transaction

Routes the confirmation to nullifier for backward compatibility.

Confirms the acceptance of a transaction by the Mailbox, as part of the L2 transaction process within Bridgehub. This function is utilized by requestL2TransactionTwoBridges to validate the execution of a transaction.

function bridgehubConfirmL2Transaction(
  uint256 _chainId,
  bytes32 _txDataHash,
  bytes32 _txHash
) external;

Parameters

NameTypeDescription
_chainIduint256The chain ID of the ZK chain to which confirm the deposit.
_txDataHashbytes32The keccak256 hash of 0x01
_txHashbytes32The hash of the L1->L2 transaction to confirm the deposit.

isWithdrawalFinalized

function isWithdrawalFinalized(
  uint256 _chainId,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex
) external view returns (bool);

Events

BridgehubMintData

event BridgehubMintData(bytes bridgeMintData);

BridgehubDepositFinalized

event BridgehubDepositFinalized(
  uint256 indexed chainId,
  bytes32 indexed txDataHash,
  bytes32 indexed l2DepositTxHash
);

ClaimedFailedDepositAssetRouter

event ClaimedFailedDepositAssetRouter(
  uint256 indexed chainId, bytes32 indexed assetId, bytes assetData
);

AssetDeploymentTrackerSet

event AssetDeploymentTrackerSet(
  bytes32 indexed assetId,
  address indexed assetDeploymentTracker,
  bytes32 indexed additionalData
);

LegacyDepositInitiated

event LegacyDepositInitiated(
  uint256 indexed chainId,
  bytes32 indexed l2DepositTxHash,
  address indexed from,
  address to,
  address l1Token,
  uint256 amount
);

IL2AssetRouter

Git Source

Inherits: IAssetRouterBase

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

withdraw

function withdraw(bytes32 _assetId, bytes calldata _transferData)
  external
  returns (bytes32);

L1_ASSET_ROUTER

function L1_ASSET_ROUTER() external view returns (address);

withdrawLegacyBridge

function withdrawLegacyBridge(
  address _l1Receiver,
  address _l2Token,
  uint256 _amount,
  address _sender
) external;

finalizeDepositLegacyBridge

function finalizeDepositLegacyBridge(
  address _l1Sender,
  address _l2Receiver,
  address _l1Token,
  uint256 _amount,
  bytes calldata _data
) external;

setAssetHandlerAddress

Used to set the assetHandlerAddress for a given assetId.

Will be used by ZK Gateway

function setAssetHandlerAddress(
  uint256 _originChainId,
  bytes32 _assetId,
  address _assetHandlerAddress
) external;

setLegacyTokenAssetHandler

Function that allows native token vault to register itself as the asset handler for a legacy asset.

function setLegacyTokenAssetHandler(bytes32 _assetId) external;

Parameters

NameTypeDescription
_assetIdbytes32The assetId of the legacy token.

Events

WithdrawalInitiatedAssetRouter

event WithdrawalInitiatedAssetRouter(
  uint256 chainId,
  address indexed l2Sender,
  bytes32 indexed assetId,
  bytes assetData
);

Contents

IAssetHandler

Git Source

Author: Matter Labs

Used for any asset handler and called by the AssetRouter

Note: security-contact: security@matterlabs.dev

Functions

bridgeMint

Note, that while payable, this function will only receive base token on L2 chains, while L1 the provided msg.value is always 0. However, this may change in the future, so if your AssetHandler implementation relies on it, it is better to explicitly check it.

function bridgeMint(uint256 _chainId, bytes32 _assetId, bytes calldata _data)
  external
  payable;

Parameters

NameTypeDescription
_chainIduint256the chainId that the message is from
_assetIdbytes32the assetId of the asset being bridged
_databytesthe actual data specified for the function

bridgeBurn

Burns bridged tokens and returns the calldata for L2 <-> L1 message.

In case of native token vault _data is the tuple of _depositAmount and _l2Receiver.

function bridgeBurn(
  uint256 _chainId,
  uint256 _msgValue,
  bytes32 _assetId,
  address _originalCaller,
  bytes calldata _data
) external payable returns (bytes memory _bridgeMintData);

Parameters

NameTypeDescription
_chainIduint256the chainId that the message will be sent to
_msgValueuint256the msg.value of the L2 transaction. For now it is always 0.
_assetIdbytes32the assetId of the asset being bridged
_originalCalleraddressthe original caller of the
_databytesthe actual data specified for the function

Returns

NameTypeDescription
_bridgeMintDatabytesThe calldata used by counterpart asset handler to unlock tokens for recipient.

Events

BridgeMint

Emitted when a token is minted

event BridgeMint(
  uint256 indexed chainId,
  bytes32 indexed assetId,
  address receiver,
  uint256 amount
);

BridgeBurn

Emitted when a token is burned

event BridgeBurn(
  uint256 indexed chainId,
  bytes32 indexed assetId,
  address indexed sender,
  address receiver,
  uint256 amount
);

IBridgedStandardToken

Git Source

Functions

bridgeMint

function bridgeMint(address _account, uint256 _amount) external;

bridgeBurn

function bridgeBurn(address _account, uint256 _amount) external;

l1Address

function l1Address() external view returns (address);

originToken

function originToken() external view returns (address);

l2Bridge

function l2Bridge() external view returns (address);

assetId

function assetId() external view returns (bytes32);

nativeTokenVault

function nativeTokenVault() external view returns (address);

Events

BridgeInitialize

event BridgeInitialize(
  address indexed l1Token, string name, string symbol, uint8 decimals
);

BridgeMint

event BridgeMint(address indexed account, uint256 amount);

BridgeBurn

event BridgeBurn(address indexed account, uint256 amount);

IL1AssetDeploymentTracker

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

bridgeCheckCounterpartAddress

function bridgeCheckCounterpartAddress(
  uint256 _chainId,
  bytes32 _assetId,
  address _originalCaller,
  address _assetHandlerAddressOnCounterpart
) external view;

IL1AssetHandler

Git Source

Author: Matter Labs

Used for any asset handler and called by the L1AssetRouter

Note: security-contact: security@matterlabs.dev

Functions

bridgeRecoverFailedTransfer

function bridgeRecoverFailedTransfer(
  uint256 _chainId,
  bytes32 _assetId,
  address _depositSender,
  bytes calldata _data
) external payable;

Parameters

NameTypeDescription
_chainIduint256the chainId that the message will be sent to
_assetIdbytes32the assetId of the asset being bridged
_depositSenderaddressthe address of the entity that initiated the deposit.
_databytesthe actual data specified for the function

IL1BaseTokenAssetHandler

Git Source

Author: Matter Labs

Used for any asset handler and called by the L1AssetRouter

Note: security-contact: security@matterlabs.dev

Functions

tokenAddress

Used to get the token address of an assetId

function tokenAddress(bytes32 _assetId) external view returns (address);

IL1ERC20Bridge

Git Source

Author: Matter Labs

Legacy Bridge interface before ZK chain migration, used for backward compatibility with ZKsync Era

Note: security-contact: security@matterlabs.dev

Functions

isWithdrawalFinalized

function isWithdrawalFinalized(uint256 _l2BatchNumber, uint256 _l2MessageIndex)
  external
  view
  returns (bool);

deposit

function deposit(
  address _l2Receiver,
  address _l1Token,
  uint256 _amount,
  uint256 _l2TxGasLimit,
  uint256 _l2TxGasPerPubdataByte,
  address _refundRecipient
) external payable returns (bytes32 txHash);

deposit

function deposit(
  address _l2Receiver,
  address _l1Token,
  uint256 _amount,
  uint256 _l2TxGasLimit,
  uint256 _l2TxGasPerPubdataByte
) external payable returns (bytes32 txHash);

claimFailedDeposit

function claimFailedDeposit(
  address _depositSender,
  address _l1Token,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof
) external;

finalizeWithdrawal

function finalizeWithdrawal(
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes calldata _message,
  bytes32[] calldata _merkleProof
) external;

l2TokenAddress

function l2TokenAddress(address _l1Token) external view returns (address);

L1_NULLIFIER

function L1_NULLIFIER() external view returns (IL1Nullifier);

L1_ASSET_ROUTER

function L1_ASSET_ROUTER() external view returns (IL1AssetRouter);

L1_NATIVE_TOKEN_VAULT

function L1_NATIVE_TOKEN_VAULT() external view returns (IL1NativeTokenVault);

l2TokenBeacon

function l2TokenBeacon() external view returns (address);

l2Bridge

function l2Bridge() external view returns (address);

depositAmount

function depositAmount(
  address _account,
  address _l1Token,
  bytes32 _depositL2TxHash
) external view returns (uint256 amount);

Events

DepositInitiated

event DepositInitiated(
  bytes32 indexed l2DepositTxHash,
  address indexed from,
  address indexed to,
  address l1Token,
  uint256 amount
);

WithdrawalFinalized

event WithdrawalFinalized(
  address indexed to, address indexed l1Token, uint256 amount
);

ClaimedFailedDeposit

event ClaimedFailedDeposit(
  address indexed to, address indexed l1Token, uint256 amount
);

IL1Nullifier

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

isWithdrawalFinalized

function isWithdrawalFinalized(
  uint256 _chainId,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex
) external view returns (bool);

claimFailedDepositLegacyErc20Bridge

function claimFailedDepositLegacyErc20Bridge(
  address _depositSender,
  address _l1Token,
  uint256 _amount,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof
) external;

claimFailedDeposit

function claimFailedDeposit(
  uint256 _chainId,
  address _depositSender,
  address _l1Token,
  uint256 _amount,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof
) external;

finalizeDeposit

function finalizeDeposit(
  FinalizeL1DepositParams calldata _finalizeWithdrawalParams
) external;

BRIDGE_HUB

function BRIDGE_HUB() external view returns (IBridgehub);

legacyBridge

function legacyBridge() external view returns (IL1ERC20Bridge);

depositHappened

function depositHappened(uint256 _chainId, bytes32 _l2TxHash)
  external
  view
  returns (bytes32);

bridgehubConfirmL2TransactionForwarded

function bridgehubConfirmL2TransactionForwarded(
  uint256 _chainId,
  bytes32 _txDataHash,
  bytes32 _txHash
) external;

l1NativeTokenVault

function l1NativeTokenVault() external view returns (IL1NativeTokenVault);

setL1NativeTokenVault

function setL1NativeTokenVault(IL1NativeTokenVault _nativeTokenVault) external;

setL1AssetRouter

function setL1AssetRouter(address _l1AssetRouter) external;

chainBalance

function chainBalance(uint256 _chainId, address _token)
  external
  view
  returns (uint256);

l2BridgeAddress

function l2BridgeAddress(uint256 _chainId) external view returns (address);

transferTokenToNTV

function transferTokenToNTV(address _token) external;

nullifyChainBalanceByNTV

function nullifyChainBalanceByNTV(uint256 _chainId, address _token) external;

bridgeRecoverFailedTransfer

Withdraw funds from the initiated deposit, that failed when finalizing on L2.

Processes claims of failed deposit, whether they originated from the legacy bridge or the current system.

function bridgeRecoverFailedTransfer(
  uint256 _chainId,
  address _depositSender,
  bytes32 _assetId,
  bytes memory _assetData,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof
) external;

Parameters

NameTypeDescription
_chainIduint256The ZK chain id to which deposit was initiated.
_depositSenderaddressThe address of the entity that initiated the deposit.
_assetIdbytes32The unique identifier of the deposited L1 token.
_assetDatabytesThe encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information.
_l2TxHashbytes32The L2 transaction hash of the failed deposit finalization.
_l2BatchNumberuint256The L2 batch number where the deposit finalization was processed.
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
_l2TxNumberInBatchuint16The L2 transaction number in a batch, in which the log was sent.
_merkleProofbytes32[]The Merkle proof of the processing L1 -> L2 transaction with deposit finalization.

finalizeWithdrawal

Legacy function to finalize withdrawal via the same interface as the old L1SharedBridge.

Note, that we need to keep this interface, since the L2AssetRouter will continue returning the previous address as the l1SharedBridge. The value returned by it is used in the SDK for finalizing withdrawals.

function finalizeWithdrawal(
  uint256 _chainId,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes calldata _message,
  bytes32[] calldata _merkleProof
) external;

Parameters

NameTypeDescription
_chainIduint256The chain ID of the transaction to check
_l2BatchNumberuint256The L2 batch number where the withdrawal was processed
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message
_l2TxNumberInBatchuint16The L2 transaction number in the batch, in which the log was sent
_messagebytesThe L2 withdraw data, stored in an L2 -> L1 message
_merkleProofbytes32[]The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization

Events

BridgehubDepositFinalized

event BridgehubDepositFinalized(
  uint256 indexed chainId,
  bytes32 indexed txDataHash,
  bytes32 indexed l2DepositTxHash
);

IL1SharedBridgeLegacy

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

l2BridgeAddress

function l2BridgeAddress(uint256 _chainId) external view returns (address);

IL2SharedBridgeLegacy

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

l2TokenBeacon

function l2TokenBeacon() external returns (UpgradeableBeacon);

withdraw

function withdraw(address _l1Receiver, address _l2Token, uint256 _amount)
  external;

l1TokenAddress

function l1TokenAddress(address _l2Token) external view returns (address);

l2TokenAddress

function l2TokenAddress(address _l1Token) external view returns (address);

l1Bridge

function l1Bridge() external view returns (address);

l1SharedBridge

function l1SharedBridge() external view returns (address);

deployBeaconProxy

function deployBeaconProxy(bytes32 _salt) external returns (address);

sendMessageToL1

function sendMessageToL1(bytes calldata _message) external returns (bytes32);

Events

FinalizeDeposit

event FinalizeDeposit(
  address indexed l1Sender,
  address indexed l2Receiver,
  address indexed l2Token,
  uint256 amount
);

IL2SharedBridgeLegacyFunctions

Git Source

Author: Matter Labs

Functions

finalizeDeposit

function finalizeDeposit(
  address _l1Sender,
  address _l2Receiver,
  address _l1Token,
  uint256 _amount,
  bytes calldata _data
) external;

Events

FinalizeDeposit

event FinalizeDeposit(
  address indexed l1Sender,
  address indexed l2Receiver,
  address indexed l2Token,
  uint256 amount
);

WithdrawalInitiated

event WithdrawalInitiated(
  address indexed l2Sender,
  address indexed l1Receiver,
  address indexed l2Token,
  uint256 amount
);

IL2WrappedBaseToken

Git Source

Functions

deposit

function deposit() external payable;

withdraw

function withdraw(uint256 _amount) external;

depositTo

function depositTo(address _to) external payable;

withdrawTo

function withdrawTo(address _to, uint256 _amount) external;

Events

Initialize

event Initialize(string name, string symbol, uint8 decimals);

IWETH9

Git Source

Functions

deposit

function deposit() external payable;

withdraw

function withdraw(uint256 wad) external;

Contents

IL1NativeTokenVault

Git Source

Inherits: INativeTokenVault, IL1AssetDeploymentTracker

Author: Matter Labs

The NTV is an Asset Handler for the L1AssetRouter to handle native tokens

Note: security-contact: security@matterlabs.dev

Functions

L1_NULLIFIER

The L1Nullifier contract

function L1_NULLIFIER() external view returns (IL1Nullifier);

chainBalance

Returns the total number of specific tokens locked for some chain

function chainBalance(uint256 _chainId, bytes32 _assetId)
  external
  view
  returns (uint256);

registerEthToken

Registers ETH token

function registerEthToken() external;

Events

TokenBeaconUpdated

event TokenBeaconUpdated(address indexed l2TokenBeacon);

IL2NativeTokenVault

Git Source

Inherits: INativeTokenVault

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

l2TokenAddress

function l2TokenAddress(address _l1Token) external view returns (address);

setLegacyTokenAssetId

function setLegacyTokenAssetId(address _l2TokenAddress) external;

Events

FinalizeDeposit

event FinalizeDeposit(
  address indexed l1Sender,
  address indexed l2Receiver,
  address indexed l2Token,
  uint256 amount
);

WithdrawalInitiated

event WithdrawalInitiated(
  address indexed l2Sender,
  address indexed l1Receiver,
  address indexed l2Token,
  uint256 amount
);

L2TokenBeaconUpdated

event L2TokenBeaconUpdated(
  address indexed l2TokenBeacon, bytes32 indexed l2TokenProxyBytecodeHash
);

INativeTokenVault

Git Source

Author: Matter Labs

The NTV is an Asset Handler for the L1AssetRouter to handle native tokens

Note: security-contact: security@matterlabs.dev

Functions

WETH_TOKEN

The Weth token address

function WETH_TOKEN() external view returns (address);

ASSET_ROUTER

The AssetRouter contract

function ASSET_ROUTER() external view returns (IAssetRouterBase);

L1_CHAIN_ID

The chain ID of the L1 chain

function L1_CHAIN_ID() external view returns (uint256);

originChainId

Returns the chain ID of the origin chain for a given asset ID

function originChainId(bytes32 assetId) external view returns (uint256);

registerToken

Registers tokens within the NTV.

Allows the bridge to register a token address for the vault.

No access control is ok, since the bridging of tokens should be permissionless. This requires permissionless registration.

The goal is to allow bridging native tokens automatically, by registering them on the fly.

function registerToken(address _l1Token) external;

ensureTokenIsRegistered

Ensures that the native token is registered with the NTV.

This function is used to ensure that the token is registered with the NTV.

function ensureTokenIsRegistered(address _nativeToken)
  external
  returns (bytes32);

getERC20Getters

Used to get the the ERC20 data for a token

function getERC20Getters(address _token, uint256 _originChainId)
  external
  view
  returns (bytes memory);

tokenAddress

Used to get the token address of an assetId

function tokenAddress(bytes32 assetId) external view returns (address);

assetId

Used to get the assetId of a token

function assetId(address token) external view returns (bytes32);

calculateCreate2TokenAddress

Used to get the expected bridged token address corresponding to its native counterpart

function calculateCreate2TokenAddress(
  uint256 _originChainId,
  address _originToken
) external view returns (address);

tryRegisterTokenFromBurnData

Tries to register a token from the provided _burnData and reverts if it is not possible.

function tryRegisterTokenFromBurnData(
  bytes calldata _burnData,
  bytes32 _expectedAssetId
) external;

Events

BridgedTokenBeaconUpdated

event BridgedTokenBeaconUpdated(
  address bridgedTokenBeacon, bytes32 bridgedTokenProxyBytecodeHash
);

Bridge Errors

EthTransferFailed

Git Source

error EthTransferFailed();

NativeTokenVaultAlreadySet

Git Source

error NativeTokenVaultAlreadySet();

WrongMsgLength

Git Source

error WrongMsgLength(uint256 expected, uint256 length);

ZeroAmountToTransfer

Git Source

error ZeroAmountToTransfer();

WrongAmountTransferred

Git Source

error WrongAmountTransferred(uint256 balance, uint256 nullifierChainBalance);

EmptyToken

Git Source

error EmptyToken();

ClaimFailedDepositFailed

Git Source

error ClaimFailedDepositFailed();

WrongL2Sender

Git Source

error WrongL2Sender(address providedL2Sender);

WrongCounterpart

Git Source

error WrongCounterpart();

Contents

IBridgehub

Git Source

Inherits: IAssetHandler, IL1AssetHandler

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

setPendingAdmin

Starts the transfer of admin rights. Only the current admin or owner can propose a new pending one.

New admin can accept admin rights by calling acceptAdmin function.

function setPendingAdmin(address _newPendingAdmin) external;

Parameters

NameTypeDescription
_newPendingAdminaddressAddress of the new admin

acceptAdmin

Accepts transfer of admin rights. Only pending admin can accept the role.

function acceptAdmin() external;

chainTypeManagerIsRegistered

Getters

function chainTypeManagerIsRegistered(address _chainTypeManager)
  external
  view
  returns (bool);

chainTypeManager

function chainTypeManager(uint256 _chainId) external view returns (address);

assetIdIsRegistered

function assetIdIsRegistered(bytes32 _baseTokenAssetId)
  external
  view
  returns (bool);

baseToken

function baseToken(uint256 _chainId) external view returns (address);

baseTokenAssetId

function baseTokenAssetId(uint256 _chainId) external view returns (bytes32);

sharedBridge

function sharedBridge() external view returns (address);

messageRoot

function messageRoot() external view returns (IMessageRoot);

getZKChain

function getZKChain(uint256 _chainId) external view returns (address);

getAllZKChains

function getAllZKChains() external view returns (address[] memory);

getAllZKChainChainIDs

function getAllZKChainChainIDs() external view returns (uint256[] memory);

migrationPaused

function migrationPaused() external view returns (bool);

admin

function admin() external view returns (address);

assetRouter

function assetRouter() external view returns (address);

proveL2MessageInclusion

Mailbox forwarder

function proveL2MessageInclusion(
  uint256 _chainId,
  uint256 _batchNumber,
  uint256 _index,
  L2Message calldata _message,
  bytes32[] calldata _proof
) external view returns (bool);

proveL2LogInclusion

function proveL2LogInclusion(
  uint256 _chainId,
  uint256 _batchNumber,
  uint256 _index,
  L2Log memory _log,
  bytes32[] calldata _proof
) external view returns (bool);

proveL1ToL2TransactionStatus

function proveL1ToL2TransactionStatus(
  uint256 _chainId,
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof,
  TxStatus _status
) external view returns (bool);

requestL2TransactionDirect

function requestL2TransactionDirect(
  L2TransactionRequestDirect calldata _request
) external payable returns (bytes32 canonicalTxHash);

requestL2TransactionTwoBridges

function requestL2TransactionTwoBridges(
  L2TransactionRequestTwoBridgesOuter calldata _request
) external payable returns (bytes32 canonicalTxHash);

l2TransactionBaseCost

function l2TransactionBaseCost(
  uint256 _chainId,
  uint256 _gasPrice,
  uint256 _l2GasLimit,
  uint256 _l2GasPerPubdataByteLimit
) external view returns (uint256);

createNewChain

function createNewChain(
  uint256 _chainId,
  address _chainTypeManager,
  bytes32 _baseTokenAssetId,
  uint256 _salt,
  address _admin,
  bytes calldata _initData,
  bytes[] calldata _factoryDeps
) external returns (uint256 chainId);

addChainTypeManager

function addChainTypeManager(address _chainTypeManager) external;

removeChainTypeManager

function removeChainTypeManager(address _chainTypeManager) external;

addTokenAssetId

function addTokenAssetId(bytes32 _baseTokenAssetId) external;

setAddresses

function setAddresses(
  address _sharedBridge,
  ICTMDeploymentTracker _l1CtmDeployer,
  IMessageRoot _messageRoot
) external;

whitelistedSettlementLayers

function whitelistedSettlementLayers(uint256 _chainId)
  external
  view
  returns (bool);

registerSettlementLayer

function registerSettlementLayer(
  uint256 _newSettlementLayerChainId,
  bool _isWhitelisted
) external;

settlementLayer

function settlementLayer(uint256 _chainId) external view returns (uint256);

forwardTransactionOnGateway

function forwardTransactionOnGateway(
  uint256 _chainId,
  bytes32 _canonicalTxHash,
  uint64 _expirationTimestamp
) external;

ctmAssetIdFromChainId

function ctmAssetIdFromChainId(uint256 _chainId)
  external
  view
  returns (bytes32);

ctmAssetIdFromAddress

function ctmAssetIdFromAddress(address _ctmAddress)
  external
  view
  returns (bytes32);

l1CtmDeployer

function l1CtmDeployer() external view returns (ICTMDeploymentTracker);

ctmAssetIdToAddress

function ctmAssetIdToAddress(bytes32 _assetInfo)
  external
  view
  returns (address);

setCTMAssetAddress

function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress)
  external;

L1_CHAIN_ID

function L1_CHAIN_ID() external view returns (uint256);

registerAlreadyDeployedZKChain

function registerAlreadyDeployedZKChain(uint256 _chainId, address _hyperchain)
  external;

getHyperchain

return the ZK chain contract for a chainId

It is a legacy method. Do not use!

function getHyperchain(uint256 _chainId) external view returns (address);

registerLegacyChain

function registerLegacyChain(uint256 _chainId) external;

pauseMigration

function pauseMigration() external;

unpauseMigration

function unpauseMigration() external;

Events

NewPendingAdmin

pendingAdmin is changed

Also emitted when new admin is accepted and in this case, newPendingAdmin would be zero address

event NewPendingAdmin(
  address indexed oldPendingAdmin, address indexed newPendingAdmin
);

NewAdmin

Admin changed

event NewAdmin(address indexed oldAdmin, address indexed newAdmin);

AssetRegistered

CTM asset registered

event AssetRegistered(
  bytes32 indexed assetInfo,
  address indexed _assetAddress,
  bytes32 indexed additionalData,
  address sender
);

SettlementLayerRegistered

event SettlementLayerRegistered(
  uint256 indexed chainId, bool indexed isWhitelisted
);

MigrationStarted

Emitted when the bridging to the chain is started.

event MigrationStarted(
  uint256 indexed chainId,
  bytes32 indexed assetId,
  uint256 indexed settlementLayerChainId
);

Parameters

NameTypeDescription
chainIduint256Chain ID of the ZK chain
assetIdbytes32Asset ID of the token for the zkChain's CTM
settlementLayerChainIduint256The chain id of the settlement layer the chain migrates to.

MigrationFinalized

Emitted when the bridging to the chain is complete.

event MigrationFinalized(
  uint256 indexed chainId, bytes32 indexed assetId, address indexed zkChain
);

Parameters

NameTypeDescription
chainIduint256Chain ID of the ZK chain
assetIdbytes32Asset ID of the token for the zkChain's CTM
zkChainaddressThe address of the ZK chain on the chain where it is migrated to.

NewChain

event NewChain(
  uint256 indexed chainId,
  address chainTypeManager,
  address indexed chainGovernance
);

ChainTypeManagerAdded

event ChainTypeManagerAdded(address indexed chainTypeManager);

ChainTypeManagerRemoved

event ChainTypeManagerRemoved(address indexed chainTypeManager);

BaseTokenAssetIdRegistered

event BaseTokenAssetIdRegistered(bytes32 indexed assetId);

ICTMDeploymentTracker

Git Source

Inherits: IL1AssetDeploymentTracker

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

bridgehubDeposit

function bridgehubDeposit(
  uint256 _chainId,
  address _originalCaller,
  uint256 _l2Value,
  bytes calldata _data
) external payable returns (L2TransactionRequestTwoBridgesInner memory request);

BRIDGE_HUB

function BRIDGE_HUB() external view returns (IBridgehub);

L1_ASSET_ROUTER

function L1_ASSET_ROUTER() external view returns (IAssetRouterBase);

registerCTMAssetOnL1

function registerCTMAssetOnL1(address _ctmAddress) external;

calculateAssetId

function calculateAssetId(address _l1CTM) external view returns (bytes32);

IMessageRoot

Git Source

Author: Matter Labs

MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot.

Note: security-contact: security@matterlabs.dev

Functions

BRIDGE_HUB

function BRIDGE_HUB() external view returns (IBridgehub);

addNewChain

function addNewChain(uint256 _chainId) external;

addChainBatchRoot

function addChainBatchRoot(
  uint256 _chainId,
  uint256 _batchNumber,
  bytes32 _chainBatchRoot
) external;

Contents

IL1Messenger

Git Source

Author: Matter Labs

The interface of the L1 Messenger contract, responsible for sending messages to L1.

Note: security-contact: security@matterlabs.dev

Functions

sendToL1

function sendToL1(bytes calldata _message) external returns (bytes32);

IL2ContractDeployer

Git Source

Author: Matter Labs

System smart contract that is responsible for deploying other smart contracts on a ZK chain.

Functions

allowedBytecodeTypesToDeploy

Returns what types of bytecode are allowed to be deployed on this chain

function allowedBytecodeTypesToDeploy()
  external
  view
  returns (AllowedBytecodeTypes mode);

forceDeployOnAddresses

This method is to be used only during an upgrade to set bytecodes on specific addresses.

function forceDeployOnAddresses(ForceDeployment[] calldata _deployParams)
  external;

create2

Deploys a contract with similar address derivation rules to the EVM's CREATE2 opcode.

function create2(bytes32 _salt, bytes32 _bytecodeHash, bytes calldata _input)
  external;

Parameters

NameTypeDescription
_saltbytes32The create2 salt.
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_inputbytesThe constructor calldata.

setAllowedBytecodeTypesToDeploy

Changes what types of bytecodes are allowed to be deployed on the chain.

function setAllowedBytecodeTypesToDeploy(
  AllowedBytecodeTypes newAllowedBytecodeTypes
) external;

Parameters

NameTypeDescription
newAllowedBytecodeTypesAllowedBytecodeTypesThe new allowed bytecode types mode.

Structs

ForceDeployment

A struct that describes a forced deployment on an address.

struct ForceDeployment {
  bytes32 bytecodeHash;
  address newAddress;
  bool callConstructor;
  uint256 value;
  bytes input;
}

Properties

NameTypeDescription
bytecodeHashbytes32The bytecode hash to put on an address.
newAddressaddressThe address on which to deploy the bytecodehash to.
callConstructorboolWhether to run the constructor on the force deployment.
valueuint256The msg.value with which to initialize a contract.
inputbytesThe constructor calldata.

Contents

Contents

IRestriction

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

getSupportsRestrictionMagic

A method used to check that the contract supports this interface.

function getSupportsRestrictionMagic() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Returns the RESTRICTION_MAGIC

validateCall

Ensures that the invoker has the required role to call the function.

function validateCall(Call calldata _call, address _invoker) external view;

Parameters

NameTypeDescription
_callCallThe call data.
_invokeraddressThe address of the invoker.

Constants

Git Source

RESTRICTION_MAGIC

The magic value that has to be returned by the getSupportsRestrictionMagic

bytes32 constant RESTRICTION_MAGIC = keccak256("Restriction");

IAccessControlRestriction

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Events

RoleSet

Emitted when the required role for a specific function is set.

event RoleSet(
  address indexed target, bytes4 indexed selector, bytes32 requiredRole
);

FallbackRoleSet

Emitted when the required role for a fallback function is set.

event FallbackRoleSet(address indexed target, bytes32 requiredRole);

IChainAdmin

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

getRestrictions

Returns the list of active restrictions.

function getRestrictions() external view returns (address[] memory);

isRestrictionActive

Checks if the restriction is active.

function isRestrictionActive(address _restriction) external view returns (bool);

Parameters

NameTypeDescription
_restrictionaddressThe address of the restriction contract.

addRestriction

Adds a new restriction to the active restrictions set.

function addRestriction(address _restriction) external;

Parameters

NameTypeDescription
_restrictionaddressThe address of the restriction contract.

removeRestriction

Removes a restriction from the active restrictions set.

Sometimes restrictions might need to enforce their permanence (e.g. if a chain should be a rollup forever).

function removeRestriction(address _restriction) external;

Parameters

NameTypeDescription
_restrictionaddressThe address of the restriction contract.

multicall

Execute multiple calls as part of contract administration.

Intended for batch processing of contract interactions, managing gas efficiency and atomicity of operations.

Note, that this function lacks access control. It is expected that the access control is implemented in a separate restriction contract.

Even though all the validation from external modules is executed via staticcall, the function is marked as nonReentrant to prevent reentrancy attacks in case the staticcall restriction is lifted in the future.

function multicall(Call[] calldata _calls, bool _requireSuccess)
  external
  payable;

Parameters

NameTypeDescription
_callsCall[]Array of Call structures defining target, value, and data for each call.
_requireSuccessboolIf true, reverts transaction on any call failure.

Events

UpdateUpgradeTimestamp

Emitted when the expected upgrade timestamp for a specific protocol version is set.

event UpdateUpgradeTimestamp(
  uint256 indexed protocolVersion, uint256 upgradeTimestamp
);

CallExecuted

Emitted when the call is executed from the contract.

event CallExecuted(Call call, bool success, bytes returnData);

RestrictionAdded

Emitted when a new restriction is added.

event RestrictionAdded(address indexed restriction);

RestrictionRemoved

Emitted when a restriction is removed.

event RestrictionRemoved(address indexed restriction);

EnableEvmEmulator

The EVM emulator has been enabled

event EnableEvmEmulator();

IChainAdminOwnable

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

setTokenMultiplierSetter

function setTokenMultiplierSetter(address _tokenMultiplierSetter) external;

setUpgradeTimestamp

function setUpgradeTimestamp(
  uint256 _protocolVersion,
  uint256 _upgradeTimestamp
) external;

multicall

function multicall(Call[] calldata _calls, bool _requireSuccess)
  external
  payable;

setTokenMultiplier

function setTokenMultiplier(
  IAdmin _chainContract,
  uint128 _nominator,
  uint128 _denominator
) external;

Events

UpdateUpgradeTimestamp

Emitted when the expected upgrade timestamp for a specific protocol version is set.

event UpdateUpgradeTimestamp(
  uint256 indexed _protocolVersion, uint256 _upgradeTimestamp
);

CallExecuted

Emitted when the call is executed from the contract.

event CallExecuted(Call _call, bool _success, bytes _returnData);

NewTokenMultiplierSetter

Emitted when the new token multiplier address is set.

event NewTokenMultiplierSetter(
  address _oldTokenMultiplierSetter, address _newTokenMultiplierSetter
);

Structs

Call

Represents a call to be made during multicall.

struct Call {
  address target;
  uint256 value;
  bytes data;
}

Properties

NameTypeDescription
targetaddressThe address to which the call will be made.
valueuint256The amount of Ether (in wei) to be sent along with the call.
databytesThe calldata to be executed on the target address.

IGovernance

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

isOperation

function isOperation(bytes32 _id) external view returns (bool);

isOperationPending

function isOperationPending(bytes32 _id) external view returns (bool);

isOperationReady

function isOperationReady(bytes32 _id) external view returns (bool);

isOperationDone

function isOperationDone(bytes32 _id) external view returns (bool);

getOperationState

function getOperationState(bytes32 _id) external view returns (OperationState);

scheduleTransparent

function scheduleTransparent(Operation calldata _operation, uint256 _delay)
  external;

scheduleShadow

function scheduleShadow(bytes32 _id, uint256 _delay) external;

cancel

function cancel(bytes32 _id) external;

execute

function execute(Operation calldata _operation) external payable;

executeInstant

function executeInstant(Operation calldata _operation) external payable;

hashOperation

function hashOperation(Operation calldata _operation)
  external
  pure
  returns (bytes32);

updateDelay

function updateDelay(uint256 _newDelay) external;

updateSecurityCouncil

function updateSecurityCouncil(address _newSecurityCouncil) external;

Events

TransparentOperationScheduled

Emitted when transparent operation is scheduled.

event TransparentOperationScheduled(
  bytes32 indexed _id, uint256 delay, Operation _operation
);

ShadowOperationScheduled

Emitted when shadow operation is scheduled.

event ShadowOperationScheduled(bytes32 indexed _id, uint256 delay);

OperationExecuted

Emitted when the operation is executed with delay or instantly.

event OperationExecuted(bytes32 indexed _id);

ChangeSecurityCouncil

Emitted when the security council address is changed.

event ChangeSecurityCouncil(
  address _securityCouncilBefore, address _securityCouncilAfter
);

ChangeMinDelay

Emitted when the minimum delay for future operations is modified.

event ChangeMinDelay(uint256 _delayBefore, uint256 _delayAfter);

OperationCancelled

Emitted when the operation with specified id is cancelled.

event OperationCancelled(bytes32 indexed _id);

Structs

Operation

Defines the structure of an operation that Governance executes.

struct Operation {
  Call[] calls;
  bytes32 predecessor;
  bytes32 salt;
}

Properties

NameTypeDescription
callsCall[]An array of Call structs, each representing a call to be made during the operation.
predecessorbytes32The hash of the predecessor operation, that should be executed before this operation.
saltbytes32A bytes32 value used for creating unique operation hashes.

Enums

OperationState

This enumeration includes the following states:

enum OperationState {
  Unset,
  Waiting,
  Ready,
  Done
}

IPermanentRestriction

Git Source

Author: Matter Labs

The interface for the permanent restriction contract.

Note: security-contact: security@matterlabs.dev

Events

AdminImplementationAllowed

Emitted when the implementation is allowed or disallowed.

event AdminImplementationAllowed(
  bytes32 indexed implementationHash, bool isAllowed
);

AllowedDataChanged

Emitted when a certain calldata is allowed or disallowed.

event AllowedDataChanged(bytes data, bool isAllowed);

SelectorValidationChanged

Emitted when the selector is labeled as validated or not.

event SelectorValidationChanged(bytes4 indexed selector, bool isValidated);

AllowL2Admin

Emitted when the L2 admin is whitelisted or not.

event AllowL2Admin(address indexed adminAddress);

Contents

Contents

IAdmin

Git Source

Inherits: IZKChainBase

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

setPendingAdmin

Starts the transfer of admin rights. Only the current admin can propose a new pending one.

New admin can accept admin rights by calling acceptAdmin function.

function setPendingAdmin(address _newPendingAdmin) external;

Parameters

NameTypeDescription
_newPendingAdminaddressAddress of the new admin

acceptAdmin

Accepts transfer of admin rights. Only pending admin can accept the role.

function acceptAdmin() external;

setValidator

Change validator status (active or not active)

function setValidator(address _validator, bool _active) external;

Parameters

NameTypeDescription
_validatoraddressValidator address
_activeboolActive flag

setPorterAvailability

Change zk porter availability

function setPorterAvailability(bool _zkPorterIsAvailable) external;

Parameters

NameTypeDescription
_zkPorterIsAvailableboolThe availability of zk porter shard

setPriorityTxMaxGasLimit

Change the max L2 gas limit for L1 -> L2 transactions

function setPriorityTxMaxGasLimit(uint256 _newPriorityTxMaxGasLimit) external;

Parameters

NameTypeDescription
_newPriorityTxMaxGasLimituint256The maximum number of L2 gas that a user can request for L1 -> L2 transactions

changeFeeParams

Change the fee params for L1->L2 transactions

function changeFeeParams(FeeParams calldata _newFeeParams) external;

Parameters

NameTypeDescription
_newFeeParamsFeeParamsThe new fee params

setTokenMultiplier

Change the token multiplier for L1->L2 transactions

function setTokenMultiplier(uint128 _nominator, uint128 _denominator) external;

setPubdataPricingMode

Change the pubdata pricing mode before the first batch is processed

function setPubdataPricingMode(PubdataPricingMode _pricingMode) external;

Parameters

NameTypeDescription
_pricingModePubdataPricingModeThe new pubdata pricing mode

setTransactionFilterer

Set the transaction filterer

function setTransactionFilterer(address _transactionFilterer) external;

allowEvmEmulation

Allow EVM emulation on chain

function allowEvmEmulation() external returns (bytes32 canonicalTxHash);

upgradeChainFromVersion

Perform the upgrade from the current protocol version with the corresponding upgrade data

function upgradeChainFromVersion(
  uint256 _protocolVersion,
  Diamond.DiamondCutData calldata _cutData
) external;

Parameters

NameTypeDescription
_protocolVersionuint256The current protocol version from which upgrade is executed
_cutDataDiamond.DiamondCutDataThe diamond cut parameters that is executed in the upgrade

executeUpgrade

Executes a proposed governor upgrade

Only the ChainTypeManager contract can execute the upgrade

function executeUpgrade(Diamond.DiamondCutData calldata _diamondCut) external;

Parameters

NameTypeDescription
_diamondCutDiamond.DiamondCutDataThe diamond cut parameters to be executed

freezeDiamond

Instantly pause the functionality of all freezable facets & their selectors

Only the governance mechanism may freeze Diamond Proxy

function freezeDiamond() external;

unfreezeDiamond

Unpause the functionality of all freezable facets & their selectors

Only the CTM can unfreeze Diamond Proxy

function unfreezeDiamond() external;

genesisUpgrade

function genesisUpgrade(
  address _l1GenesisUpgrade,
  address _ctmDeployer,
  bytes calldata _forceDeploymentData,
  bytes[] calldata _factoryDeps
) external;

setDAValidatorPair

Set the L1 DA validator address as well as the L2 DA validator address.

While in principle it is possible that updating only one of the addresses is needed, usually these should work in pair and L1 validator typically expects a specific input from the L2 Validator. That's why we change those together to prevent admins of chains from shooting themselves in the foot.

function setDAValidatorPair(address _l1DAValidator, address _l2DAValidator)
  external;

Parameters

NameTypeDescription
_l1DAValidatoraddressThe address of the L1 DA validator
_l2DAValidatoraddressThe address of the L2 DA validator

makePermanentRollup

Makes the chain as permanent rollup.

This is a security feature needed for chains that should be trusted to keep their data available even if the chain admin becomes malicious and tries to set the DA validator pair to something which does not publish DA to Ethereum.

DANGEROUS: once activated, there is no way back!

function makePermanentRollup() external;

forwardedBridgeBurn

Similar to IL1AssetHandler interface, used to send chains.

function forwardedBridgeBurn(
  address _settlementLayer,
  address _originalCaller,
  bytes calldata _data
) external payable returns (bytes memory _bridgeMintData);

forwardedBridgeRecoverFailedTransfer

Similar to IL1AssetHandler interface, used to claim failed chain transfers.

function forwardedBridgeRecoverFailedTransfer(
  uint256 _chainId,
  bytes32 _assetInfo,
  address _originalCaller,
  bytes calldata _chainData
) external payable;

forwardedBridgeMint

Similar to IL1AssetHandler interface, used to receive chains.

function forwardedBridgeMint(
  bytes calldata _data,
  bool _contractAlreadyDeployed
) external payable;

prepareChainCommitment

function prepareChainCommitment()
  external
  view
  returns (ZKChainCommitment memory commitment);

Events

IsPorterAvailableStatusUpdate

Porter availability status changes

event IsPorterAvailableStatusUpdate(bool isPorterAvailable);

ValidatorStatusUpdate

Validator's status changed

event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);

NewPendingAdmin

pendingAdmin is changed

Also emitted when new admin is accepted and in this case, newPendingAdmin would be zero address

event NewPendingAdmin(
  address indexed oldPendingAdmin, address indexed newPendingAdmin
);

NewAdmin

Admin changed

event NewAdmin(address indexed oldAdmin, address indexed newAdmin);

NewPriorityTxMaxGasLimit

Priority transaction max L2 gas limit changed

event NewPriorityTxMaxGasLimit(
  uint256 oldPriorityTxMaxGasLimit, uint256 newPriorityTxMaxGasLimit
);

NewFeeParams

Fee params for L1->L2 transactions changed

event NewFeeParams(FeeParams oldFeeParams, FeeParams newFeeParams);

PubdataPricingModeUpdate

Validium mode status changed

event PubdataPricingModeUpdate(PubdataPricingMode validiumMode);

NewTransactionFilterer

The transaction filterer has been updated

event NewTransactionFilterer(
  address oldTransactionFilterer, address newTransactionFilterer
);

NewBaseTokenMultiplier

BaseToken multiplier for L1->L2 transactions changed

event NewBaseTokenMultiplier(
  uint128 oldNominator,
  uint128 oldDenominator,
  uint128 newNominator,
  uint128 newDenominator
);

ExecuteUpgrade

Emitted when an upgrade is executed.

event ExecuteUpgrade(Diamond.DiamondCutData diamondCut);

MigrationComplete

Emitted when the migration to the new settlement layer is complete.

event MigrationComplete();

Freeze

Emitted when the contract is frozen.

event Freeze();

Unfreeze

Emitted when the contract is unfrozen.

event Unfreeze();

EnableEvmEmulator

The EVM emulator has been enabled

event EnableEvmEmulator();

NewL2DAValidator

New pair of DA validators set

event NewL2DAValidator(
  address indexed oldL2DAValidator, address indexed newL2DAValidator
);

NewL1DAValidator

event NewL1DAValidator(
  address indexed oldL1DAValidator, address indexed newL1DAValidator
);

BridgeMint

event BridgeMint(address indexed _account, uint256 _amount);

IDiamondInit

Git Source

Functions

initialize

function initialize(InitializeData calldata _initData)
  external
  returns (bytes32);

IExecutor

Git Source

Inherits: IZKChainBase

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

commitBatchesSharedBridge

Function called by the operator to commit new batches. It is responsible for:

  • Verifying the correctness of their timestamps.
  • Processing their L2->L1 logs.
  • Storing batch commitments.
function commitBatchesSharedBridge(
  uint256 _chainId,
  uint256 _processFrom,
  uint256 _processTo,
  bytes calldata _commitData
) external;

Parameters

NameTypeDescription
_chainIduint256Chain ID of the chain.
_processFromuint256The batch number from which the processing starts.
_processTouint256The batch number at which the processing ends.
_commitDatabytesThe encoded data of the new batches to be committed.

proveBatchesSharedBridge

Batches commitment verification.

Only verifies batch commitments without any other processing.

function proveBatchesSharedBridge(
  uint256 _chainId,
  uint256 _processBatchFrom,
  uint256 _processBatchTo,
  bytes calldata _proofData
) external;

Parameters

NameTypeDescription
_chainIduint256Chain ID of the chain.
_processBatchFromuint256The batch number from which the verification starts.
_processBatchTouint256The batch number at which the verification ends.
_proofDatabytesThe encoded data of the new batches to be verified.

executeBatchesSharedBridge

The function called by the operator to finalize (execute) batches. It is responsible for:

  • Processing all pending operations (commpleting priority requests).
  • Finalizing this batch (i.e. allowing to withdraw funds from the system)
function executeBatchesSharedBridge(
  uint256 _chainId,
  uint256 _processFrom,
  uint256 _processTo,
  bytes calldata _executeData
) external;

Parameters

NameTypeDescription
_chainIduint256Chain ID of the chain.
_processFromuint256The batch number from which the execution starts.
_processTouint256The batch number at which the execution ends.
_executeDatabytesThe encoded data of the new batches to be executed.

revertBatchesSharedBridge

Reverts unexecuted batches

function revertBatchesSharedBridge(uint256 _chainId, uint256 _newLastBatch)
  external;

Parameters

NameTypeDescription
_chainIduint256Chain ID of the chain
_newLastBatchuint256batch number after which batches should be reverted NOTE: Doesn't delete the stored data about batches, but only decreases counters that are responsible for the number of batches

Events

BlockCommit

Event emitted when a batch is committed

It has the name "BlockCommit" and not "BatchCommit" due to backward compatibility considerations

event BlockCommit(
  uint256 indexed batchNumber,
  bytes32 indexed batchHash,
  bytes32 indexed commitment
);

Parameters

NameTypeDescription
batchNumberuint256Number of the batch committed
batchHashbytes32Hash of the L2 batch
commitmentbytes32Calculated input for the ZKsync circuit

BlocksVerification

Event emitted when batches are verified

It has the name "BlocksVerification" and not "BatchesVerification" due to backward compatibility considerations

event BlocksVerification(
  uint256 indexed previousLastVerifiedBatch,
  uint256 indexed currentLastVerifiedBatch
);

Parameters

NameTypeDescription
previousLastVerifiedBatchuint256Batch number of the previous last verified batch
currentLastVerifiedBatchuint256Batch number of the current last verified batch

BlockExecution

Event emitted when a batch is executed

It has the name "BlockExecution" and not "BatchExecution" due to backward compatibility considerations

event BlockExecution(
  uint256 indexed batchNumber,
  bytes32 indexed batchHash,
  bytes32 indexed commitment
);

Parameters

NameTypeDescription
batchNumberuint256Number of the batch executed
batchHashbytes32Hash of the L2 batch
commitmentbytes32Verified input for the ZKsync circuit

BlocksRevert

Event emitted when batches are reverted

It has the name "BlocksRevert" and not "BatchesRevert" due to backward compatibility considerations

event BlocksRevert(
  uint256 totalBatchesCommitted,
  uint256 totalBatchesVerified,
  uint256 totalBatchesExecuted
);

Parameters

NameTypeDescription
totalBatchesCommitteduint256Total number of committed batches after the revert
totalBatchesVerifieduint256Total number of verified batches after the revert
totalBatchesExecuteduint256Total number of executed batches

Structs

StoredBatchInfo

Rollup batch stored data

struct StoredBatchInfo {
  uint64 batchNumber;
  bytes32 batchHash;
  uint64 indexRepeatedStorageChanges;
  uint256 numberOfLayer1Txs;
  bytes32 priorityOperationsHash;
  bytes32 l2LogsTreeRoot;
  uint256 timestamp;
  bytes32 commitment;
}

Properties

NameTypeDescription
batchNumberuint64Rollup batch number
batchHashbytes32Hash of L2 batch
indexRepeatedStorageChangesuint64The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more
numberOfLayer1Txsuint256Number of priority operations to be processed
priorityOperationsHashbytes32Hash of all priority operations from this batch
l2LogsTreeRootbytes32Root hash of tree that contains L2 -> L1 messages from this batch
timestampuint256Rollup batch timestamp, have the same format as Ethereum batch constant
commitmentbytes32Verified input for the ZKsync circuit

CommitBatchInfo

Data needed to commit new batch

pubdataCommitments format: This will always start with a 1 byte pubdataSource flag. Current allowed values are 0 (calldata) or 1 (blobs) kzg: list of: opening point (16 bytes) || claimed value (32 bytes) || commitment (48 bytes) || proof (48 bytes) = 144 bytes calldata: pubdataCommitments.length - 1 - 32 bytes of pubdata and 32 bytes appended to serve as the blob commitment part for the aux output part of the batch commitment

For 2 blobs we will be sending 288 bytes of calldata instead of the full amount for pubdata.

When using calldata, we only need to send one blob commitment since the max number of bytes in calldata fits in a single blob and we can pull the linear hash from the system logs

struct CommitBatchInfo {
  uint64 batchNumber;
  uint64 timestamp;
  uint64 indexRepeatedStorageChanges;
  bytes32 newStateRoot;
  uint256 numberOfLayer1Txs;
  bytes32 priorityOperationsHash;
  bytes32 bootloaderHeapInitialContentsHash;
  bytes32 eventsQueueStateHash;
  bytes systemLogs;
  bytes operatorDAInput;
}

Properties

NameTypeDescription
batchNumberuint64Number of the committed batch
timestampuint64Unix timestamp denoting the start of the batch execution
indexRepeatedStorageChangesuint64The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more
newStateRootbytes32The state root of the full state tree
numberOfLayer1Txsuint256Number of priority operations to be processed
priorityOperationsHashbytes32Hash of all priority operations from this batch
bootloaderHeapInitialContentsHashbytes32Hash of the initial contents of the bootloader heap. In practice it serves as the commitment to the transactions in the batch.
eventsQueueStateHashbytes32Hash of the events queue state. In practice it serves as the commitment to the events in the batch.
systemLogsbytesconcatenation of all L2 -> L1 system logs in the batch
operatorDAInputbytesPacked pubdata commitments/data.

Constants

Git Source

L2_LOG_ADDRESS_OFFSET

Offset used to pull Address From Log. Equal to 4 (bytes for isService)

uint256 constant L2_LOG_ADDRESS_OFFSET = 4;

L2_LOG_KEY_OFFSET

Offset used to pull Key From Log. Equal to 4 (bytes for isService) + 20 (bytes for address)

uint256 constant L2_LOG_KEY_OFFSET = 24;

L2_LOG_VALUE_OFFSET

Offset used to pull Value From Log. Equal to 4 (bytes for isService) + 20 (bytes for address) + 32 (bytes for key)

uint256 constant L2_LOG_VALUE_OFFSET = 56;

MAX_NUMBER_OF_BLOBS

Max number of blobs currently supported

uint256 constant MAX_NUMBER_OF_BLOBS = 6;

TOTAL_BLOBS_IN_COMMITMENT

The number of blobs that must be present in the commitment to a batch. It represents the maximal number of blobs that circuits can support and can be larger than the maximal number of blobs supported by the contract (MAX_NUMBER_OF_BLOBS).

uint256 constant TOTAL_BLOBS_IN_COMMITMENT = 16;

IGetters

Git Source

Inherits: IZKChainBase

Author: Matter Labs

Most of the methods simply return the values that correspond to the current diamond proxy and possibly not to the ZK Chain as a whole. For example, if the chain is migrated to another settlement layer, the values returned by this facet will correspond to the values stored on this chain and possilbly not the canonical state of the chain.

Note: security-contact: security@matterlabs.dev

Functions

getVerifier

function getVerifier() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the verifier smart contract

getAdmin

function getAdmin() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the current admin

getPendingAdmin

function getPendingAdmin() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the pending admin

getBridgehub

function getBridgehub() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the bridgehub

getChainTypeManager

function getChainTypeManager() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the state transition

getChainId

function getChainId() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The chain ID

getBaseToken

function getBaseToken() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the base token

getBaseTokenAssetId

function getBaseTokenAssetId() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The address of the base token

getTotalBatchesCommitted

function getTotalBatchesCommitted() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed

getTotalBatchesVerified

function getTotalBatchesVerified() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed & verified

getTotalBatchesExecuted

function getTotalBatchesExecuted() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed & verified & executed

getTransactionFilterer

function getTransactionFilterer() external view returns (address);

getTotalPriorityTxs

function getTotalPriorityTxs() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of priority operations that were added to the priority queue, including all processed ones

getPriorityTreeStartIndex

function getPriorityTreeStartIndex() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The start index of the priority tree, i.e. the index of the first priority operation that was included into the priority tree.

getPriorityTreeRoot

function getPriorityTreeRoot() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The root hash of the priority tree

isPriorityQueueActive

function isPriorityQueueActive() external view returns (bool);

Returns

NameTypeDescription
<none>boolWhether the priority queue is active, i.e. whether new priority operations are appended to it. Once the chain processes all the transactions that were present in the priority queue, all the L1->L2 related operations will start to get done using the priority tree.

getFirstUnprocessedPriorityTx

The function that returns the first unprocessed priority transaction.

Returns zero if and only if no operations were processed from the queue.

If all the transactions were processed, it will return the last processed index, so in case exactly unprocessed transactions are needed, one should check that getPriorityQueueSize() is greater than 0.

function getFirstUnprocessedPriorityTx() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256Index of the oldest priority operation that wasn't processed yet

getPriorityQueueSize

function getPriorityQueueSize() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of priority operations currently in the queue

isValidator

function isValidator(address _address) external view returns (bool);

Returns

NameTypeDescription
<none>boolWhether the address has a validator access

l2LogsRootHash

function l2LogsRootHash(uint256 _batchNumber)
  external
  view
  returns (bytes32 merkleRoot);

Returns

NameTypeDescription
merkleRootbytes32Merkle root of the tree with L2 logs for the selected batch

storedBatchHash

For unfinalized (non executed) batches may change

returns zero for non-committed batches

function storedBatchHash(uint256 _batchNumber) external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The hash of committed L2 batch.

getL2BootloaderBytecodeHash

function getL2BootloaderBytecodeHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Bytecode hash of bootloader program.

getL2DefaultAccountBytecodeHash

function getL2DefaultAccountBytecodeHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Bytecode hash of default account (bytecode for EOA).

getL2EvmEmulatorBytecodeHash

function getL2EvmEmulatorBytecodeHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Bytecode hash of EVM emulator.

getVerifierParams

This function is deprecated and will soon be removed.

function getVerifierParams() external view returns (VerifierParams memory);

Returns

NameTypeDescription
<none>VerifierParamsVerifier parameters.

isDiamondStorageFrozen

function isDiamondStorageFrozen() external view returns (bool);

Returns

NameTypeDescription
<none>boolWhether the diamond is frozen or not

getProtocolVersion

function getProtocolVersion() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The current packed protocol version. To access human-readable version, use getSemverProtocolVersion function.

getSemverProtocolVersion

function getSemverProtocolVersion()
  external
  view
  returns (uint32, uint32, uint32);

Returns

NameTypeDescription
<none>uint32The tuple of (major, minor, patch) protocol version.
<none>uint32
<none>uint32

getL2SystemContractsUpgradeTxHash

function getL2SystemContractsUpgradeTxHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The upgrade system contract transaction hash, 0 if the upgrade is not initialized

getL2SystemContractsUpgradeBatchNumber

*It is equal to 0 in the following two cases:

  • No upgrade transaction has ever been processed.
  • The upgrade transaction has been processed and the batch with such transaction has been executed (i.e. finalized).*
function getL2SystemContractsUpgradeBatchNumber()
  external
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256The L2 batch number in which the upgrade transaction was processed.

getPriorityTxMaxGasLimit

function getPriorityTxMaxGasLimit() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The maximum number of L2 gas that a user can request for L1 -> L2 transactions

isEthWithdrawalFinalized

function isEthWithdrawalFinalized(
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex
) external view returns (bool);

Parameters

NameTypeDescription
_l2BatchNumberuint256The L2 batch number within which the withdrawal happened.
_l2MessageIndexuint256The index of the L2->L1 message denoting the withdrawal.

Returns

NameTypeDescription
<none>boolWhether a withdrawal has been finalized.

getPubdataPricingMode

function getPubdataPricingMode() external view returns (PubdataPricingMode);

Returns

NameTypeDescription
<none>PubdataPricingModeThe pubdata pricing mode.

baseTokenGasPriceMultiplierNominator

function baseTokenGasPriceMultiplierNominator() external view returns (uint128);

Returns

NameTypeDescription
<none>uint128the baseTokenGasPriceMultiplierNominator, used to compare the baseTokenPrice to ether for L1->L2 transactions

baseTokenGasPriceMultiplierDenominator

function baseTokenGasPriceMultiplierDenominator()
  external
  view
  returns (uint128);

Returns

NameTypeDescription
<none>uint128the baseTokenGasPriceMultiplierDenominator, used to compare the baseTokenPrice to ether for L1->L2 transactions

facets

function facets() external view returns (Facet[] memory);

Returns

NameTypeDescription
<none>Facet[]result All facet addresses and their function selectors

facetFunctionSelectors

function facetFunctionSelectors(address _facet)
  external
  view
  returns (bytes4[] memory);

Returns

NameTypeDescription
<none>bytes4[]NON-sorted array with function selectors supported by a specific facet

facetAddresses

function facetAddresses() external view returns (address[] memory facets);

Returns

NameTypeDescription
facetsaddress[]NON-sorted array of facet addresses supported on diamond

facetAddress

function facetAddress(bytes4 _selector) external view returns (address facet);

Returns

NameTypeDescription
facetaddressThe facet address associated with a selector. Zero if the selector is not added to the diamond

isFunctionFreezable

function isFunctionFreezable(bytes4 _selector) external view returns (bool);

Returns

NameTypeDescription
<none>boolWhether the selector can be frozen by the admin or always accessible

isFacetFreezable

function isFacetFreezable(address _facet)
  external
  view
  returns (bool isFreezable);

Returns

NameTypeDescription
isFreezableboolWhether the facet can be frozen by the admin or always accessible

getSettlementLayer

function getSettlementLayer() external view returns (address);

Returns

NameTypeDescription
<none>addressThe address of the current settlement layer.

Structs

Facet

Faсet structure compatible with the EIP-2535 diamond loupe

struct Facet {
  address addr;
  bytes4[] selectors;
}

Properties

NameTypeDescription
addraddressThe address of the facet contract
selectorsbytes4[]The NON-sorted array with selectors associated with facet

IL1DAValidator

Git Source

Functions

checkDA

The function that checks the data availability for the given batch input.

function checkDA(
  uint256 _chainId,
  uint256 _batchNumber,
  bytes32 _l2DAValidatorOutputHash,
  bytes calldata _operatorDAInput,
  uint256 _maxBlobsSupported
) external returns (L1DAValidatorOutput memory output);

Parameters

NameTypeDescription
_chainIduint256The chain id of the chain that is being committed.
_batchNumberuint256The batch number for which the data availability is being checked.
_l2DAValidatorOutputHashbytes32The hash of that was returned by the l2DAValidator.
_operatorDAInputbytesThe DA input by the operator provided on L1.
_maxBlobsSupporteduint256The maximal number of blobs supported by the chain. We provide this value for future compatibility. This is needed because the corresponding blobsLinearHashes/blobsOpeningCommitments in the L1DAValidatorOutput struct will have to have this length as it is required to be static by the circuits.

ILegacyGetters

Git Source

Inherits: IZKChainBase

Author: Matter Labs

This interface contains getters for the ZKsync contract that should not be used, but still are kept for backward compatibility.

Note: security-contact: security@matterlabs.dev

Functions

getTotalBlocksCommitted

It is a deprecated method, please use getTotalBatchesCommitted instead

function getTotalBlocksCommitted() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed

getTotalBlocksVerified

It is a deprecated method, please use getTotalBatchesVerified instead.

function getTotalBlocksVerified() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed & verified

getTotalBlocksExecuted

It is a deprecated method, please use getTotalBatchesExecuted instead.

function getTotalBlocksExecuted() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of batches that were committed & verified & executed

storedBlockHash

For unfinalized (non executed) batches may change

It is a deprecated method, please use storedBatchHash instead.

returns zero for non-committed batches

function storedBlockHash(uint256 _batchNumber) external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32The hash of committed L2 batch.

getL2SystemContractsUpgradeBlockNumber

It is a deprecated method, please use getL2SystemContractsUpgradeBatchNumber instead.

*It is equal to 0 in the following two cases:

  • No upgrade transaction has ever been processed.
  • The upgrade transaction has been processed and the batch with such transaction has been executed (i.e. finalized).*
function getL2SystemContractsUpgradeBlockNumber()
  external
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256The L2 batch number in which the upgrade transaction was processed.

IMailbox

Git Source

Inherits: IZKChainBase

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

proveL2MessageInclusion

Prove that a specific arbitrary-length message was sent in a specific L2 batch number

function proveL2MessageInclusion(
  uint256 _batchNumber,
  uint256 _index,
  L2Message calldata _message,
  bytes32[] calldata _proof
) external view returns (bool);

Parameters

NameTypeDescription
_batchNumberuint256The executed L2 batch number in which the message appeared
_indexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message
_messageL2MessageInformation about the sent message: sender address, the message itself, tx index in the L2 batch where the message was sent
_proofbytes32[]Merkle proof for inclusion of L2 log that was sent with the message

Returns

NameTypeDescription
<none>boolWhether the proof is valid

proveL2LogInclusion

Prove that a specific L2 log was sent in a specific L2 batch

function proveL2LogInclusion(
  uint256 _batchNumber,
  uint256 _index,
  L2Log memory _log,
  bytes32[] calldata _proof
) external view returns (bool);

Parameters

NameTypeDescription
_batchNumberuint256The executed L2 batch number in which the log appeared
_indexuint256The position of the l2log in the L2 logs Merkle tree
_logL2LogInformation about the sent log
_proofbytes32[]Merkle proof for inclusion of the L2 log

Returns

NameTypeDescription
<none>boolWhether the proof is correct and L2 log is included in batch

proveL1ToL2TransactionStatus

Prove that the L1 -> L2 transaction was processed with the specified status.

function proveL1ToL2TransactionStatus(
  bytes32 _l2TxHash,
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes32[] calldata _merkleProof,
  TxStatus _status
) external view returns (bool);

Parameters

NameTypeDescription
_l2TxHashbytes32The L2 canonical transaction hash
_l2BatchNumberuint256The L2 batch number where the transaction was processed
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message
_l2TxNumberInBatchuint16The L2 transaction number in the batch, in which the log was sent
_merkleProofbytes32[]The Merkle proof of the processing L1 -> L2 transaction
_statusTxStatusThe execution status of the L1 -> L2 transaction (true - success & 0 - fail)

Returns

NameTypeDescription
<none>boolWhether the proof is correct and the transaction was actually executed with provided status NOTE: It may return false for incorrect proof, but it doesn't mean that the L1 -> L2 transaction has an opposite status!

finalizeEthWithdrawal

Finalize the withdrawal and release funds

function finalizeEthWithdrawal(
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBatch,
  bytes calldata _message,
  bytes32[] calldata _merkleProof
) external;

Parameters

NameTypeDescription
_l2BatchNumberuint256The L2 batch number where the withdrawal was processed
_l2MessageIndexuint256The position in the L2 logs Merkle tree of the l2Log that was sent with the message
_l2TxNumberInBatchuint16The L2 transaction number in a batch, in which the log was sent
_messagebytesThe L2 withdraw data, stored in an L2 -> L1 message
_merkleProofbytes32[]The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization

requestL2Transaction

Request execution of L2 transaction from L1.

*If the L2 deposit finalization transaction fails, the _refundRecipient will receive the _l2Value. Please note, the contract may change the refund recipient's address to eliminate sending funds to addresses out of control.

  • If _refundRecipient is a contract on L1, the refund will be sent to the aliased _refundRecipient.
  • If _refundRecipient is set to address(0) and the sender has NO deployed bytecode on L1, the refund will be sent to the msg.sender address.
  • If _refundRecipient is set to address(0) and the sender has deployed bytecode on L1, the refund will be sent to the aliased msg.sender address.*

The address aliasing of L1 contracts as refund recipient on L2 is necessary to guarantee that the funds are controllable, since address aliasing to the from address for the L2 tx will be applied if the L1 msg.sender is a contract. Without address aliasing for L1 contracts as refund recipients they would not be able to make proper L2 tx requests through the Mailbox to use or withdraw the funds from L2, and the funds would be lost.

function requestL2Transaction(
  address _contractL2,
  uint256 _l2Value,
  bytes calldata _calldata,
  uint256 _l2GasLimit,
  uint256 _l2GasPerPubdataByteLimit,
  bytes[] calldata _factoryDeps,
  address _refundRecipient
) external payable returns (bytes32 canonicalTxHash);

Parameters

NameTypeDescription
_contractL2addressThe L2 receiver address
_l2Valueuint256msg.value of L2 transaction
_calldatabytesThe input of the L2 transaction
_l2GasLimituint256Maximum amount of L2 gas that transaction can consume during execution on L2
_l2GasPerPubdataByteLimituint256The maximum amount L2 gas that the operator may charge the user for single byte of pubdata.
_factoryDepsbytes[]An array of L2 bytecodes that will be marked as known on L2
_refundRecipientaddressThe address on L2 that will receive the refund for the transaction.

Returns

NameTypeDescription
canonicalTxHashbytes32The hash of the requested L2 transaction. This hash can be used to follow the transaction status

bridgehubRequestL2Transaction

when requesting transactions through the bridgehub

function bridgehubRequestL2Transaction(
  BridgehubL2TransactionRequest calldata _request
) external returns (bytes32 canonicalTxHash);

bridgehubRequestL2TransactionOnGateway

On the Gateway the chain's mailbox receives the tx from the bridgehub.

function bridgehubRequestL2TransactionOnGateway(
  bytes32 _canonicalTxHash,
  uint64 _expirationTimestamp
) external;

requestL2ServiceTransaction

Request execution of service L2 transaction from L1.

Used for chain configuration. Can be called only by DiamondProxy itself.

function requestL2ServiceTransaction(
  address _contractL2,
  bytes calldata _l2Calldata
) external returns (bytes32 canonicalTxHash);

Parameters

NameTypeDescription
_contractL2addressThe L2 receiver address
_l2CalldatabytesThe input of the L2 transaction

requestL2TransactionToGatewayMailbox

On L1 we have to forward to the Gateway's mailbox which sends to the Bridgehub on the Gw

function requestL2TransactionToGatewayMailbox(
  uint256 _chainId,
  bytes32 _canonicalTxHash,
  uint64 _expirationTimestamp
) external returns (bytes32 canonicalTxHash);

Parameters

NameTypeDescription
_chainIduint256the chainId of the chain
_canonicalTxHashbytes32the canonical transaction hash
_expirationTimestampuint64the expiration timestamp

l2TransactionBaseCost

Estimates the cost in Ether of requesting execution of an L2 transaction from L1

function l2TransactionBaseCost(
  uint256 _gasPrice,
  uint256 _l2GasLimit,
  uint256 _l2GasPerPubdataByteLimit
) external view returns (uint256);

Parameters

NameTypeDescription
_gasPriceuint256expected L1 gas price at which the user requests the transaction execution
_l2GasLimituint256Maximum amount of L2 gas that transaction can consume during execution on L2
_l2GasPerPubdataByteLimituint256The maximum amount of L2 gas that the operator may charge the user for a single byte of pubdata.

Returns

NameTypeDescription
<none>uint256The estimated ETH spent on L2 gas for the transaction

proveL2LeafInclusion

Proves that a certain leaf was included as part of the log merkle tree.

Warning: this function does not enforce any additional checks on the structure of the leaf. This means that it can accept intermediate nodes of the Merkle tree as a _leaf as well as the default "empty" leaves. It is the responsibility of the caller to ensure that the _leaf is a hash of a valid leaf.

function proveL2LeafInclusion(
  uint256 _batchNumber,
  uint256 _batchRootMask,
  bytes32 _leaf,
  bytes32[] calldata _proof
) external view returns (bool);

Events

NewPriorityRequest

transfer Eth to shared bridge as part of migration process

New priority request event. Emitted when a request is placed into the priority queue

event NewPriorityRequest(
  uint256 txId,
  bytes32 txHash,
  uint64 expirationTimestamp,
  L2CanonicalTransaction transaction,
  bytes[] factoryDeps
);

Parameters

NameTypeDescription
txIduint256Serial number of the priority operation
txHashbytes32keccak256 hash of encoded transaction representation
expirationTimestampuint64Timestamp up to which priority request should be processed
transactionL2CanonicalTransactionThe whole transaction structure that is requested to be executed on L2
factoryDepsbytes[]An array of bytecodes that were shown in the L1 public data. Will be marked as known bytecodes in L2

NewRelayedPriorityTransaction

New relayed priority request event. It is emitted on a chain that is deployed on top of the gateway when it receives a request relayed via the Bridgehub.

IMPORTANT: this event most likely will be removed in the future, so no one should rely on it for indexing purposes.

event NewRelayedPriorityTransaction(
  uint256 txId, bytes32 txHash, uint64 expirationTimestamp
);

Parameters

NameTypeDescription
txIduint256Serial number of the priority operation
txHashbytes32keccak256 hash of encoded transaction representation
expirationTimestampuint64Timestamp up to which priority request should be processed

ITransactionFilterer

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

isTransactionAllowed

Check if the transaction is allowed

function isTransactionAllowed(
  address sender,
  address contractL2,
  uint256 mintValue,
  uint256 l2Value,
  bytes memory l2Calldata,
  address refundRecipient
) external view returns (bool);

Parameters

NameTypeDescription
senderaddressThe sender of the transaction
contractL2addressThe L2 receiver address
mintValueuint256The value of the L1 transaction
l2Valueuint256The msg.value of the L2 transaction
l2CalldatabytesThe calldata of the L2 transaction
refundRecipientaddressThe address to refund the excess value

Returns

NameTypeDescription
<none>boolWhether the transaction is allowed

IVerifier

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

verify

Verifies a zk-SNARK proof.

function verify(uint256[] calldata _publicInputs, uint256[] calldata _proof)
  external
  view
  returns (bool);

Returns

NameTypeDescription
<none>boolA boolean value indicating whether the zk-SNARK proof is valid. Note: The function may revert execution instead of returning false in some cases.

verificationKeyHash

Calculates a keccak256 hash of the runtime loaded verification keys.

function verificationKeyHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32vkHash The keccak256 hash of the loaded verification keys.

IVerifierV2

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

verify

Verifies a zk-SNARK proof.

function verify(uint256[] calldata _publicInputs, uint256[] calldata _proof)
  external
  view
  returns (bool);

Returns

NameTypeDescription
<none>boolA boolean value indicating whether the zk-SNARK proof is valid. Note: The function may revert execution instead of returning false in some cases.

verificationKeyHash

Calculates a keccak256 hash of the runtime loaded verification keys.

function verificationKeyHash() external view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32vkHash The keccak256 hash of the loaded verification keys.

IZKChain

Git Source

Inherits: IAdmin, IExecutor, IGetters, IMailbox

Events

ProposeTransparentUpgrade

event ProposeTransparentUpgrade(
  Diamond.DiamondCutData diamondCut,
  uint256 indexed proposalId,
  bytes32 proposalSalt
);

IZKChainBase

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

getName

function getName() external view returns (string memory);

Returns

NameTypeDescription
<none>stringReturns facet name.

Contents

IComplexUpgrader

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

forceDeployAndUpgrade

function forceDeployAndUpgrade(
  IL2ContractDeployer.ForceDeployment[] calldata _forceDeployments,
  address _delegateTo,
  bytes calldata _calldata
) external payable;

upgrade

function upgrade(address _delegateTo, bytes calldata _calldata)
  external
  payable;

IL2GatewayUpgrade

Git Source

Functions

upgrade

function upgrade(
  IL2ContractDeployer.ForceDeployment[] calldata _forceDeployments,
  address _ctmDeployer,
  bytes calldata _fixedForceDeploymentsData,
  bytes calldata _additionalForceDeploymentsData
) external payable;

IL2GenesisUpgrade

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

genesisUpgrade

function genesisUpgrade(
  uint256 _chainId,
  address _ctmDeployer,
  bytes calldata _fixedForceDeploymentsData,
  bytes calldata _additionalForceDeploymentsData
) external payable;

Events

UpgradeComplete

event UpgradeComplete(uint256 _chainId);

ISystemContext

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

setChainId

function setChainId(uint256 _newChainId) external;

Contents

AddressAliasHelper

Git Source

State Variables

offset

uint160 private constant offset =
  uint160(0x1111000000000000000000000000000000001111);

Functions

applyL1ToL2Alias

Utility function converts the address that submitted a tx to the inbox on L1 to the msg.sender viewed on L2

function applyL1ToL2Alias(address l1Address)
  internal
  pure
  returns (address l2Address);

Parameters

NameTypeDescription
l1Addressaddressthe address in the L1 that triggered the tx to L2

Returns

NameTypeDescription
l2AddressaddressL2 address as viewed in msg.sender

undoL1ToL2Alias

Utility function that converts the msg.sender viewed on L2 to the address that submitted a tx to the inbox on L1

function undoL1ToL2Alias(address l2Address)
  internal
  pure
  returns (address l1Address);

Parameters

NameTypeDescription
l2AddressaddressL2 address as viewed in msg.sender

Returns

NameTypeDescription
l1Addressaddressthe address in the L1 that triggered the tx to L2

actualRefundRecipient

Utility function used to calculate the correct refund recipient

function actualRefundRecipient(
  address _refundRecipient,
  address _originalCaller
) internal view returns (address _recipient);

Parameters

NameTypeDescription
_refundRecipientaddressthe address that should receive the refund
_originalCalleraddressthe address that triggered the tx to L2

Returns

NameTypeDescription
_recipientaddressthe corrected address that should receive the refund

Contents

Contents

IConsensusRegistry

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

add

function add(
  address _nodeOwner,
  uint32 _validatorWeight,
  BLS12_381PublicKey calldata _validatorPubKey,
  BLS12_381Signature calldata _validatorPoP,
  uint32 _attesterWeight,
  Secp256k1PublicKey calldata _attesterPubKey
) external;

deactivate

function deactivate(address _nodeOwner) external;

activate

function activate(address _nodeOwner) external;

remove

function remove(address _nodeOwner) external;

changeValidatorWeight

function changeValidatorWeight(address _nodeOwner, uint32 _weight) external;

changeAttesterWeight

function changeAttesterWeight(address _nodeOwner, uint32 _weight) external;

changeValidatorKey

function changeValidatorKey(
  address _nodeOwner,
  BLS12_381PublicKey calldata _pubKey,
  BLS12_381Signature calldata _pop
) external;

changeAttesterKey

function changeAttesterKey(
  address _nodeOwner,
  Secp256k1PublicKey calldata _pubKey
) external;

commitAttesterCommittee

function commitAttesterCommittee() external;

commitValidatorCommittee

function commitValidatorCommittee() external;

getAttesterCommittee

function getAttesterCommittee()
  external
  view
  returns (CommitteeAttester[] memory);

getValidatorCommittee

function getValidatorCommittee()
  external
  view
  returns (CommitteeValidator[] memory);

Events

NodeAdded

event NodeAdded(
  address indexed nodeOwner,
  uint32 validatorWeight,
  BLS12_381PublicKey validatorPubKey,
  BLS12_381Signature validatorPoP,
  uint32 attesterWeight,
  Secp256k1PublicKey attesterPubKey
);

NodeDeactivated

event NodeDeactivated(address indexed nodeOwner);

NodeActivated

event NodeActivated(address indexed nodeOwner);

NodeRemoved

event NodeRemoved(address indexed nodeOwner);

NodeDeleted

event NodeDeleted(address indexed nodeOwner);

NodeValidatorWeightChanged

event NodeValidatorWeightChanged(address indexed nodeOwner, uint32 newWeight);

NodeAttesterWeightChanged

event NodeAttesterWeightChanged(address indexed nodeOwner, uint32 newWeight);

NodeValidatorKeyChanged

event NodeValidatorKeyChanged(
  address indexed nodeOwner,
  BLS12_381PublicKey newPubKey,
  BLS12_381Signature newPoP
);

NodeAttesterKeyChanged

event NodeAttesterKeyChanged(
  address indexed nodeOwner, Secp256k1PublicKey newPubKey
);

ValidatorsCommitted

event ValidatorsCommitted(uint32 commit);

AttestersCommitted

event AttestersCommitted(uint32 commit);

Errors

UnauthorizedOnlyOwnerOrNodeOwner

error UnauthorizedOnlyOwnerOrNodeOwner();

NodeOwnerExists

error NodeOwnerExists();

NodeOwnerDoesNotExist

error NodeOwnerDoesNotExist();

NodeOwnerNotFound

error NodeOwnerNotFound();

ValidatorPubKeyExists

error ValidatorPubKeyExists();

AttesterPubKeyExists

error AttesterPubKeyExists();

InvalidInputNodeOwnerAddress

error InvalidInputNodeOwnerAddress();

InvalidInputBLS12_381PublicKey

error InvalidInputBLS12_381PublicKey();

InvalidInputBLS12_381Signature

error InvalidInputBLS12_381Signature();

InvalidInputSecp256k1PublicKey

error InvalidInputSecp256k1PublicKey();

Structs

Node

Represents a consensus node.

struct Node {
  uint32 attesterLastUpdateCommit;
  uint32 validatorLastUpdateCommit;
  uint32 nodeOwnerIdx;
  AttesterAttr attesterLatest;
  AttesterAttr attesterSnapshot;
  ValidatorAttr validatorLatest;
  ValidatorAttr validatorSnapshot;
}

Properties

NameTypeDescription
attesterLastUpdateCommituint32The latest attestersCommit where the node's attester attributes were updated.
validatorLastUpdateCommituint32The latest validatorsCommit where the node's validator attributes were updated.
nodeOwnerIdxuint32Index of the node owner within the array of node owners.
attesterLatestAttesterAttrAttester attributes to read if node.attesterLastUpdateCommit < attestersCommit.
attesterSnapshotAttesterAttrAttester attributes to read if node.attesterLastUpdateCommit == attestersCommit.
validatorLatestValidatorAttrValidator attributes to read if node.validatorLastUpdateCommit < validatorsCommit.
validatorSnapshotValidatorAttrValidator attributes to read if node.validatorLastUpdateCommit == validatorsCommit.

AttesterAttr

Represents the attester attributes of a consensus node.

struct AttesterAttr {
  bool active;
  bool removed;
  uint32 weight;
  Secp256k1PublicKey pubKey;
}

Properties

NameTypeDescription
activeboolA flag stating if the attester is active.
removedboolA flag stating if the attester has been removed (and is pending a deletion).
weightuint32Attester's voting weight.
pubKeySecp256k1PublicKeyAttester's Secp256k1 public key.

CommitteeAttester

Represents an attester within a committee.

struct CommitteeAttester {
  uint32 weight;
  Secp256k1PublicKey pubKey;
}

Properties

NameTypeDescription
weightuint32Attester's voting weight.
pubKeySecp256k1PublicKeyAttester's Secp256k1 public key.

ValidatorAttr

Represents the validator attributes of a consensus node.

struct ValidatorAttr {
  bool active;
  bool removed;
  uint32 weight;
  BLS12_381PublicKey pubKey;
  BLS12_381Signature proofOfPossession;
}

Properties

NameTypeDescription
activeboolA flag stating if the validator is active.
removedboolA flag stating if the validator has been removed (and is pending a deletion).
weightuint32Validator's voting weight.
pubKeyBLS12_381PublicKeyValidator's BLS12-381 public key.
proofOfPossessionBLS12_381SignatureValidator's Proof-of-possession (a signature over the public key).

CommitteeValidator

Represents a validator within a committee.

struct CommitteeValidator {
  uint32 weight;
  BLS12_381PublicKey pubKey;
  BLS12_381Signature proofOfPossession;
}

Properties

NameTypeDescription
weightuint32Validator's voting weight.
pubKeyBLS12_381PublicKeyValidator's BLS12-381 public key.
proofOfPossessionBLS12_381SignatureValidator's Proof-of-possession (a signature over the public key).

BLS12_381PublicKey

Represents BLS12_381 public key.

struct BLS12_381PublicKey {
  bytes32 a;
  bytes32 b;
  bytes32 c;
}

Properties

NameTypeDescription
abytes32First component of the BLS12-381 public key.
bbytes32Second component of the BLS12-381 public key.
cbytes32Third component of the BLS12-381 public key.

BLS12_381Signature

Represents BLS12_381 signature.

struct BLS12_381Signature {
  bytes32 a;
  bytes16 b;
}

Properties

NameTypeDescription
abytes32First component of the BLS12-381 signature.
bbytes16Second component of the BLS12-381 signature.

Secp256k1PublicKey

Represents Secp256k1 public key.

struct Secp256k1PublicKey {
  bytes1 tag;
  bytes32 x;
}

Properties

NameTypeDescription
tagbytes1Y-coordinate's even/odd indicator of the Secp256k1 public key.
xbytes32X-coordinate component of the Secp256k1 public key.

IL2DAValidator

Git Source

Functions

validatePubdata

function validatePubdata(
  bytes32 _chainedLogsHash,
  bytes32 _logsRootHash,
  bytes32 _chainedMessagesHash,
  bytes32 _chainedBytecodesHash,
  bytes calldata _totalL2ToL1PubdataAndStateDiffs
) external returns (bytes32 outputHash);

IPaymaster

Git Source

Functions

validateAndPayForPaymasterTransaction

Called by the bootloader to verify that the paymaster agrees to pay for the fee for the transaction. This transaction should also send the necessary amount of funds onto the bootloader address.

The developer should strive to preserve as many steps as possible both for valid and invalid transactions as this very method is also used during the gas fee estimation (without some of the necessary data, e.g. signature).

function validateAndPayForPaymasterTransaction(
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  Transaction calldata _transaction
) external payable returns (bytes4 magic, bytes memory context);

Parameters

NameTypeDescription
_txHashbytes32The hash of the transaction
_suggestedSignedHashbytes32The hash of the transaction that is signed by an EOA
_transactionTransactionThe transaction itself.

Returns

NameTypeDescription
magicbytes4The value that should be equal to the signature of the validateAndPayForPaymasterTransaction if the paymaster agrees to pay for the transaction.
contextbytesThe "context" of the transaction: an array of bytes of length at most 1024 bytes, which will be passed to the postTransaction method of the account.

postTransaction

Called by the bootloader after the execution of the transaction. Please note that there is no guarantee that this method will be called at all. Unlike the original EIP4337, this method won't be called if the transaction execution results in out-of-gas.

The exact amount refunded depends on the gas spent by the "postOp" itself and so the developers should take that into account.

function postTransaction(
  bytes calldata _context,
  Transaction calldata _transaction,
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  ExecutionResult _txResult,
  uint256 _maxRefundedGas
) external payable;

Parameters

NameTypeDescription
_contextbytes
_transactionTransaction
_txHashbytes32
_suggestedSignedHashbytes32
_txResultExecutionResult
_maxRefundedGasuint256

Constants

Git Source

PAYMASTER_VALIDATION_SUCCESS_MAGIC

bytes4 constant PAYMASTER_VALIDATION_SUCCESS_MAGIC =
  IPaymaster.validateAndPayForPaymasterTransaction.selector;

IPaymasterFlow

Git Source

Author: Matter Labs

This is NOT an interface to be implemented by contracts. It is just used for encoding.

The interface that is used for encoding/decoding of different types of paymaster flows.

Note: security-contact: security@matterlabs.dev

Functions

general

function general(bytes calldata input) external;

approvalBased

function approvalBased(
  address _token,
  uint256 _minAllowance,
  bytes calldata _innerInput
) external;

Contents

AddressAliasHelper

Git Source

State Variables

offset

uint160 internal constant offset =
  uint160(0x1111000000000000000000000000000000001111);

Functions

applyL1ToL2Alias

Utility function converts the address that submitted a tx to the inbox on L1 to the msg.sender viewed on L2

function applyL1ToL2Alias(address l1Address)
  internal
  pure
  returns (address l2Address);

Parameters

NameTypeDescription
l1Addressaddressthe address in the L1 that triggered the tx to L2

Returns

NameTypeDescription
l2AddressaddressL2 address as viewed in msg.sender

undoL1ToL2Alias

Utility function that converts the msg.sender viewed on L2 to the address that submitted a tx to the inbox on L1

function undoL1ToL2Alias(address l2Address)
  internal
  pure
  returns (address l1Address);

Parameters

NameTypeDescription
l2AddressaddressL2 address as viewed in msg.sender

Returns

NameTypeDescription
l1Addressaddressthe address in the L1 that triggered the tx to L2

Contents

Contents

IAccount

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

validateTransaction

Called by the bootloader to validate that an account agrees to process the transaction (and potentially pay for it).

The developer should strive to preserve as many steps as possible both for valid and invalid transactions as this very method is also used during the gas fee estimation (without some of the necessary data, e.g. signature).

function validateTransaction(
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  Transaction calldata _transaction
) external payable returns (bytes4 magic);

Parameters

NameTypeDescription
_txHashbytes32The hash of the transaction to be used in the explorer
_suggestedSignedHashbytes32The hash of the transaction is signed by EOAs
_transactionTransactionThe transaction itself

Returns

NameTypeDescription
magicbytes4The magic value that should be equal to the signature of this function if the user agrees to proceed with the transaction.

executeTransaction

function executeTransaction(
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  Transaction calldata _transaction
) external payable;

executeTransactionFromOutside

function executeTransactionFromOutside(Transaction calldata _transaction)
  external
  payable;

payForTransaction

function payForTransaction(
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  Transaction calldata _transaction
) external payable;

prepareForPaymaster

function prepareForPaymaster(
  bytes32 _txHash,
  bytes32 _possibleSignedHash,
  Transaction calldata _transaction
) external payable;

Constants

Git Source

ACCOUNT_VALIDATION_SUCCESS_MAGIC

bytes4 constant ACCOUNT_VALIDATION_SUCCESS_MAGIC =
  IAccount.validateTransaction.selector;

IAccountCodeStorage

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

storeAccountConstructingCodeHash

function storeAccountConstructingCodeHash(address _address, bytes32 _hash)
  external;

storeAccountConstructedCodeHash

function storeAccountConstructedCodeHash(address _address, bytes32 _hash)
  external;

markAccountCodeHashAsConstructed

function markAccountCodeHashAsConstructed(address _address) external;

getRawCodeHash

function getRawCodeHash(address _address)
  external
  view
  returns (bytes32 codeHash);

getCodeHash

function getCodeHash(uint256 _input) external view returns (bytes32 codeHash);

getCodeSize

function getCodeSize(uint256 _input) external view returns (uint256 codeSize);

isAccountEVM

function isAccountEVM(address _addr) external view returns (bool);

IBaseToken

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

balanceOf

function balanceOf(uint256) external view returns (uint256);

transferFromTo

function transferFromTo(address _from, address _to, uint256 _amount) external;

totalSupply

function totalSupply() external view returns (uint256);

mint

function mint(address _account, uint256 _amount) external;

withdraw

function withdraw(address _l1Receiver) external payable;

withdrawWithMessage

function withdrawWithMessage(
  address _l1Receiver,
  bytes calldata _additionalData
) external payable;

Events

Mint

event Mint(address indexed account, uint256 amount);

Transfer

event Transfer(address indexed from, address indexed to, uint256 value);

Withdrawal

event Withdrawal(
  address indexed _l2Sender, address indexed _l1Receiver, uint256 _amount
);

WithdrawalWithMessage

event WithdrawalWithMessage(
  address indexed _l2Sender,
  address indexed _l1Receiver,
  uint256 _amount,
  bytes _additionalData
);

IBootloaderUtilities

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

getTransactionHashes

function getTransactionHashes(Transaction calldata _transaction)
  external
  view
  returns (bytes32 txHash, bytes32 signedTxHash);

IBridgehub

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

setAddresses

function setAddresses(
  address _assetRouter,
  address _ctmDeployer,
  address _messageRoot
) external;

owner

function owner() external view returns (address);

IComplexUpgrader

Git Source

Author: Matter Labs

The interface for the ComplexUpgrader contract.

Note: security-contact: security@matterlabs.dev

Functions

forceDeployAndUpgrade

function forceDeployAndUpgrade(
  ForceDeployment[] calldata _forceDeployments,
  address _delegateTo,
  bytes calldata _calldata
) external payable;

upgrade

function upgrade(address _delegateTo, bytes calldata _calldata)
  external
  payable;

ICompressor

Git Source

Author: Matter Labs

The interface for the Compressor contract, responsible for verifying the correctness of the compression of the state diffs and bytecodes.

Note: security-contact: security@matterlabs.dev

Functions

publishCompressedBytecode

function publishCompressedBytecode(
  bytes calldata _bytecode,
  bytes calldata _rawCompressedData
) external returns (bytes32 bytecodeHash);

verifyCompressedStateDiffs

function verifyCompressedStateDiffs(
  uint256 _numberOfStateDiffs,
  uint256 _enumerationIndexSize,
  bytes calldata _stateDiffs,
  bytes calldata _compressedStateDiffs
) external returns (bytes32 stateDiffHash);

Constants

Git Source

OPERATION_BITMASK

uint8 constant OPERATION_BITMASK = 7;

LENGTH_BITS_OFFSET

uint8 constant LENGTH_BITS_OFFSET = 3;

MAX_ENUMERATION_INDEX_SIZE

uint8 constant MAX_ENUMERATION_INDEX_SIZE = 8;

IContractDeployer

Git Source

Author: Matter Labs

Interface of the contract deployer contract -- a system contract responsible for deploying other contracts.

Note: security-contact: security@matterlabs.dev

Functions

allowedBytecodeTypesToDeploy

Returns what types of bytecode are allowed to be deployed on this chain.

function allowedBytecodeTypesToDeploy()
  external
  view
  returns (AllowedBytecodeTypes mode);

Returns

NameTypeDescription
modeAllowedBytecodeTypesThe allowed bytecode types mode.

getNewAddressCreate2

Calculates the address of a deployed contract via create2

function getNewAddressCreate2(
  address _sender,
  bytes32 _bytecodeHash,
  bytes32 _salt,
  bytes calldata _input
) external view returns (address newAddress);

Parameters

NameTypeDescription
_senderaddressThe account that deploys the contract.
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_saltbytes32The create2 salt.
_inputbytesThe constructor data.

Returns

NameTypeDescription
newAddressaddressThe derived address of the account.

getNewAddressCreate

Calculates the address of a deployed contract via create

function getNewAddressCreate(address _sender, uint256 _senderNonce)
  external
  pure
  returns (address newAddress);

Parameters

NameTypeDescription
_senderaddressThe account that deploys the contract.
_senderNonceuint256The deploy nonce of the sender's account.

Returns

NameTypeDescription
newAddressaddressThe derived address of the contract.

create2

Deploys a contract with similar address derivation rules to the EVM's CREATE2 opcode.

function create2(bytes32 _salt, bytes32 _bytecodeHash, bytes calldata _input)
  external
  payable
  returns (address newAddress);

Parameters

NameTypeDescription
_saltbytes32The CREATE2 salt
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_inputbytesThe constructor calldata

Returns

NameTypeDescription
newAddressaddressThe derived address of the contract.

create2Account

Deploys a contract account with similar address derivation rules to the EVM's CREATE2 opcode.

this method may be callable only in system mode, that is checked in the createAccount by onlySystemCall modifier.

function create2Account(
  bytes32 _salt,
  bytes32 _bytecodeHash,
  bytes calldata _input,
  AccountAbstractionVersion _aaVersion
) external payable returns (address newAddress);

Parameters

NameTypeDescription
_saltbytes32The CREATE2 salt
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_inputbytesThe constructor calldata.
_aaVersionAccountAbstractionVersionThe account abstraction version to use.

Returns

NameTypeDescription
newAddressaddressThe derived address of the contract.

create

Deploys a contract with similar address derivation rules to the EVM's CREATE opcode.

Although this method accepts salt as one of its parameters. It is not used anywhere and is needed simply for the consistency for the compiler Note: this method may be callable only in system mode, that is checked in the createAccount by onlySystemCall modifier.

function create(bytes32 _salt, bytes32 _bytecodeHash, bytes calldata _input)
  external
  payable
  returns (address newAddress);

Parameters

NameTypeDescription
_saltbytes32A 32-byte salt.
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_inputbytesThe constructor calldata

Returns

NameTypeDescription
newAddressaddressThe derived address of the contract.

createAccount

Deploys a contract account with similar address derivation rules to the EVM's CREATE opcode.

This method also accepts salt as one of its parameters. It is not used anywhere and it needed simply for the consistency for the compiler

function createAccount(
  bytes32,
  bytes32 _bytecodeHash,
  bytes calldata _input,
  AccountAbstractionVersion _aaVersion
) external payable returns (address newAddress);

Parameters

NameTypeDescription
<none>bytes32
_bytecodeHashbytes32The correctly formatted hash of the bytecode.
_inputbytesThe constructor calldata.
_aaVersionAccountAbstractionVersionThe account abstraction version to use.

Returns

NameTypeDescription
newAddressaddressThe derived address of the contract.

getAccountInfo

Returns information about a certain account.

function getAccountInfo(address _address)
  external
  view
  returns (AccountInfo memory info);

Parameters

NameTypeDescription
_addressaddressThe address of the account.

Returns

NameTypeDescription
infoAccountInfoThe information about the account (AA version and nonce ordering).

extendedAccountVersion

Returns the account abstraction version if _address is a deployed contract. Returns the latest supported account abstraction version if _address is an EOA.

function extendedAccountVersion(address _address)
  external
  view
  returns (AccountAbstractionVersion);

Parameters

NameTypeDescription
_addressaddressThe address of the account.

Returns

NameTypeDescription
<none>AccountAbstractionVersionThe account abstraction version of the account. In particular, Version1 for EOAs, None for non-account contracts. .

updateAccountVersion

Update the used version of the account.

Note that it allows changes from account to non-account and vice versa.

function updateAccountVersion(AccountAbstractionVersion _version) external;

Parameters

NameTypeDescription
_versionAccountAbstractionVersionThe new version of the AA protocol to use.

updateNonceOrdering

Updates the nonce ordering of the account. Since only KeyedSequential ordering is supported, currently this method always reverts.

function updateNonceOrdering(AccountNonceOrdering) external;

forceDeployOnAddresses

This method is to be used only during an upgrade to set bytecodes on specific addresses.

We do not require onlySystemCall here, since the method is accessible only by FORCE_DEPLOYER.

function forceDeployOnAddresses(ForceDeployment[] calldata _deployments)
  external
  payable;

Parameters

NameTypeDescription
_deploymentsForceDeployment[]The list of forced deployments to be done.

createEVM

Deploys an EVM contract using address derivation of EVM's CREATE opcode.

Note: this method may be callable only in system mode.

function createEVM(bytes calldata _initCode)
  external
  payable
  returns (uint256 evmGasUsed, address newAddress);

Parameters

NameTypeDescription
_initCodebytesThe init code for the contract.

Returns

NameTypeDescription
evmGasUseduint256The amount of EVM gas used.
newAddressaddressThe address of created contract.

create2EVM

Deploys an EVM contract using address derivation of EVM's CREATE2 opcode.

Note: this method may be callable only in system mode.

function create2EVM(bytes32 _salt, bytes calldata _initCode)
  external
  payable
  returns (uint256 evmGasUsed, address newAddress);

Parameters

NameTypeDescription
_saltbytes32The CREATE2 salt.
_initCodebytesThe init code for the contract.

Returns

NameTypeDescription
evmGasUseduint256The amount of EVM gas used.
newAddressaddressThe address of created contract.

setAllowedBytecodeTypesToDeploy

Changes what types of bytecodes are allowed to be deployed on the chain.

function setAllowedBytecodeTypesToDeploy(
  AllowedBytecodeTypes newAllowedBytecodeTypes
) external;

Parameters

NameTypeDescription
newAllowedBytecodeTypesAllowedBytecodeTypesThe new allowed bytecode types mode.

Events

ContractDeployed

Emitted when a contract is deployed.

event ContractDeployed(
  address indexed deployerAddress,
  bytes32 indexed bytecodeHash,
  address indexed contractAddress
);

Parameters

NameTypeDescription
deployerAddressaddressThe address of the deployer.
bytecodeHashbytes32The formatted hash of the bytecode that was deployed.
contractAddressaddressThe address of the newly deployed contract.

AccountNonceOrderingUpdated

Emitted when account's nonce ordering is updated. Since currently only KeyedSequential ordering is supported and updating is not possible, the event is not emitted and is reserved for future use when updating becomes possible.

event AccountNonceOrderingUpdated(
  address indexed accountAddress, AccountNonceOrdering nonceOrdering
);

Parameters

NameTypeDescription
accountAddressaddressThe address of the account.
nonceOrderingAccountNonceOrderingThe new nonce ordering of the account.

AccountVersionUpdated

Emitted when account's AA version is updated.

event AccountVersionUpdated(
  address indexed accountAddress, AccountAbstractionVersion aaVersion
);

Parameters

NameTypeDescription
accountAddressaddressThe address of the contract.
aaVersionAccountAbstractionVersionThe new AA version of the contract.

AllowedBytecodeTypesModeUpdated

Emitted when the allowed bytecode types mode is updated (e.g. from EraVm to EraVmAndEVM).

event AllowedBytecodeTypesModeUpdated(AllowedBytecodeTypes mode);

Parameters

NameTypeDescription
modeAllowedBytecodeTypesThe new allowed bytecode types mode.

Structs

AccountInfo

Information about an account contract.

For EOA and simple contracts (i.e. not accounts) this has default value, which corresponds to AccountAbstractionVersion.None.and AccountNonceOrdering.KeyedSequential.

struct AccountInfo {
  AccountAbstractionVersion supportedAAVersion;
  AccountNonceOrdering nonceOrdering;
}

Enums

AccountAbstractionVersion

Defines the version of the account abstraction protocol that a contract claims to follow.

  • None means that the account is just a contract and it should never be interacted with as a custom account
  • Version1 means that the account follows the first version of the account abstraction protocol
enum AccountAbstractionVersion {
  None,
  Version1
}

AccountNonceOrdering

Defines the nonce ordering used by the account

  • KeyedSequential means that it is expected that the nonces are monotonic and increment by 1 at a time for each key (nonces are split 192:64 bits into nonceKey:nonceValue parts, as proposed by EIP-4337).
  • Arbitrary ordering is deprecated.

This ordering is more of a suggestion to the operator on how the AA expects its transactions to be processed and is not considered as a system invariant.

enum AccountNonceOrdering {
  KeyedSequential,
  __DEPRECATED_Arbitrary
}

AllowedBytecodeTypes

Defines what types of bytecode are allowed to be deployed on this chain

  • EraVm means that only native contracts can be deployed
  • EraVmAndEVM means that native contracts and EVM contracts can be deployed
enum AllowedBytecodeTypes {
  EraVm,
  EraVmAndEVM
}

ICreate2Factory

Git Source

Author: Matter Labs

The contract that can be used for deterministic contract deployment.

Note: security-contact: security@matterlabs.dev

Functions

create2

Function that calls the create2 method of the ContractDeployer contract.

This function accepts the same parameters as the create2 function of the ContractDeployer system contract, so that we could efficiently relay the calldata.

function create2(bytes32, bytes32, bytes calldata)
  external
  payable
  returns (address);

create2Account

Function that calls the create2Account method of the ContractDeployer contract.

This function accepts the same parameters as the create2Account function of the ContractDeployer system contract, so that we could efficiently relay the calldata.

function create2Account(
  bytes32,
  bytes32,
  bytes calldata,
  IContractDeployer.AccountAbstractionVersion
) external payable returns (address);

IImmutableSimulator

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

getImmutable

function getImmutable(address _dest, uint256 _index)
  external
  view
  returns (bytes32);

setImmutables

function setImmutables(address _dest, ImmutableData[] calldata _immutables)
  external;

IKnownCodesStorage

Git Source

Author: Matter Labs

The interface for the KnownCodesStorage contract, which is responsible for storing the hashes of the bytecodes that have been published to the network.

Note: security-contact: security@matterlabs.dev

Functions

markFactoryDeps

function markFactoryDeps(bool _shouldSendToL1, bytes32[] calldata _hashes)
  external;

markBytecodeAsPublished

function markBytecodeAsPublished(bytes32 _bytecodeHash) external;

getMarker

function getMarker(bytes32 _hash) external view returns (uint256);

publishEVMBytecode

function publishEVMBytecode(uint256 evmBytecodeLen, bytes calldata bytecode)
  external
  payable
  returns (bytes32);

Events

MarkedAsKnown

event MarkedAsKnown(
  bytes32 indexed bytecodeHash, bool indexed sendBytecodeToL1
);

IL1Messenger

Git Source

Author: Matter Labs

The interface of the L1 Messenger contract, responsible for sending messages to L1.

Note: security-contact: security@matterlabs.dev

Functions

sendToL1

function sendToL1(bytes calldata _message) external returns (bytes32);

sendL2ToL1Log

function sendL2ToL1Log(bool _isService, bytes32 _key, bytes32 _value)
  external
  returns (uint256 logIdInMerkleTree);

requestBytecodeL1Publication

function requestBytecodeL1Publication(bytes32 _bytecodeHash) external;

Events

L1MessageSent

event L1MessageSent(
  address indexed _sender, bytes32 indexed _hash, bytes _message
);

L2ToL1LogSent

event L2ToL1LogSent(L2ToL1Log _l2log);

BytecodeL1PublicationRequested

event BytecodeL1PublicationRequested(bytes32 _bytecodeHash);

Constants

Git Source

L2_TO_L1_LOG_SERIALIZE_SIZE

Bytes in raw L2 to L1 log

Equal to the bytes size of the tuple - (uint8 ShardId, bool isService, uint16 txNumberInBlock, address sender, bytes32 key, bytes32 value)

uint256 constant L2_TO_L1_LOG_SERIALIZE_SIZE = 88;

L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH

The value of default leaf hash for L2 to L1 logs Merkle tree

An incomplete fixed-size tree is filled with this value to be a full binary tree

Actually equal to the keccak256(new bytes(L2_TO_L1_LOG_SERIALIZE_SIZE))

bytes32 constant L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH =
  0x72abee45b59e344af8a6e520241c4744aff26ed411f4c4b00f8af09adada43ba;

STATE_DIFF_COMPRESSION_VERSION_NUMBER

The current version of state diff compression being used.

uint256 constant STATE_DIFF_COMPRESSION_VERSION_NUMBER = 1;

IL2DAValidator

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

validatePubdata

function validatePubdata(
  bytes32 _chainedLogsHash,
  bytes32 _logsRootHash,
  bytes32 _chainedMessagesHash,
  bytes32 _chainedBytecodesHash,
  bytes calldata _totalL2ToL1PubdataAndStateDiffs
) external returns (bytes32 outputHash);

IL2GenesisUpgrade

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

genesisUpgrade

function genesisUpgrade(
  uint256 _chainId,
  address _ctmDeployer,
  bytes calldata _fixedForceDeploymentsData,
  bytes calldata _additionalForceDeploymentsData
) external payable;

Events

UpgradeComplete

event UpgradeComplete(uint256 _chainId);

IL2SharedBridgeLegacy

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

l2TokenBeacon

function l2TokenBeacon() external view returns (UpgradeableBeacon);

withdraw

function withdraw(address _l1Receiver, address _l2Token, uint256 _amount)
  external;

l1TokenAddress

function l1TokenAddress(address _l2Token) external view returns (address);

l2TokenAddress

function l2TokenAddress(address _l1Token) external view returns (address);

l1Bridge

function l1Bridge() external view returns (address);

l1SharedBridge

function l1SharedBridge() external view returns (address);

deployBeaconProxy

function deployBeaconProxy(bytes32 _salt) external returns (address);

sendMessageToL1

function sendMessageToL1(bytes calldata _message) external;

Events

FinalizeDeposit

event FinalizeDeposit(
  address indexed l1Sender,
  address indexed l2Receiver,
  address indexed l2Token,
  uint256 amount
);

IL2StandardToken

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

bridgeMint

function bridgeMint(address _account, uint256 _amount) external;

bridgeBurn

function bridgeBurn(address _account, uint256 _amount) external;

l1Address

function l1Address() external view returns (address);

l2Bridge

function l2Bridge() external view returns (address);

Events

BridgeMint

event BridgeMint(address indexed _account, uint256 _amount);

BridgeBurn

event BridgeBurn(address indexed _account, uint256 _amount);

IL2WrappedBaseToken

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

initializeV3

Initializes a contract token for later use. Expected to be used in the proxy.

This function is used to integrate the previously deployed WETH token with the bridge.

Sets up name/symbol/decimals getters.

function initializeV3(
  string calldata name_,
  string calldata symbol_,
  address _l2Bridge,
  address _l1Address,
  bytes32 _baseTokenAssetId
) external;

Parameters

NameTypeDescription
name_stringThe name of the token.
symbol_stringThe symbol of the token.
_l2BridgeaddressAddress of the L2 bridge
_l1AddressaddressAddress of the L1 token that can be deposited to mint this L2 WETH. Note: The decimals are hardcoded to 18, the same as on Ether.
_baseTokenAssetIdbytes32

IMailbox

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

finalizeEthWithdrawal

function finalizeEthWithdrawal(
  uint256 _l2BatchNumber,
  uint256 _l2MessageIndex,
  uint16 _l2TxNumberInBlock,
  bytes calldata _message,
  bytes32[] calldata _merkleProof
) external;

IMessageRoot

Git Source

Author: Matter Labs

MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot.

Note: security-contact: security@matterlabs.dev

Functions

getAggregatedRoot

The aggregated root of the batches from different chains.

function getAggregatedRoot() external view returns (bytes32 aggregatedRoot);

Returns

NameTypeDescription
aggregatedRootbytes32of the batches from different chains.

INonceHolder

Git Source

Author: Matter Labs

Interface of the nonce holder contract -- a contract used by the system to ensure that there is always a unique identifier for a transaction with a particular account (we call it nonce). In other words, the pair of (address, nonce) should always be unique.

Custom accounts should use methods of this contract to store nonces or other possible unique identifiers for the transaction.

Note: security-contact: security@matterlabs.dev

Functions

getMinNonce

Returns the current minimal nonce for account.

function getMinNonce(address _address) external view returns (uint256);

Parameters

NameTypeDescription
_addressaddressThe account to return the minimal nonce for

Returns

NameTypeDescription
<none>uint256The current minimal nonce for this account.

getKeyedNonce

Returns the current keyed nonce for account given its nonce key.

function getKeyedNonce(address _address, uint192 _key)
  external
  view
  returns (uint256);

Parameters

NameTypeDescription
_addressaddressThe account to return the nonce for.
_keyuint192The key of the nonce to return.

Returns

NameTypeDescription
<none>uint256The current keyed nonce with the given key for this account. Returns the full nonce (including the provided key), not just the nonce value.

getRawNonce

Returns the raw version of the current minimal nonce

It is equal to minNonce + 2^128 * deployment nonce.

function getRawNonce(address _address) external view returns (uint256);

Parameters

NameTypeDescription
_addressaddressThe account to return the raw nonce for

Returns

NameTypeDescription
<none>uint256The raw nonce for this account.

increaseMinNonce

Increases the minimal nonce for the msg.sender and returns the previous one.

function increaseMinNonce(uint256 _value) external returns (uint256);

Parameters

NameTypeDescription
_valueuint256The number by which to increase the minimal nonce for msg.sender.

Returns

NameTypeDescription
<none>uint256oldMinNonce The value of the minimal nonce for msg.sender before the increase.

setValueUnderNonce

Sets the nonce value key as used.

function setValueUnderNonce(uint256 _key, uint256 _value) external;

getValueUnderNonce

Gets the value stored inside a custom nonce.

function getValueUnderNonce(uint256 _key) external view returns (uint256);

incrementMinNonceIfEquals

A convenience method to increment the minimal nonce if it is equal to the _expectedNonce.

This function only increments minNonce for nonces with nonceKey == 0. AAs that try to use this method with a keyed nonce will revert. For keyed nonces, incrementMinNonceIfEqualsKeyed should be used. This is to prevent DefaultAccount and other deployed AAs from unintentionally allowing keyed nonces to be used.

function incrementMinNonceIfEquals(uint256 _expectedNonce) external;

Parameters

NameTypeDescription
_expectedNonceuint256The expected minimal nonce for the account.

incrementMinNonceIfEqualsKeyed

A convenience method to increment the minimal nonce if it is equal to the _expectedNonce. This is a keyed counterpart to incrementMinNonceIfEquals.

Reverts for nonces with nonceKey == 0.

function incrementMinNonceIfEqualsKeyed(uint256 _expectedNonce) external;

Parameters

NameTypeDescription
_expectedNonceuint256The expected minimal nonce for the account.

getDeploymentNonce

Returns the deployment nonce for the accounts used for CREATE opcode.

function getDeploymentNonce(address _address) external view returns (uint256);

Parameters

NameTypeDescription
_addressaddressThe address to return the deploy nonce of.

Returns

NameTypeDescription
<none>uint256deploymentNonce The deployment nonce of the account.

incrementDeploymentNonce

Increments the deployment nonce for the account and returns the previous one.

function incrementDeploymentNonce(address _address) external returns (uint256);

Parameters

NameTypeDescription
_addressaddressThe address of the account which to return the deploy nonce for.

Returns

NameTypeDescription
<none>uint256prevDeploymentNonce The deployment nonce at the time this function is called.

validateNonceUsage

Checks and reverts based on whether the nonce is used (or not used).

This method should be used by the bootloader.

function validateNonceUsage(address _address, uint256 _key, bool _shouldBeUsed)
  external
  view;

Parameters

NameTypeDescription
_addressaddressThe address the nonce of which is being checked.
_keyuint256The nonce value which is tested.
_shouldBeUsedboolThe flag for the method. If true, the method checks that whether this nonce is marked as used and reverts if this is not the case. If false, this method will check that the nonce has not been used yet, and revert otherwise.

isNonceUsed

Returns whether a nonce has been used for an account.

function isNonceUsed(address _address, uint256 _nonce)
  external
  view
  returns (bool);

Parameters

NameTypeDescription
_addressaddressThe address the nonce of which is being checked.
_nonceuint256The nonce value which is checked.

Returns

NameTypeDescription
<none>booltrue if the nonce has been used, false otherwise.

Events

ValueSetUnderNonce

event ValueSetUnderNonce(
  address indexed accountAddress, uint256 indexed key, uint256 value
);

IPaymaster

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

validateAndPayForPaymasterTransaction

Called by the bootloader to verify that the paymaster agrees to pay for the fee for the transaction. This transaction should also send the necessary amount of funds onto the bootloader address.

The developer should strive to preserve as many steps as possible both for valid and invalid transactions as this very method is also used during the gas fee estimation (without some of the necessary data, e.g. signature).

function validateAndPayForPaymasterTransaction(
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  Transaction calldata _transaction
) external payable returns (bytes4 magic, bytes memory context);

Parameters

NameTypeDescription
_txHashbytes32The hash of the transaction
_suggestedSignedHashbytes32The hash of the transaction that is signed by an EOA
_transactionTransactionThe transaction itself.

Returns

NameTypeDescription
magicbytes4The value that should be equal to the signature of the validateAndPayForPaymasterTransaction if the paymaster agrees to pay for the transaction.
contextbytesThe "context" of the transaction: an array of bytes of length at most 1024 bytes, which will be passed to the postTransaction method of the account.

postTransaction

Called by the bootloader after the execution of the transaction. Please note that there is no guarantee that this method will be called at all. Unlike the original EIP4337, this method won't be called if the transaction execution results in out-of-gas.

The exact amount refunded depends on the gas spent by the "postOp" itself and so the developers should take that into account.

function postTransaction(
  bytes calldata _context,
  Transaction calldata _transaction,
  bytes32 _txHash,
  bytes32 _suggestedSignedHash,
  ExecutionResult _txResult,
  uint256 _maxRefundedGas
) external payable;

Parameters

NameTypeDescription
_contextbytes
_transactionTransaction
_txHashbytes32
_suggestedSignedHashbytes32
_txResultExecutionResult
_maxRefundedGasuint256

Constants

Git Source

PAYMASTER_VALIDATION_SUCCESS_MAGIC

bytes4 constant PAYMASTER_VALIDATION_SUCCESS_MAGIC =
  IPaymaster.validateAndPayForPaymasterTransaction.selector;

IPaymasterFlow

Git Source

Author: Matter Labs

This is NOT an interface to be implemented by contracts. It is just used for encoding.

The interface that is used for encoding/decoding of different types of paymaster flows.

Note: security-contact: security@matterlabs.dev

Functions

general

function general(bytes calldata input) external;

approvalBased

function approvalBased(
  address _token,
  uint256 _minAllowance,
  bytes calldata _innerInput
) external;

IPubdataChunkPublisher

Git Source

Author: Matter Labs

Interface for contract responsible chunking pubdata into the appropriate size for EIP-4844 blobs.

Note: security-contact: security@matterlabs.dev

Functions

chunkPubdataToBlobs

Chunks pubdata into pieces that can fit into blobs.

Note: This is an early implementation, in the future we plan to support up to 16 blobs per l1 batch.

function chunkPubdataToBlobs(bytes calldata _pubdata)
  external
  pure
  returns (bytes32[] memory blobLinearHashes);

Parameters

NameTypeDescription
_pubdatabytesThe total l2 to l1 pubdata that will be sent via L1 blobs.

ISystemContext

Git Source

Author: Matter Labs

Contract that stores some of the context variables, that may be either block-scoped, tx-scoped or system-wide.

Note: security-contact: security@matterlabs.dev

Functions

chainId

function chainId() external view returns (uint256);

origin

function origin() external view returns (address);

gasPrice

function gasPrice() external view returns (uint256);

blockGasLimit

function blockGasLimit() external view returns (uint256);

coinbase

function coinbase() external view returns (address);

difficulty

function difficulty() external view returns (uint256);

baseFee

function baseFee() external view returns (uint256);

txNumberInBlock

function txNumberInBlock() external view returns (uint16);

getBlockHashEVM

function getBlockHashEVM(uint256 _block) external view returns (bytes32);

getBatchHash

function getBatchHash(uint256 _batchNumber)
  external
  view
  returns (bytes32 hash);

getBlockNumber

function getBlockNumber() external view returns (uint128);

getBlockTimestamp

function getBlockTimestamp() external view returns (uint128);

getBatchNumberAndTimestamp

function getBatchNumberAndTimestamp()
  external
  view
  returns (uint128 blockNumber, uint128 blockTimestamp);

getL2BlockNumberAndTimestamp

function getL2BlockNumberAndTimestamp()
  external
  view
  returns (uint128 blockNumber, uint128 blockTimestamp);

gasPerPubdataByte

function gasPerPubdataByte() external view returns (uint256 gasPerPubdataByte);

getCurrentPubdataSpent

function getCurrentPubdataSpent()
  external
  view
  returns (uint256 currentPubdataSpent);

setChainId

function setChainId(uint256 _newChainId) external;

Structs

BlockInfo

struct BlockInfo {
  uint128 timestamp;
  uint128 number;
}

VirtualBlockUpgradeInfo

A structure representing the timeline for the upgrade from the batch numbers to the L2 block numbers.

It will be used for the L1 batch -> L2 block migration in Q3 2023 only.

struct VirtualBlockUpgradeInfo {
  uint128 virtualBlockStartBatch;
  uint128 virtualBlockFinishL2Block;
}

ISystemContextDeprecated

Git Source

Author: Matter Labs

The interface with deprecated functions of the SystemContext contract. It is aimed for backward compatibility.

Note: security-contact: security@matterlabs.dev

Functions

currentBlockInfo

function currentBlockInfo() external view returns (uint256);

getBlockNumberAndTimestamp

function getBlockNumberAndTimestamp()
  external
  view
  returns (uint256 blockNumber, uint256 blockTimestamp);

blockHash

function blockHash(uint256 _blockNumber) external view returns (bytes32 hash);

IEvmHashesStorage

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.de

Functions

storeEvmCodeHash

function storeEvmCodeHash(
  bytes32 versionedBytecodeHash,
  bytes32 evmBytecodeHash
) external;

getEvmCodeHash

function getEvmCodeHash(bytes32 versionedBytecodeHash)
  external
  view
  returns (bytes32);

Errors

AddressHasNoCode

Git Source

error AddressHasNoCode(address);

CallerMustBeBootloader

Git Source

error CallerMustBeBootloader();

CallerMustBeEvmContract

Git Source

error CallerMustBeEvmContract();

CallerMustBeSystemContract

Git Source

error CallerMustBeSystemContract();

CompressionValueAddError

Git Source

error CompressionValueAddError(uint256 expected, uint256 actual);

CompressionValueTransformError

Git Source

error CompressionValueTransformError(uint256 expected, uint256 actual);

CompressionValueSubError

Git Source

error CompressionValueSubError(uint256 expected, uint256 actual);

CompressorInitialWritesProcessedNotEqual

Git Source

error CompressorInitialWritesProcessedNotEqual(uint256 expected, uint256 actual);

CompressorEnumIndexNotEqual

Git Source

error CompressorEnumIndexNotEqual(uint256 expected, uint256 actual);

DerivedKeyNotEqualToCompressedValue

Git Source

error DerivedKeyNotEqualToCompressedValue(bytes32 expected, bytes32 provided);

DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo

Git Source

error DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo();

EmptyBytes32

Git Source

error EmptyBytes32();

EncodedAndRealBytecodeChunkNotEqual

Git Source

error EncodedAndRealBytecodeChunkNotEqual(uint64 expected, uint64 provided);

EncodedLengthNotFourTimesSmallerThanOriginal

Git Source

error EncodedLengthNotFourTimesSmallerThanOriginal();

EVMBytecodeHash

Git Source

error EVMBytecodeHash();

EVMBytecodeHashUnknown

Git Source

error EVMBytecodeHashUnknown();

EVMEmulationNotSupported

Git Source

error EVMEmulationNotSupported();

FailedToChargeGas

Git Source

error FailedToChargeGas();

FailedToPayOperator

Git Source

error FailedToPayOperator();

HashIsNonZero

Git Source

error HashIsNonZero(bytes32);

HashMismatch

Git Source

error HashMismatch(bytes32 expected, bytes32 actual);

IndexOutOfBounds

Git Source

error IndexOutOfBounds();

IndexSizeError

Git Source

error IndexSizeError();

InsufficientFunds

Git Source

error InsufficientFunds(uint256 required, uint256 actual);

InvalidCall

Git Source

error InvalidCall();

InvalidCodeHash

Git Source

error InvalidCodeHash(CodeHashReason);

InvalidInput

Git Source

error InvalidInput();

InvalidNonceOrderingChange

Git Source

error InvalidNonceOrderingChange();

InvalidSig

Git Source

error InvalidSig(SigField, uint256);

Keccak256InvalidReturnData

Git Source

error Keccak256InvalidReturnData();

MalformedBytecode

Git Source

error MalformedBytecode(BytecodeError);

NonceAlreadyUsed

Git Source

error NonceAlreadyUsed(address account, uint256 nonce);

NonceIncreaseError

Git Source

error NonceIncreaseError(uint256 min, uint256 max, uint256 proposed);

NonceJumpError

NonceNotUsed

Git Source

error NonceNotUsed(address account, uint256 nonce);

NonEmptyAccount

Git Source

error NonEmptyAccount();

NonEmptyMsgValue

Git Source

error NonEmptyMsgValue();

NotAllowedToDeployInKernelSpace

Git Source

error NotAllowedToDeployInKernelSpace();

Overflow

Git Source

error Overflow();

ReconstructionMismatch

Git Source

error ReconstructionMismatch(PubdataField, bytes32 expected, bytes32 actual);

ShaInvalidReturnData

Git Source

error ShaInvalidReturnData();

StateDiffLengthMismatch

Git Source

error StateDiffLengthMismatch();

SystemCallFlagRequired

Git Source

error SystemCallFlagRequired();

TooMuchPubdata

Git Source

error TooMuchPubdata(uint256 limit, uint256 supplied);

Unauthorized

Git Source

error Unauthorized(address);

UnknownCodeHash

Git Source

error UnknownCodeHash(bytes32);

UnsupportedOperation

Git Source

error UnsupportedOperation();

UnsupportedPaymasterFlow

Git Source

error UnsupportedPaymasterFlow();

UnsupportedTxType

Git Source

error UnsupportedTxType(uint256);

ValueMismatch

Git Source

error ValueMismatch(uint256 expected, uint256 actual);

ZeroNonceError

Git Source

error ZeroNonceError();

SloadContractBytecodeUnknown

Git Source

error SloadContractBytecodeUnknown();

PreviousBytecodeUnknown

Git Source

error PreviousBytecodeUnknown();

InvalidChainId

Git Source

error InvalidChainId();

UpgradeTransactionMustBeFirst

Git Source

error UpgradeTransactionMustBeFirst();

L2BlockNumberZero

Git Source

error L2BlockNumberZero();

PreviousL2BlockHashIsIncorrect

Git Source

error PreviousL2BlockHashIsIncorrect(
  bytes32 correctPrevBlockHash, bytes32 expectedPrevL2BlockHash
);

CannotInitializeFirstVirtualBlock

Git Source

error CannotInitializeFirstVirtualBlock();

L2BlockAndBatchTimestampMismatch

Git Source

error L2BlockAndBatchTimestampMismatch(
  uint128 l2BlockTimestamp, uint128 currentBatchTimestamp
);

InconsistentNewBatchTimestamp

Git Source

error InconsistentNewBatchTimestamp(
  uint128 newBatchTimestamp, uint128 lastL2BlockTimestamp
);

NoVirtualBlocks

Git Source

error NoVirtualBlocks();

CannotReuseL2BlockNumberFromPreviousBatch

Git Source

error CannotReuseL2BlockNumberFromPreviousBatch();

IncorrectSameL2BlockTimestamp

Git Source

error IncorrectSameL2BlockTimestamp(
  uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp
);

IncorrectSameL2BlockPrevBlockHash

Git Source

error IncorrectSameL2BlockPrevBlockHash(
  bytes32 expectedPrevL2BlockHash, bytes32 latestL2blockHash
);

IncorrectVirtualBlockInsideMiniblock

Git Source

error IncorrectVirtualBlockInsideMiniblock();

IncorrectL2BlockHash

Git Source

error IncorrectL2BlockHash(
  bytes32 expectedPrevL2BlockHash, bytes32 pendingL2BlockHash
);

NonMonotonicL2BlockTimestamp

Git Source

error NonMonotonicL2BlockTimestamp(
  uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp
);

CurrentBatchNumberMustBeGreaterThanZero

Git Source

error CurrentBatchNumberMustBeGreaterThanZero();

TimestampsShouldBeIncremental

Git Source

error TimestampsShouldBeIncremental(
  uint128 newTimestamp, uint128 previousBatchTimestamp
);

ProvidedBatchNumberIsNotCorrect

Git Source

error ProvidedBatchNumberIsNotCorrect(
  uint128 previousBatchNumber, uint128 _expectedNewNumber
);

CodeOracleCallFailed

Git Source

error CodeOracleCallFailed();

ReturnedBytecodeDoesNotMatchExpectedHash

Git Source

error ReturnedBytecodeDoesNotMatchExpectedHash(
  bytes32 returnedBytecode, bytes32 expectedBytecodeHash
);

SecondCallShouldHaveCostLessGas

Git Source

error SecondCallShouldHaveCostLessGas(
  uint256 secondCallCost, uint256 firstCallCost
);

ThirdCallShouldHaveSameGasCostAsSecondCall

Git Source

error ThirdCallShouldHaveSameGasCostAsSecondCall(
  uint256 thirdCallCost, uint256 secondCallCost
);

CallToKeccakShouldHaveSucceeded

Git Source

error CallToKeccakShouldHaveSucceeded();

KeccakReturnDataSizeShouldBe32Bytes

Git Source

error KeccakReturnDataSizeShouldBe32Bytes(uint256 returnDataSize);

KeccakResultIsNotCorrect

Git Source

error KeccakResultIsNotCorrect(bytes32 result);

KeccakShouldStartWorkingAgain

Git Source

error KeccakShouldStartWorkingAgain();

KeccakMismatchBetweenNumberOfInputsAndOutputs

Git Source

error KeccakMismatchBetweenNumberOfInputsAndOutputs(
  uint256 testInputsLength, uint256 expectedOutputsLength
);

KeccakHashWasNotCalculatedCorrectly

Git Source

error KeccakHashWasNotCalculatedCorrectly(
  bytes32 result, bytes32 expectedOutputs
);

TransactionFailed

Git Source

error TransactionFailed();

NotEnoughGas

Git Source

error NotEnoughGas();

TooMuchGas

Git Source

error TooMuchGas();

InvalidNewL2BlockNumber

Git Source

error InvalidNewL2BlockNumber(uint256 l2BlockNumber);

CodeHashReason

Git Source

enum CodeHashReason {
  NotContractOnConstructor,
  NotConstructedContract
}

SigField

Git Source

enum SigField {
  Length,
  V,
  S
}

PubdataField

Git Source

enum PubdataField {
  NumberOfLogs,
  LogsHash,
  MsgHash,
  Bytecode,
  InputDAFunctionSig,
  InputLogsHash,
  InputLogsRootHash,
  InputMsgsHash,
  InputBytecodeHash,
  Offset,
  Length
}

BytecodeError

Git Source

enum BytecodeError {
  Version,
  NumberOfWords,
  Length,
  WordsMustBeOdd,
  DictionaryLength,
  EvmBytecodeLength,
  EvmBytecodeLengthTooBig
}

Constants

Git Source

SYSTEM_CONTRACTS_OFFSET

All the system contracts introduced by ZKsync have their addresses started from 2^15 in order to avoid collision with Ethereum precompiles.

uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000;

REAL_SYSTEM_CONTRACTS_OFFSET

Unlike the value above, it is not overridden for the purpose of testing and is identical to the constant value actually used as the system contracts offset on mainnet.

uint160 constant REAL_SYSTEM_CONTRACTS_OFFSET = 0x8000;

MAX_SYSTEM_CONTRACT_ADDRESS

All the system contracts must be located in the kernel space, i.e. their addresses must be below 2^16.

uint160 constant MAX_SYSTEM_CONTRACT_ADDRESS = 0xffff;

USER_CONTRACTS_OFFSET

The offset from which the built-in, but user space contracts are located.

uint160 constant USER_CONTRACTS_OFFSET = MAX_SYSTEM_CONTRACT_ADDRESS + 1;

ECRECOVER_SYSTEM_CONTRACT

address constant ECRECOVER_SYSTEM_CONTRACT = address(0x01);

SHA256_SYSTEM_CONTRACT

address constant SHA256_SYSTEM_CONTRACT = address(0x02);

IDENTITY_SYSTEM_CONTRACT

address constant IDENTITY_SYSTEM_CONTRACT = address(0x04);

MODEXP_SYSTEM_CONTRACT

address constant MODEXP_SYSTEM_CONTRACT = address(0x05);

ECADD_SYSTEM_CONTRACT

address constant ECADD_SYSTEM_CONTRACT = address(0x06);

ECMUL_SYSTEM_CONTRACT

address constant ECMUL_SYSTEM_CONTRACT = address(0x07);

ECPAIRING_SYSTEM_CONTRACT

address constant ECPAIRING_SYSTEM_CONTRACT = address(0x08);

COMPUTATIONAL_PRICE_FOR_PUBDATA

*The number of gas that need to be spent for a single byte of pubdata regardless of the pubdata price. This variable is used to ensure the following:

  • That the long-term storage of the operator is compensated properly.
  • That it is not possible that the pubdata counter grows too high without spending proportional amount of computation.*
uint256 constant COMPUTATIONAL_PRICE_FOR_PUBDATA = 80;

CURRENT_MAX_PRECOMPILE_ADDRESS

*The maximal possible address of an L1-like precompie. These precompiles maintain the following properties:

  • Their extcodehash is EMPTY_STRING_KECCAK
  • Their extcodesize is 0 despite having a bytecode formally deployed there.*
uint256 constant CURRENT_MAX_PRECOMPILE_ADDRESS = 0xff;

BOOTLOADER_FORMAL_ADDRESS

address payable constant BOOTLOADER_FORMAL_ADDRESS =
  payable(address(SYSTEM_CONTRACTS_OFFSET + 0x01));

ACCOUNT_CODE_STORAGE_SYSTEM_CONTRACT

IAccountCodeStorage constant ACCOUNT_CODE_STORAGE_SYSTEM_CONTRACT =
  IAccountCodeStorage(address(SYSTEM_CONTRACTS_OFFSET + 0x02));

NONCE_HOLDER_SYSTEM_CONTRACT

INonceHolder constant NONCE_HOLDER_SYSTEM_CONTRACT =
  INonceHolder(address(SYSTEM_CONTRACTS_OFFSET + 0x03));

KNOWN_CODE_STORAGE_CONTRACT

IKnownCodesStorage constant KNOWN_CODE_STORAGE_CONTRACT =
  IKnownCodesStorage(address(SYSTEM_CONTRACTS_OFFSET + 0x04));

IMMUTABLE_SIMULATOR_SYSTEM_CONTRACT

IImmutableSimulator constant IMMUTABLE_SIMULATOR_SYSTEM_CONTRACT =
  IImmutableSimulator(address(SYSTEM_CONTRACTS_OFFSET + 0x05));

DEPLOYER_SYSTEM_CONTRACT

IContractDeployer constant DEPLOYER_SYSTEM_CONTRACT =
  IContractDeployer(address(SYSTEM_CONTRACTS_OFFSET + 0x06));

REAL_DEPLOYER_SYSTEM_CONTRACT

IContractDeployer constant REAL_DEPLOYER_SYSTEM_CONTRACT =
  IContractDeployer(address(REAL_SYSTEM_CONTRACTS_OFFSET + 0x06));

FORCE_DEPLOYER

address constant FORCE_DEPLOYER = address(SYSTEM_CONTRACTS_OFFSET + 0x07);

L1_MESSENGER_CONTRACT

IL1Messenger constant L1_MESSENGER_CONTRACT =
  IL1Messenger(address(SYSTEM_CONTRACTS_OFFSET + 0x08));

MSG_VALUE_SYSTEM_CONTRACT

address constant MSG_VALUE_SYSTEM_CONTRACT =
  address(SYSTEM_CONTRACTS_OFFSET + 0x09);

BASE_TOKEN_SYSTEM_CONTRACT

IBaseToken constant BASE_TOKEN_SYSTEM_CONTRACT =
  IBaseToken(address(SYSTEM_CONTRACTS_OFFSET + 0x0a));

REAL_BASE_TOKEN_SYSTEM_CONTRACT

IBaseToken constant REAL_BASE_TOKEN_SYSTEM_CONTRACT =
  IBaseToken(address(REAL_SYSTEM_CONTRACTS_OFFSET + 0x0a));

SYSTEM_CONTEXT_CONTRACT

ISystemContext constant SYSTEM_CONTEXT_CONTRACT =
  ISystemContext(payable(address(SYSTEM_CONTRACTS_OFFSET + 0x0b)));

REAL_SYSTEM_CONTEXT_CONTRACT

ISystemContext constant REAL_SYSTEM_CONTEXT_CONTRACT =
  ISystemContext(payable(address(REAL_SYSTEM_CONTRACTS_OFFSET + 0x0b)));

BOOTLOADER_UTILITIES

IBootloaderUtilities constant BOOTLOADER_UTILITIES =
  IBootloaderUtilities(address(SYSTEM_CONTRACTS_OFFSET + 0x0c));

EVENT_WRITER_CONTRACT

address constant EVENT_WRITER_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x0d);

COMPRESSOR_CONTRACT

ICompressor constant COMPRESSOR_CONTRACT =
  ICompressor(address(SYSTEM_CONTRACTS_OFFSET + 0x0e));

COMPLEX_UPGRADER_CONTRACT

IComplexUpgrader constant COMPLEX_UPGRADER_CONTRACT =
  IComplexUpgrader(address(SYSTEM_CONTRACTS_OFFSET + 0x0f));

KECCAK256_SYSTEM_CONTRACT

address constant KECCAK256_SYSTEM_CONTRACT = address(0x8010);

PUBDATA_CHUNK_PUBLISHER

IPubdataChunkPublisher constant PUBDATA_CHUNK_PUBLISHER =
  IPubdataChunkPublisher(address(SYSTEM_CONTRACTS_OFFSET + 0x11));

CODE_ORACLE_SYSTEM_CONTRACT

address constant CODE_ORACLE_SYSTEM_CONTRACT =
  address(SYSTEM_CONTRACTS_OFFSET + 0x12);

EVM_GAS_MANAGER

address constant EVM_GAS_MANAGER = address(SYSTEM_CONTRACTS_OFFSET + 0x13);

EVM_PREDEPLOYS_MANAGER

address constant EVM_PREDEPLOYS_MANAGER =
  address(SYSTEM_CONTRACTS_OFFSET + 0x14);

EVM_HASHES_STORAGE

IEvmHashesStorage constant EVM_HASHES_STORAGE =
  IEvmHashesStorage(address(SYSTEM_CONTRACTS_OFFSET + 0x15));

L2_CREATE2_FACTORY

ICreate2Factory constant L2_CREATE2_FACTORY =
  ICreate2Factory(address(USER_CONTRACTS_OFFSET));

L2_ASSET_ROUTER

address constant L2_ASSET_ROUTER = address(USER_CONTRACTS_OFFSET + 0x03);

L2_BRIDGE_HUB

IBridgehub constant L2_BRIDGE_HUB =
  IBridgehub(address(USER_CONTRACTS_OFFSET + 0x02));

L2_NATIVE_TOKEN_VAULT_ADDR

address constant L2_NATIVE_TOKEN_VAULT_ADDR =
  address(USER_CONTRACTS_OFFSET + 0x04);

L2_MESSAGE_ROOT

IMessageRoot constant L2_MESSAGE_ROOT =
  IMessageRoot(address(USER_CONTRACTS_OFFSET + 0x05));

SLOAD_CONTRACT_ADDRESS

address constant SLOAD_CONTRACT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x06);

WRAPPED_BASE_TOKEN_IMPL_ADDRESS

address constant WRAPPED_BASE_TOKEN_IMPL_ADDRESS =
  address(USER_CONTRACTS_OFFSET + 0x07);

MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT

If the bitwise AND of the extraAbi[2] param when calling the MSG_VALUE_SIMULATOR is non-zero, the call will be assumed to be a system one.

uint256 constant MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT = 1;

MAX_MSG_VALUE

The maximal msg.value that context can have

uint256 constant MAX_MSG_VALUE = type(uint128).max;

CREATE2_PREFIX

Prefix used during derivation of account addresses using CREATE2

keccak256("zksyncCreate2")

bytes32 constant CREATE2_PREFIX =
  0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494;

CREATE_PREFIX

Prefix used during derivation of account addresses using CREATE

keccak256("zksyncCreate")

bytes32 constant CREATE_PREFIX =
  0x63bae3a9951d38e8a3fbb7b70909afc1200610fc5bc55ade242f815974674f23;

CREATE2_EVM_PREFIX

Prefix used during derivation of account addresses using CREATE2 within the EVM

bytes1 constant CREATE2_EVM_PREFIX = 0xff;

STATE_DIFF_ENTRY_SIZE

Each state diff consists of 156 bytes of actual data and 116 bytes of unused padding, needed for circuit efficiency.

uint256 constant STATE_DIFF_ENTRY_SIZE = 272;

L2_TO_L1_LOGS_MERKLE_TREE_LEAVES

The number of leaves in the L2->L1 log Merkle tree. While formally a tree of any length is acceptable, the node supports only a constant length of 16384 leaves.

uint256 constant L2_TO_L1_LOGS_MERKLE_TREE_LEAVES = 16_384;

DERIVED_KEY_LENGTH

The length of the derived key in bytes inside compressed state diffs.

uint256 constant DERIVED_KEY_LENGTH = 32;

ENUM_INDEX_LENGTH

The length of the enum index in bytes inside compressed state diffs.

uint256 constant ENUM_INDEX_LENGTH = 8;

VALUE_LENGTH

The length of value in bytes inside compressed state diffs.

uint256 constant VALUE_LENGTH = 32;

COMPRESSED_INITIAL_WRITE_SIZE

The length of the compressed initial storage write in bytes.

uint256 constant COMPRESSED_INITIAL_WRITE_SIZE =
  DERIVED_KEY_LENGTH + VALUE_LENGTH;

COMPRESSED_REPEATED_WRITE_SIZE

The length of the compressed repeated storage write in bytes.

uint256 constant COMPRESSED_REPEATED_WRITE_SIZE =
  ENUM_INDEX_LENGTH + VALUE_LENGTH;

INITIAL_WRITE_STARTING_POSITION

The position from which the initial writes start in the compressed state diffs.

uint256 constant INITIAL_WRITE_STARTING_POSITION = 4;

STATE_DIFF_DERIVED_KEY_OFFSET

Each storage diffs consists of the following elements: [20bytes address][32bytes key][32bytes derived key][8bytes enum index][32bytes initial value][32bytes final value]

The offset of the derived key in a storage diff.

uint256 constant STATE_DIFF_DERIVED_KEY_OFFSET = 52;

STATE_DIFF_ENUM_INDEX_OFFSET

The offset of the enum index in a storage diff.

uint256 constant STATE_DIFF_ENUM_INDEX_OFFSET = 84;

STATE_DIFF_FINAL_VALUE_OFFSET

The offset of the final value in a storage diff.

uint256 constant STATE_DIFF_FINAL_VALUE_OFFSET = 124;

BLOB_SIZE_BYTES

Total number of bytes in a blob. Blob = 4096 field elements * 31 bytes per field element

EIP-4844 defines it as 131_072 but we use 4096 * 31 within our circuits to always fit within a field element

Our circuits will prove that a EIP-4844 blob and our internal blob are the same.

uint256 constant BLOB_SIZE_BYTES = 126_976;

MAX_NUMBER_OF_BLOBS

Max number of blobs currently supported

uint256 constant MAX_NUMBER_OF_BLOBS = 6;

ERA_VM_BYTECODE_FLAG

Marker of EraVM bytecode

uint8 constant ERA_VM_BYTECODE_FLAG = 1;

EVM_BYTECODE_FLAG

Marker of EVM bytecode

uint8 constant EVM_BYTECODE_FLAG = 2;

SERVICE_CALL_PSEUDO_CALLER

address constant SERVICE_CALL_PSEUDO_CALLER =
  0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;

SystemLogKey

Git Source

enum SystemLogKey {
  L2_TO_L1_LOGS_TREE_ROOT_KEY,
  PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY,
  CHAINED_PRIORITY_TXN_HASH_KEY,
  NUMBER_OF_LAYER_1_TXS_KEY,
  PREV_BATCH_HASH_KEY,
  L2_DA_VALIDATOR_OUTPUT_HASH_KEY,
  USED_L2_DA_VALIDATOR_ADDRESS_KEY,
  EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY
}

Contents

DynamicIncrementalMerkle

Git Source

Library for managing https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures. Each tree is a complete binary tree with the ability to sequentially insert leaves, changing them from a zero to a non-zero value and updating its root. This structure allows inserting commitments (or other entries) that are not stored, but can be proven to be part of the tree at a later time if the root is kept. See {MerkleProof}. A tree is defined by the following parameters: Depth: The number of levels in the tree, it also defines the maximum number of leaves as 2**depth. Zero value: The value that represents an empty leaf. Used to avoid regular zero values to be part of the tree. Hashing function: A cryptographic hash function used to produce internal nodes. This is a fork of OpenZeppelin's MerkleTree library, with the changes to support dynamic tree growth (doubling the size when full).

Functions

setup

Initialize a Bytes32PushTree using {Hashes-Keccak256} to hash internal nodes. The capacity of the tree (i.e. number of leaves) is set to 2**levels. IMPORTANT: The zero value should be carefully chosen since it will be stored in the tree representing empty leaves. It should be a value that is not expected to be part of the tree.

function setup(Bytes32PushTree storage self, bytes32 zero)
  internal
  returns (bytes32 initialRoot);

reset

Resets the tree to a blank state. Calling this function on MerkleTree that was already setup and used will reset it to a blank state.

function reset(Bytes32PushTree storage self, bytes32 zero)
  internal
  returns (bytes32 initialRoot);

Parameters

NameTypeDescription
selfBytes32PushTree
zerobytes32The value that represents an empty leaf.

Returns

NameTypeDescription
initialRootbytes32The initial root of the tree.

push

Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the tree, and the resulting root. Hashing the leaf before calling this function is recommended as a protection against second pre-image attacks.

function push(Bytes32PushTree storage self, bytes32 leaf)
  internal
  returns (uint256 index, bytes32 newRoot);

root

Tree's root.

function root(Bytes32PushTree storage self) internal view returns (bytes32);

height

Tree's height (does not include the root node).

function height(Bytes32PushTree storage self) internal view returns (uint256);

Structs

Bytes32PushTree

A complete bytes32 Merkle tree. The sides and zero arrays are set to have a length equal to the depth of the tree during setup. Struct members have an underscore prefix indicating that they are "private" and should not be read or written to directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and lead to unexpected behavior. NOTE: The root and the updates history is not stored within the tree. Consider using a secondary structure to store a list of historical roots from the values returned from setup and {push} (e.g. a mapping, {BitMaps} or {Checkpoints}). WARNING: Updating any of the tree's parameters after the first insertion will result in a corrupted tree.

struct Bytes32PushTree {
  uint256 _nextLeafIndex;
  bytes32[] _sides;
  bytes32[] _zeros;
}

Merkle

Git Source

Author: Matter Labs

Note: security-contact: security@matterlabs.dev

Functions

calculateRoot

Calculate Merkle root by the provided Merkle proof. NOTE: When using this function, check that the _path length is equal to the tree height to prevent shorter/longer paths attack however, for chains settling on GW the proof includes the GW proof, so the path increases. See Mailbox for more details.

function calculateRoot(
  bytes32[] calldata _path,
  uint256 _index,
  bytes32 _itemHash
) internal pure returns (bytes32);

Parameters

NameTypeDescription
_pathbytes32[]Merkle path from the leaf to the root
_indexuint256Leaf index in the tree
_itemHashbytes32Hash of leaf content

Returns

NameTypeDescription
<none>bytes32The Merkle root

calculateRootMemory

Calculate Merkle root by the provided Merkle proof.

NOTE: When using this function, check that the _path length is appropriate to prevent shorter/longer paths attack

NOTE the tree can be joined. In this case the second tree's leaves indexes increase by the number of leaves in the first tree.

function calculateRootMemory(
  bytes32[] memory _path,
  uint256 _index,
  bytes32 _itemHash
) internal pure returns (bytes32);

Parameters

NameTypeDescription
_pathbytes32[]Merkle path from the leaf to the root
_indexuint256Leaf index in the tree.
_itemHashbytes32Hash of leaf content

Returns

NameTypeDescription
<none>bytes32The Merkle root

calculateRootPaths

Calculate Merkle root by the provided Merkle proof for a range of elements NOTE: When using this function, check that the _startPath and _endPath lengths are equal to the tree height to prevent shorter/longer paths attack

function calculateRootPaths(
  bytes32[] memory _startPath,
  bytes32[] memory _endPath,
  uint256 _startIndex,
  bytes32[] memory _itemHashes
) internal pure returns (bytes32);

Parameters

NameTypeDescription
_startPathbytes32[]Merkle path from the first element of the range to the root
_endPathbytes32[]Merkle path from the last element of the range to the root
_startIndexuint256Index of the first element of the range in the tree
_itemHashesbytes32[]Hashes of the elements in the range

Returns

NameTypeDescription
<none>bytes32The Merkle root

efficientHash

Keccak hash of the concatenation of two 32-byte words

function efficientHash(bytes32 _lhs, bytes32 _rhs)
  internal
  pure
  returns (bytes32 result);

_validatePathLengthForSingleProof

function _validatePathLengthForSingleProof(uint256 _index, uint256 _pathLength)
  private
  pure;

UncheckedMath

Git Source

Author: Matter Labs

The library for unchecked math.

Note: security-contact: security@matterlabs.dev

Functions

uncheckedInc

function uncheckedInc(uint256 _number) internal pure returns (uint256);

uncheckedAdd

function uncheckedAdd(uint256 _lhs, uint256 _rhs)
  internal
  pure
  returns (uint256);

RestrictionValidator

Git Source

Author: Matter Labs

The library which validates whether an address can be a valid restriction

Note: security-contact: security@matterlabs.dev

Functions

validateRestriction

Ensures that the provided address implements the restriction interface

Note that it can not guarantee that the corresponding address indeed implements the interface completely or that it is implemented correctly. It is mainly used to ensure that invalid restrictions can not be accidentally added.

function validateRestriction(address _restriction) internal view;

Diamond

Git Source

Author: Matter Labs

The helper library for managing the EIP-2535 diamond proxy.

Note: security-contact: security@matterlabs.dev

State Variables

DIAMOND_INIT_SUCCESS_RETURN_VALUE

Magic value that should be returned by diamond cut initialize contracts.

Used to distinguish calls to contracts that were supposed to be used as diamond initializer from other contracts.

bytes32 internal constant DIAMOND_INIT_SUCCESS_RETURN_VALUE =
  0x33774e659306e47509050e97cb651e731180a42d458212294d30751925c551a2;

DIAMOND_STORAGE_POSITION

Storage position of DiamondStorage structure.

bytes32 private constant DIAMOND_STORAGE_POSITION =
  0xc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131b;

Functions

getDiamondStorage

function getDiamondStorage()
  internal
  pure
  returns (DiamondStorage storage diamondStorage);

Returns

NameTypeDescription
diamondStorageDiamondStorageThe pointer to the storage where all specific diamond proxy parameters stored

diamondCut

Add/replace/remove any number of selectors and optionally execute a function with delegatecall

function diamondCut(DiamondCutData memory _diamondCut) internal;

Parameters

NameTypeDescription
_diamondCutDiamondCutDataDiamond's facet changes and the parameters to optional initialization delegatecall

_addFunctions

Add new functions to the diamond proxy NOTE: expect but NOT enforce that _selectors is NON-EMPTY array

function _addFunctions(
  address _facet,
  bytes4[] memory _selectors,
  bool _isFacetFreezable
) private;

_replaceFunctions

Change associated facets to already known function selectors NOTE: expect but NOT enforce that _selectors is NON-EMPTY array

function _replaceFunctions(
  address _facet,
  bytes4[] memory _selectors,
  bool _isFacetFreezable
) private;

_removeFunctions

Remove association with function and facet NOTE: expect but NOT enforce that _selectors is NON-EMPTY array

function _removeFunctions(address _facet, bytes4[] memory _selectors) private;

_saveFacetIfNew

Add address to the list of known facets if it is not on the list yet NOTE: should be called ONLY before adding a new selector associated with the address

function _saveFacetIfNew(address _facet) private;

_addOneFunction

*Add one function to the already known facet NOTE: It is expected but NOT enforced that:

  • _facet is NON-ZERO address
  • _facet is already stored address in DiamondStorage.facets
  • _selector is NOT associated by another facet*
function _addOneFunction(
  address _facet,
  bytes4 _selector,
  bool _isSelectorFreezable
) private;

_removeOneFunction

Remove one associated function with facet NOTE: It is expected but NOT enforced that _facet is NON-ZERO address

function _removeOneFunction(address _facet, bytes4 _selector) private;

_removeFacet

remove facet from the list of known facets NOTE: It is expected but NOT enforced that there are no selectors associated with _facet

function _removeFacet(address _facet) private;

_initializeDiamondCut

Delegates call to the initialization address with provided calldata

Used as a final step of diamond cut to execute the logic of the initialization for changed facets

function _initializeDiamondCut(address _init, bytes memory _calldata) private;

Events

DiamondCut

event DiamondCut(FacetCut[] facetCuts, address initAddress, bytes initCalldata);

Structs

SelectorToFacet

Utility struct that contains associated facet & meta information of selector

struct SelectorToFacet {
  address facetAddress;
  uint16 selectorPosition;
  bool isFreezable;
}

Properties

NameTypeDescription
facetAddressaddressaddress of the facet which is connected with selector
selectorPositionuint16index in FacetToSelectors.selectors array, where is selector stored
isFreezablebooldenotes whether the selector can be frozen.

FacetToSelectors

Utility struct that contains associated selectors & meta information of facet

struct FacetToSelectors {
  bytes4[] selectors;
  uint16 facetPosition;
}

Properties

NameTypeDescription
selectorsbytes4[]list of all selectors that belong to the facet
facetPositionuint16index in DiamondStorage.facets array, where is facet stored

DiamondStorage

The structure that holds all diamond proxy associated parameters

According to the EIP-2535 should be stored on a special storage key - DIAMOND_STORAGE_POSITION

struct DiamondStorage {
  mapping(bytes4 selector => SelectorToFacet selectorInfo) selectorToFacet;
  mapping(address facetAddress => FacetToSelectors facetInfo) facetToSelectors;
  address[] facets;
  bool isFrozen;
}

Properties

NameTypeDescription
selectorToFacetmapping(bytes4 selector => SelectorToFacet selectorInfo)A mapping from the selector to the facet address and its meta information
facetToSelectorsmapping(address facetAddress => FacetToSelectors facetInfo)A mapping from facet address to its selectors with meta information
facetsaddress[]The array of all unique facet addresses that belong to the diamond proxy
isFrozenboolDenotes whether the diamond proxy is frozen and all freezable facets are not accessible

FacetCut

Parameters for diamond changes that touch one of the facets

struct FacetCut {
  address facet;
  Action action;
  bool isFreezable;
  bytes4[] selectors;
}

Properties

NameTypeDescription
facetaddressThe address of facet that's affected by the cut
actionActionThe action that is made on the facet
isFreezableboolDenotes whether the facet & all their selectors can be frozen
selectorsbytes4[]An array of unique selectors that belongs to the facet address

DiamondCutData

Structure of the diamond proxy changes

struct DiamondCutData {
  FacetCut[] facetCuts;
  address initAddress;
  bytes initCalldata;
}

Properties

NameTypeDescription
facetCutsFacetCut[]The set of changes (adding/removing/replacement) of implementation contracts
initAddressaddressThe address that's delegate called after setting up new facet changes
initCalldatabytesCalldata for the delegate call to initAddress

Enums

Action

Type of change over diamond: add/replace/remove facets

enum Action {
  Add,
  Replace,
  Remove
}

PriorityQueue

Git Source

Author: Matter Labs

The library provides the API to interact with the priority queue container

Order of processing operations from queue - FIFO (Fist in - first out)

Note: security-contact: security@matterlabs.dev

Functions

getFirstUnprocessedPriorityTx

Returns zero if and only if no operations were processed from the queue

function getFirstUnprocessedPriorityTx(Queue storage _queue)
  internal
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256Index of the oldest priority operation that wasn't processed yet

getTotalPriorityTxs

function getTotalPriorityTxs(Queue storage _queue)
  internal
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of priority operations that were added to the priority queue, including all processed ones

getSize

function getSize(Queue storage _queue) internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of unprocessed priority operations in a priority queue

isEmpty

function isEmpty(Queue storage _queue) internal view returns (bool);

Returns

NameTypeDescription
<none>boolWhether the priority queue contains no operations

pushBack

Add the priority operation to the end of the priority queue

function pushBack(Queue storage _queue, PriorityOperation memory _operation)
  internal;

front

function front(Queue storage _queue)
  internal
  view
  returns (PriorityOperation memory);

Returns

NameTypeDescription
<none>PriorityOperationThe first unprocessed priority operation from the queue

popFront

Remove the first unprocessed priority operation from the queue

function popFront(Queue storage _queue)
  internal
  returns (PriorityOperation memory priorityOperation);

Returns

NameTypeDescription
priorityOperationPriorityOperationthat was popped from the priority queue

Structs

Queue

Container that stores priority operations

struct Queue {
  mapping(uint256 priorityOpId => PriorityOperation priorityOp) data;
  uint256 tail;
  uint256 head;
}

Properties

NameTypeDescription
datamapping(uint256 priorityOpId => PriorityOperation priorityOp)The inner mapping that saves priority operation by its index
tailuint256The pointer to the free slot
headuint256The pointer to the first unprocessed priority operation, equal to the tail if the queue is empty

PriorityTree

Git Source

Functions

getFirstUnprocessedPriorityTx

Returns zero if and only if no operations were processed from the tree

function getFirstUnprocessedPriorityTx(Tree storage _tree)
  internal
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256Index of the oldest priority operation that wasn't processed yet

getTotalPriorityTxs

function getTotalPriorityTxs(Tree storage _tree)
  internal
  view
  returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of priority operations that were added to the priority queue, including all processed ones

getSize

function getSize(Tree storage _tree) internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256The total number of unprocessed priority operations in a priority queue

push

Add the priority operation to the end of the priority queue

function push(Tree storage _tree, bytes32 _hash) internal;

setup

Set up the tree

function setup(Tree storage _tree, uint256 _startIndex) internal;

getRoot

function getRoot(Tree storage _tree) internal view returns (bytes32);

Returns

NameTypeDescription
<none>bytes32Returns the tree root.

isHistoricalRoot

function isHistoricalRoot(Tree storage _tree, bytes32 _root)
  internal
  view
  returns (bool);

Parameters

NameTypeDescription
_treeTree
_rootbytes32The root to check.

Returns

NameTypeDescription
<none>boolReturns true if the root is a historical root.

processBatch

Process the priority operations of a batch.

Note, that the function below only checks that a certain segment of items is present in the tree. It does not check that e.g. there are no zero items inside the provided itemHashes, so in theory proofs that include non-existing priority operations could be created. This function relies on the fact that the itemHashes of _priorityOpsData are hashes of valid priority transactions. This fact is ensured by the fact the rolling hash of those is sent to the Executor by the bootloader and so assuming that zero knowledge proofs are correct, so is the structure of the itemHashes.

function processBatch(
  Tree storage _tree,
  PriorityOpsBatchInfo memory _priorityOpsData
) internal;

skipUntil

Allows to skip a certain number of operations.

It is used when the corresponding transactions have been processed by priority queue.

function skipUntil(Tree storage _tree, uint256 _lastUnprocessed) internal;

Parameters

NameTypeDescription
_treeTree
_lastUnprocesseduint256The new expected id of the unprocessed transaction.

initFromCommitment

Initialize a chain from a commitment.

function initFromCommitment(
  Tree storage _tree,
  PriorityTreeCommitment memory _commitment
) internal;

l1Reinit

Reinitialize the tree from a commitment on L1.

function l1Reinit(Tree storage _tree, PriorityTreeCommitment memory _commitment)
  internal;

checkGWReinit

Reinitialize the tree from a commitment on GW.

function checkGWReinit(
  Tree storage _tree,
  PriorityTreeCommitment memory _commitment
) internal view;

getCommitment

Returns the commitment to the priority tree.

function getCommitment(Tree storage _tree)
  internal
  view
  returns (PriorityTreeCommitment memory commitment);

Structs

Tree

struct Tree {
  uint256 startIndex;
  uint256 unprocessedIndex;
  mapping(bytes32 => bool) historicalRoots;
  DynamicIncrementalMerkle.Bytes32PushTree tree;
}

SystemContractsCaller

Git Source

The library contains the functions to make system calls.

A more detailed description of the library and its methods can be found in the system-contracts repo.

Functions

systemCall

function systemCall(
  uint32 gasLimit,
  address to,
  uint256 value,
  bytes memory data
) internal returns (bool success);

systemCallWithReturndata

function systemCallWithReturndata(
  uint32 gasLimit,
  address to,
  uint128 value,
  bytes memory data
) internal returns (bool success, bytes memory returnData);

getFarCallABI

function getFarCallABI(
  uint32 dataOffset,
  uint32 memoryPage,
  uint32 dataStart,
  uint32 dataLength,
  uint32 gasPassed,
  uint8 shardId,
  CalldataForwardingMode forwardingMode,
  bool isConstructorCall,
  bool isSystemCall
) internal pure returns (uint256 farCallAbi);

getFarCallABIWithEmptyFatPointer

function getFarCallABIWithEmptyFatPointer(
  uint32 gasPassed,
  uint8 shardId,
  CalldataForwardingMode forwardingMode,
  bool isConstructorCall,
  bool isSystemCall
) internal pure returns (uint256 farCallAbiWithEmptyFatPtr);

Utils

Git Source

Functions

safeCastToU32

function safeCastToU32(uint256 _x) internal pure returns (uint32);

Contents

Constants

Git Source

EIP_712_TX_TYPE

The type id of ZKsync's EIP-712-signed transaction.

uint8 constant EIP_712_TX_TYPE = 0x71;

LEGACY_TX_TYPE

The type id of legacy transactions.

uint8 constant LEGACY_TX_TYPE = 0x0;

EIP_2930_TX_TYPE

The type id of legacy transactions.

uint8 constant EIP_2930_TX_TYPE = 0x01;

EIP_1559_TX_TYPE

The type id of EIP1559 transactions.

uint8 constant EIP_1559_TX_TYPE = 0x02;

L1_TO_L2_TX_TYPE

The type id of L1 to L2 transactions.

uint8 constant L1_TO_L2_TX_TYPE = 0xFF;

EfficientCall

Git Source

Author: Matter Labs

This library is used to perform ultra-efficient calls using zkEVM-specific features.

EVM calls always accept a memory slice as input and return a memory slice as output. Therefore, even if the user has a ready-made calldata slice, they still need to copy it to memory before calling. This is especially inefficient for large inputs (proxies, multi-calls, etc.). In turn, zkEVM operates over a fat pointer, which is a set of (memory page, offset, start, length) in the memory/calldata/returndata. This allows forwarding the calldata slice as is, without copying it to memory.

Fat pointer is not just an integer, it is an extended data type supported on the VM level. zkEVM creates the wellformed fat pointers for all the calldata/returndata regions, later the contract may manipulate the already created fat pointers to forward a slice of the data, but not to create new fat pointers!

*The allowed operation on fat pointers are:

  1. ptr.add - Transforms ptr.offset into ptr.offset + u32(_value). If overflow happens then it panics.
  2. ptr.sub - Transforms ptr.offset into ptr.offset - u32(_value). If underflow happens then it panics.
  3. ptr.pack - Do the concatenation between the lowest 128 bits of the pointer itself and the highest 128 bits of _value. It is typically used to prepare the ABI for external calls.
  4. ptr.shrink - Transforms ptr.length into ptr.length - u32(_shrink). If underflow happens then it panics.*

*The call opcodes accept the fat pointer and change it to its canonical form before passing it to the child call

  1. ptr.start is transformed into ptr.offset + ptr.start
  2. ptr.length is transformed into ptr.length - ptr.offset
  3. ptr.offset is transformed into 0*

Note: security-contact: security@matterlabs.dev

Functions

keccak

Call the keccak256 without copying calldata to memory.

function keccak(bytes calldata _data) internal view returns (bytes32);

Parameters

NameTypeDescription
_databytesThe preimage data.

Returns

NameTypeDescription
<none>bytes32The keccak256 hash.

sha

Call the sha256 precompile without copying calldata to memory.

function sha(bytes calldata _data) internal view returns (bytes32);

Parameters

NameTypeDescription
_databytesThe preimage data.

Returns

NameTypeDescription
<none>bytes32The sha256 hash.

call

Perform a call without copying calldata to memory.

function call(
  uint256 _gas,
  address _address,
  uint256 _value,
  bytes calldata _data,
  bool _isSystem
) internal returns (bytes memory returnData);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_valueuint256The msg.value to send.
_databytesThe calldata to use for the call.
_isSystemboolWhether the call should contain the isSystem flag.

Returns

NameTypeDescription
returnDatabytesThe copied to memory return data.

staticCall

Perform a staticCall without copying calldata to memory.

function staticCall(uint256 _gas, address _address, bytes calldata _data)
  internal
  view
  returns (bytes memory returnData);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.

Returns

NameTypeDescription
returnDatabytesThe copied to memory return data.

delegateCall

Perform a delegateCall without copying calldata to memory.

function delegateCall(uint256 _gas, address _address, bytes calldata _data)
  internal
  returns (bytes memory returnData);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.

Returns

NameTypeDescription
returnDatabytesThe copied to memory return data.

mimicCall

Perform a mimicCall (a call with custom msg.sender) without copying calldata to memory.

function mimicCall(
  uint256 _gas,
  address _address,
  bytes calldata _data,
  address _whoToMimic,
  bool _isConstructor,
  bool _isSystem
) internal returns (bytes memory returnData);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.
_whoToMimicaddressThe msg.sender for the next call.
_isConstructorboolWhether the call should contain the isConstructor flag.
_isSystemboolWhether the call should contain the isSystem flag.

Returns

NameTypeDescription
returnDatabytesThe copied to memory return data.

rawCall

Perform a call without copying calldata to memory.

function rawCall(
  uint256 _gas,
  address _address,
  uint256 _value,
  bytes calldata _data,
  bool _isSystem
) internal returns (bool success);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_valueuint256The msg.value to send.
_databytesThe calldata to use for the call.
_isSystemboolWhether the call should contain the isSystem flag.

Returns

NameTypeDescription
successboolwhether the call was successful.

rawStaticCall

Perform a staticCall without copying calldata to memory.

function rawStaticCall(uint256 _gas, address _address, bytes calldata _data)
  internal
  view
  returns (bool success);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.

Returns

NameTypeDescription
successboolwhether the call was successful.

rawDelegateCall

Perform a delegatecall without copying calldata to memory.

function rawDelegateCall(uint256 _gas, address _address, bytes calldata _data)
  internal
  returns (bool success);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.

Returns

NameTypeDescription
successboolwhether the call was successful.

rawMimicCall

Perform a mimicCall (call with custom msg.sender) without copying calldata to memory.

If called not in kernel mode, it will result in a revert (enforced by the VM)

function rawMimicCall(
  uint256 _gas,
  address _address,
  bytes calldata _data,
  address _whoToMimic,
  bool _isConstructor,
  bool _isSystem
) internal returns (bool success);

Parameters

NameTypeDescription
_gasuint256The gas to use for the call.
_addressaddressThe address to call.
_databytesThe calldata to use for the call.
_whoToMimicaddressThe msg.sender for the next call.
_isConstructorboolWhether the call should contain the isConstructor flag.
_isSystemboolWhether the call should contain the isSystem flag.

Returns

NameTypeDescription
successboolwhether the call was successful.

_verifyCallResult

Verify that a low-level call was successful, and revert if it wasn't, by bubbling the revert reason.

function _verifyCallResult(bool _success)
  private
  pure
  returns (bytes memory returnData);

Parameters

NameTypeDescription
_successboolWhether the call was successful.

Returns

NameTypeDescription
returnDatabytesThe copied to memory return data.

propagateRevert

Propagate the revert reason from the current call to the caller.

function propagateRevert() internal pure;

_loadFarCallABIIntoActivePtr

Load the far call ABI into active ptr, that will be used for the next call by reference.

function _loadFarCallABIIntoActivePtr(
  uint256 _gas,
  bytes calldata _data,
  bool _isConstructor,
  bool _isSystem
) private view;

Parameters

NameTypeDescription
_gasuint256The gas to be passed to the call.
_databytesThe calldata to be passed to the call.
_isConstructorboolWhether the call is a constructor call.
_isSystemboolWhether the call is a system call.

RLPEncoder

Git Source

Author: Matter Labs

This library provides RLP encoding functionality.

Note: security-contact: security@matterlabs.dev

Functions

encodeAddress

function encodeAddress(address _val)
  internal
  pure
  returns (bytes memory encoded);

encodeUint256

function encodeUint256(uint256 _val)
  internal
  pure
  returns (bytes memory encoded);

encodeNonSingleBytesLen

Encodes the size of bytes in RLP format.

function encodeNonSingleBytesLen(uint64 _len)
  internal
  pure
  returns (bytes memory);

Parameters

NameTypeDescription
_lenuint64The length of the bytes to encode. It has a uint64 type since as larger values are not supported. NOTE: panics if the length is 1 since the length encoding is ambiguous in this case.

encodeListLen

Encodes the size of list items in RLP format.

function encodeListLen(uint64 _len) internal pure returns (bytes memory);

Parameters

NameTypeDescription
_lenuint64The length of the bytes to encode. It has a uint64 type since as larger values are not supported.

_encodeLength

function _encodeLength(uint64 _len, uint256 _offset)
  private
  pure
  returns (bytes memory encoded);

_highestByteSet

Computes the index of the highest byte set in number.

Uses little endian ordering (The least significant byte has index 0). NOTE: returns 0 for 0

function _highestByteSet(uint256 _number) private pure returns (uint256 hbs);

SystemContractHelper

Git Source

Author: Matter Labs

Library used for accessing zkEVM-specific opcodes, needed for the development of system contracts.

While this library will be eventually available to public, some of the provided methods won't work for non-system contracts and also breaking changes at short notice are possible. We do not recommend this library for external use.

Note: security-contact: security@matterlabs.dev

Functions

toL1

Send an L2Log to L1.

The meaning of all these parameters is context-dependent, but they have no intrinsic meaning per se.

function toL1(bool _isService, bytes32 _key, bytes32 _value) internal;

Parameters

NameTypeDescription
_isServiceboolThe isService flag.
_keybytes32The key part of the L2Log.
_valuebytes32The value part of the L2Log.

getCodeAddress

Get address of the currently executed code.

This allows differentiating between call and delegatecall. During the former this and codeAddress are the same, while during the latter they are not.

function getCodeAddress() internal view returns (address addr);

loadCalldataIntoActivePtr

Provide a compiler hint, by placing calldata fat pointer into virtual ACTIVE_PTR, that can be manipulated by ptr.add/ptr.sub/ptr.pack/ptr.shrink later.

This allows making a call by forwarding calldata pointer to the child call. It is a much more efficient way to forward calldata, than standard EVM bytes copying.

function loadCalldataIntoActivePtr() internal view;

ptrPackIntoActivePtr

Compiler simulation of the ptr.pack opcode for the virtual ACTIVE_PTR pointer.

Do the concatenation between lowest part of ACTIVE_PTR and highest part of _farCallAbi forming packed fat pointer for a far call or ret ABI when necessary. Note: Panics if the lowest 128 bits of _farCallAbi are not zeroes.

function ptrPackIntoActivePtr(uint256 _farCallAbi) internal view;

ptrAddIntoActive

Compiler simulation of the ptr.add opcode for the virtual ACTIVE_PTR pointer.

Transforms ACTIVE_PTR.offset into ACTIVE_PTR.offset + u32(_value). If overflow happens then it panics.

function ptrAddIntoActive(uint32 _value) internal view;

ptrShrinkIntoActive

Compiler simulation of the ptr.shrink opcode for the virtual ACTIVE_PTR pointer.

Transforms ACTIVE_PTR.length into ACTIVE_PTR.length - u32(_shrink). If underflow happens then it panics.

function ptrShrinkIntoActive(uint32 _shrink) internal view;

packPrecompileParams

packs precompile parameters into one word

function packPrecompileParams(
  uint32 _inputMemoryOffset,
  uint32 _inputMemoryLength,
  uint32 _outputMemoryOffset,
  uint32 _outputMemoryLength,
  uint64 _perPrecompileInterpreted
) internal pure returns (uint256 rawParams);

Parameters

NameTypeDescription
_inputMemoryOffsetuint32The memory offset in 32-byte words for the input data for calling the precompile.
_inputMemoryLengthuint32The length of the input data in words.
_outputMemoryOffsetuint32The memory offset in 32-byte words for the output data.
_outputMemoryLengthuint32The length of the output data in words.
_perPrecompileInterpreteduint64The constant, the meaning of which is defined separately for each precompile. For information, please read the documentation of the precompilecall log in the VM.

unsafePrecompileCall

Call precompile with given parameters.

The list of currently available precompiles sha256, keccak256, ecrecover. NOTE: The precompile type depends on this which calls precompile, which means that only system contracts corresponding to the list of precompiles above can do precompileCall.

If used not in the sha256, keccak256 or ecrecover contracts, it will just burn the gas provided.

This method is unsafe because it does not check whether there is enough gas to burn.

function unsafePrecompileCall(
  uint256 _rawParams,
  uint32 _gasToBurn,
  uint32 _pubdataToSpend
) internal view returns (bool success);

Parameters

NameTypeDescription
_rawParamsuint256The packed precompile params. They can be retrieved by the packPrecompileParams method.
_gasToBurnuint32The number of gas to burn during this call.
_pubdataToSpenduint32The number of pubdata bytes to burn during the call.

Returns

NameTypeDescription
successboolWhether the call was successful.

setValueForNextFarCall

Set msg.value to next far call.

If called not in kernel mode, it will result in a revert (enforced by the VM)

function setValueForNextFarCall(uint128 _value) internal returns (bool success);

Parameters

NameTypeDescription
_valueuint128The msg.value that will be used for the next call.

eventInitialize

Initialize a new event.

function eventInitialize(uint256 initializer, uint256 value1) internal;

Parameters

NameTypeDescription
initializeruint256The event initializing value.
value1uint256The first topic or data chunk.

eventWrite

Continue writing the previously initialized event.

function eventWrite(uint256 value1, uint256 value2) internal;

Parameters

NameTypeDescription
value1uint256The first topic or data chunk.
value2uint256The second topic or data chunk.

getZkSyncMetaBytes

Get the packed representation of the ZkSyncMeta from the current context.

NOTE: The behavior of this function will experience a breaking change in 2024.

The fields in ZkSyncMeta are NOT tightly packed, i.e. there is a special rule on how they are packed. For more information, please read the documentation on ZkSyncMeta.

function getZkSyncMetaBytes() internal view returns (uint256 meta);

Returns

NameTypeDescription
metauint256The packed representation of the ZkSyncMeta.

extractNumberFromMeta

Returns the bits [offset..offset+size-1] of the meta.

function extractNumberFromMeta(uint256 meta, uint256 offset, uint256 size)
  internal
  pure
  returns (uint256 result);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.
offsetuint256The offset of the bits.
sizeuint256The size of the extracted number in bits.

Returns

NameTypeDescription
resultuint256The extracted number.

getPubdataPublishedFromMeta

Given the packed representation of ZkSyncMeta, retrieves the number of pubdata bytes published in the batch so far.

NOTE: The behavior of this function will experience a breaking change in 2024.

function getPubdataPublishedFromMeta(uint256 meta)
  internal
  pure
  returns (uint32 pubdataPublished);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
pubdataPublisheduint32The amount of pubdata published in the system so far.

getHeapSizeFromMeta

Given the packed representation of ZkSyncMeta, retrieves the number of the current size of the heap in bytes.

The following expression: getHeapSizeFromMeta(getZkSyncMetaBytes()) is equivalent to the MSIZE in Solidity.

function getHeapSizeFromMeta(uint256 meta)
  internal
  pure
  returns (uint32 heapSize);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
heapSizeuint32The size of the memory in bytes byte.

getAuxHeapSizeFromMeta

Given the packed representation of ZkSyncMeta, retrieves the number of the current size of the auxiliary heap in bytes.

You can read more on auxiliary memory in the VM1.2 documentation.

function getAuxHeapSizeFromMeta(uint256 meta)
  internal
  pure
  returns (uint32 auxHeapSize);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
auxHeapSizeuint32The size of the auxiliary memory in bytes byte.

getShardIdFromMeta

Given the packed representation of ZkSyncMeta, retrieves the shardId of this.

Currently only shard 0 (zkRollup) is supported.

function getShardIdFromMeta(uint256 meta) internal pure returns (uint8 shardId);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
shardIduint8The shardId of this.

getCallerShardIdFromMeta

Given the packed representation of ZkSyncMeta, retrieves the shardId of the msg.sender.

Currently only shard 0 (zkRollup) is supported.

function getCallerShardIdFromMeta(uint256 meta)
  internal
  pure
  returns (uint8 callerShardId);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
callerShardIduint8The shardId of the msg.sender.

getCodeShardIdFromMeta

Given the packed representation of ZkSyncMeta, retrieves the shardId of the currently executed code.

Currently only shard 0 (zkRollup) is supported.

function getCodeShardIdFromMeta(uint256 meta)
  internal
  pure
  returns (uint8 codeShardId);

Parameters

NameTypeDescription
metauint256Packed representation of the ZkSyncMeta.

Returns

NameTypeDescription
codeShardIduint8The shardId of the currently executed code.

getZkSyncMeta

Retrieves the ZkSyncMeta structure.

NOTE: The behavior of this function will experience a breaking change in 2024.

function getZkSyncMeta() internal view returns (ZkSyncMeta memory meta);

Returns

NameTypeDescription
metaZkSyncMetaThe ZkSyncMeta execution context parameters.

getCallFlags

Returns the call flags for the current call.

Call flags is the value of the first register at the start of the call.

The zero bit of the callFlags indicates whether the call is a constructor call. The first bit of the callFlags indicates whether the call is a system one.

function getCallFlags() internal view returns (uint256 callFlags);

Returns

NameTypeDescription
callFlagsuint256The bitmask of the callflags.

getCalldataPtr

Returns the current calldata pointer.

NOTE: This file is just an integer and it cannot be used to forward the calldata to the next calls in any way.

function getCalldataPtr() internal view returns (uint256 ptr);

Returns

NameTypeDescription
ptruint256The current calldata pointer.

getExtraAbiData

Returns the N-th extraAbiParam for the current call.

It is equal to the value of the (N+2)-th register at the start of the call.

function getExtraAbiData(uint256 index)
  internal
  view
  returns (uint256 extraAbiData);

Returns

NameTypeDescription
extraAbiDatauint256The value of the N-th extraAbiParam for this call.

isSystemCall

Returns whether the current call is a system call.

function isSystemCall() internal view returns (bool);

Returns

NameTypeDescription
<none>booltrue or false based on whether the current call is a system call.

isSystemContract

Returns whether the address is a system contract.

function isSystemContract(address _address) internal pure returns (bool);

Parameters

NameTypeDescription
_addressaddressThe address to test

Returns

NameTypeDescription
<none>booltrue or false based on whether the _address is a system contract.

isSystemCallFromEvmEmulator

Returns whether the current call is a system call from EVM emulator.

function isSystemCallFromEvmEmulator() internal view returns (bool);

Returns

NameTypeDescription
<none>booltrue or false based on whether the current call is a system call from EVM emulator.

burnGas

Method used for burning a certain amount of gas.

function burnGas(uint32 _gasToPay, uint32 _pubdataToSpend) internal view;

Parameters

NameTypeDescription
_gasToPayuint32The number of gas to burn.
_pubdataToSpenduint32The number of pubdata bytes to burn during the call.

mimicCall

Performs a mimicCall to an address.

function mimicCall(address _to, address _whoToMimic, bytes memory _data)
  internal
  returns (bool success, bytes memory returndata);

Parameters

NameTypeDescription
_toaddressThe address to call.
_whoToMimicaddressThe address to mimic.
_databytesThe data to pass to the call.

Returns

NameTypeDescription
successboolWhether the call was successful.
returndatabytesThe return data of the call.

forceDeployNoConstructor

Force deploys some bytecode hash to an address without invoking the constructor.

function forceDeployNoConstructor(address _addr, bytes32 _bytecodeHash)
  internal;

Parameters

NameTypeDescription
_addraddressThe address to force-deploy the bytecodehash to.
_bytecodeHashbytes32The bytecode hash to force-deploy.

mimicCallWithPropagatedRevert

Performs a mimicCall to an address, while ensuring that the call was successful

function mimicCallWithPropagatedRevert(
  address _to,
  address _whoToMimic,
  bytes memory _data
) internal;

Parameters

NameTypeDescription
_toaddressThe address to call.
_whoToMimicaddressThe address to mimic.
_databytesThe data to pass to the call.

Constants

Git Source

UINT32_MASK

uint256 constant UINT32_MASK = type(uint32).max;

UINT64_MASK

uint256 constant UINT64_MASK = type(uint64).max;

UINT128_MASK

uint256 constant UINT128_MASK = type(uint128).max;

ADDRESS_MASK

uint256 constant ADDRESS_MASK = type(uint160).max;

ZkSyncMeta

Git Source

NOTE: The getZkSyncMeta that is used to obtain this struct will experience a breaking change in 2024.

struct ZkSyncMeta {
  uint32 pubdataPublished;
  uint32 heapSize;
  uint32 auxHeapSize;
  uint8 shardId;
  uint8 callerShardId;
  uint8 codeShardId;
}

Global

Git Source

enum Global {
  CalldataPtr,
  CallFlags,
  ExtraABIData1,
  ExtraABIData2,
  ReturndataPtr
}

SystemContractsCaller

Git Source

Author: Matter Labs

A library that allows calling contracts with the isSystem flag.

It is needed to call ContractDeployer and NonceHolder.

Note: security-contact: security@matterlabs.dev

Functions

systemCall

Makes a call with the isSystem flag.

Note, that the isSystem flag can only be set when calling system contracts.

function systemCall(
  uint32 gasLimit,
  address to,
  uint256 value,
  bytes memory data
) internal returns (bool success);

Parameters

NameTypeDescription
gasLimituint32The gas limit for the call.
toaddressThe address to call.
valueuint256The value to pass with the transaction.
databytesThe calldata.

Returns

NameTypeDescription
successboolWhether the transaction has been successful.

systemCallWithReturndata

Makes a call with the isSystem flag.

Note, that the isSystem flag can only be set when calling system contracts.

function systemCallWithReturndata(
  uint32 gasLimit,
  address to,
  uint128 value,
  bytes memory data
) internal returns (bool success, bytes memory returnData);

Parameters

NameTypeDescription
gasLimituint32The gas limit for the call.
toaddressThe address to call.
valueuint128The value to pass with the transaction.
databytesThe calldata.

Returns

NameTypeDescription
successboolWhether the transaction has been successful.
returnDatabytesThe returndata of the transaction (revert reason in case the transaction has failed).

systemCallWithPropagatedRevert

Makes a call with the isSystem flag.

Note, that the isSystem flag can only be set when calling system contracts.

function systemCallWithPropagatedRevert(
  uint32 gasLimit,
  address to,
  uint128 value,
  bytes memory data
) internal returns (bytes memory returnData);

Parameters

NameTypeDescription
gasLimituint32The gas limit for the call.
toaddressThe address to call.
valueuint128The value to pass with the transaction.
databytesThe calldata.

Returns

NameTypeDescription
returnDatabytesThe returndata of the transaction. In case the transaction reverts, the error bubbles up to the parent frame.

getFarCallABI

Calculates the packed representation of the FarCallABI.

The FarCallABI has the following structure: pub struct FarCallABI { pub memory_quasi_fat_pointer: FatPointer, pub gas_passed: u32, pub shard_id: u8, pub forwarding_mode: FarCallForwardPageType, pub constructor_call: bool, pub to_system: bool, } The FatPointer struct: pub struct FatPointer { pub offset: u32, // offset relative to start pub memory_page: u32, // memory page where slice is located pub start: u32, // absolute start of the slice pub length: u32, // length of the slice }

Note, that the actual layout is the following: [0..32) bits -- the calldata offset [32..64) bits -- the memory page to use. Can be left blank in most of the cases. [64..96) bits -- the absolute start of the slice [96..128) bits -- the length of the slice. [128..192) bits -- empty bits. [192..224) bits -- gasPassed. [224..232) bits -- forwarding_mode [232..240) bits -- shard id. [240..248) bits -- constructor call flag [248..256] bits -- system call flag

function getFarCallABI(
  uint32 dataOffset,
  uint32 memoryPage,
  uint32 dataStart,
  uint32 dataLength,
  uint32 gasPassed,
  uint8 shardId,
  CalldataForwardingMode forwardingMode,
  bool isConstructorCall,
  bool isSystemCall
) internal pure returns (uint256 farCallAbi);

Parameters

NameTypeDescription
dataOffsetuint32Calldata offset in memory. Provide 0 unless using custom pointer.
memoryPageuint32Memory page to use. Provide 0 unless using custom pointer.
dataStartuint32The start of the calldata slice. Provide the offset in memory if not using custom pointer.
dataLengthuint32The calldata length. Provide the length of the calldata in bytes unless using custom pointer.
gasPasseduint32The gas to pass with the call.
shardIduint8Of the account to call. Currently only 0 is supported.
forwardingModeCalldataForwardingModeThe forwarding mode to use: - provide CalldataForwardingMode.UseHeap when using your current memory - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer.
isConstructorCallboolWhether the call will be a call to the constructor (ignored when the caller is not a system contract).
isSystemCallboolWhether the call will have the isSystem flag.

Returns

NameTypeDescription
farCallAbiuint256The far call ABI.

getFarCallABIWithEmptyFatPointer

Calculates the packed representation of the FarCallABI with zero fat pointer fields.

function getFarCallABIWithEmptyFatPointer(
  uint32 gasPassed,
  uint8 shardId,
  CalldataForwardingMode forwardingMode,
  bool isConstructorCall,
  bool isSystemCall
) internal pure returns (uint256 farCallAbiWithEmptyFatPtr);

Parameters

NameTypeDescription
gasPasseduint32The gas to pass with the call.
shardIduint8Of the account to call. Currently only 0 is supported.
forwardingModeCalldataForwardingModeThe forwarding mode to use: - provide CalldataForwardingMode.UseHeap when using your current memory - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer.
isConstructorCallboolWhether the call will be a call to the constructor (ignored when the caller is not a system contract).
isSystemCallboolWhether the call will have the isSystem flag.

Returns

NameTypeDescription
farCallAbiWithEmptyFatPtruint256The far call ABI with zero fat pointer fields.

Constants

Git Source

TO_L1_CALL_ADDRESS

address constant TO_L1_CALL_ADDRESS = address((1 << 16) - 1);

CODE_ADDRESS_CALL_ADDRESS

address constant CODE_ADDRESS_CALL_ADDRESS = address((1 << 16) - 2);

PRECOMPILE_CALL_ADDRESS

address constant PRECOMPILE_CALL_ADDRESS = address((1 << 16) - 3);

META_CALL_ADDRESS

address constant META_CALL_ADDRESS = address((1 << 16) - 4);

MIMIC_CALL_CALL_ADDRESS

address constant MIMIC_CALL_CALL_ADDRESS = address((1 << 16) - 5);

SYSTEM_MIMIC_CALL_CALL_ADDRESS

address constant SYSTEM_MIMIC_CALL_CALL_ADDRESS = address((1 << 16) - 6);

MIMIC_CALL_BY_REF_CALL_ADDRESS

address constant MIMIC_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 7);

SYSTEM_MIMIC_CALL_BY_REF_CALL_ADDRESS

address constant SYSTEM_MIMIC_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 8);

RAW_FAR_CALL_CALL_ADDRESS

address constant RAW_FAR_CALL_CALL_ADDRESS = address((1 << 16) - 9);

RAW_FAR_CALL_BY_REF_CALL_ADDRESS

address constant RAW_FAR_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 10);

SYSTEM_CALL_CALL_ADDRESS

address constant SYSTEM_CALL_CALL_ADDRESS = address((1 << 16) - 11);

SYSTEM_CALL_BY_REF_CALL_ADDRESS

address constant SYSTEM_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 12);

SET_CONTEXT_VALUE_CALL_ADDRESS

address constant SET_CONTEXT_VALUE_CALL_ADDRESS = address((1 << 16) - 13);

SET_PUBDATA_PRICE_CALL_ADDRESS

address constant SET_PUBDATA_PRICE_CALL_ADDRESS = address((1 << 16) - 14);

INCREMENT_TX_COUNTER_CALL_ADDRESS

address constant INCREMENT_TX_COUNTER_CALL_ADDRESS = address((1 << 16) - 15);

PTR_CALLDATA_CALL_ADDRESS

address constant PTR_CALLDATA_CALL_ADDRESS = address((1 << 16) - 16);

CALLFLAGS_CALL_ADDRESS

address constant CALLFLAGS_CALL_ADDRESS = address((1 << 16) - 17);

PTR_RETURNDATA_CALL_ADDRESS

address constant PTR_RETURNDATA_CALL_ADDRESS = address((1 << 16) - 18);

EVENT_INITIALIZE_ADDRESS

address constant EVENT_INITIALIZE_ADDRESS = address((1 << 16) - 19);

EVENT_WRITE_ADDRESS

address constant EVENT_WRITE_ADDRESS = address((1 << 16) - 20);

LOAD_CALLDATA_INTO_ACTIVE_PTR_CALL_ADDRESS

address constant LOAD_CALLDATA_INTO_ACTIVE_PTR_CALL_ADDRESS =
  address((1 << 16) - 21);

LOAD_LATEST_RETURNDATA_INTO_ACTIVE_PTR_CALL_ADDRESS

address constant LOAD_LATEST_RETURNDATA_INTO_ACTIVE_PTR_CALL_ADDRESS =
  address((1 << 16) - 22);

PTR_ADD_INTO_ACTIVE_CALL_ADDRESS

address constant PTR_ADD_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 23);

PTR_SHRINK_INTO_ACTIVE_CALL_ADDRESS

address constant PTR_SHRINK_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 24);

PTR_PACK_INTO_ACTIVE_CALL_ADDRESS

address constant PTR_PACK_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 25);

MULTIPLICATION_HIGH_ADDRESS

address constant MULTIPLICATION_HIGH_ADDRESS = address((1 << 16) - 26);

GET_EXTRA_ABI_DATA_ADDRESS

address constant GET_EXTRA_ABI_DATA_ADDRESS = address((1 << 16) - 27);

META_PUBDATA_PUBLISHED_OFFSET

uint256 constant META_PUBDATA_PUBLISHED_OFFSET = 0 * 8;

META_HEAP_SIZE_OFFSET

uint256 constant META_HEAP_SIZE_OFFSET = 8 * 8;

META_AUX_HEAP_SIZE_OFFSET

uint256 constant META_AUX_HEAP_SIZE_OFFSET = 12 * 8;

META_SHARD_ID_OFFSET

uint256 constant META_SHARD_ID_OFFSET = 28 * 8;

META_CALLER_SHARD_ID_OFFSET

uint256 constant META_CALLER_SHARD_ID_OFFSET = 29 * 8;

META_CODE_SHARD_ID_OFFSET

uint256 constant META_CODE_SHARD_ID_OFFSET = 30 * 8;

CalldataForwardingMode

Git Source

The way to forward the calldata:

  • Use the current heap (i.e. the same as on EVM).
  • Use the auxiliary heap.
  • Forward via a pointer

Note, that currently, users do not have access to the auxiliary heap and so the only type of forwarding that will be used by the users are UseHeap and ForwardFatPointer for forwarding a slice of the current calldata to the next call.

enum CalldataForwardingMode {
  UseHeap,
  ForwardFatPointer,
  UseAuxHeap
}

Utils

Git Source

Author: Matter Labs

Common utilities used in ZKsync system contracts

Note: security-contact: security@matterlabs.dev

State Variables

IS_CONSTRUCTOR_BYTECODE_HASH_BIT_MASK

Bit mask of bytecode hash "isConstructor" marker

bytes32 internal constant IS_CONSTRUCTOR_BYTECODE_HASH_BIT_MASK =
  0x00ff000000000000000000000000000000000000000000000000000000000000;

SET_IS_CONSTRUCTOR_MARKER_BIT_MASK

Bit mask to set the "isConstructor" marker in the bytecode hash

bytes32 internal constant SET_IS_CONSTRUCTOR_MARKER_BIT_MASK =
  0x0001000000000000000000000000000000000000000000000000000000000000;

MAX_BYTECODE_LENGTH

uint256 internal constant MAX_BYTECODE_LENGTH = (2 ** 16) - 1;

Functions

safeCastToU128

function safeCastToU128(uint256 _x) internal pure returns (uint128);

safeCastToU32

function safeCastToU32(uint256 _x) internal pure returns (uint32);

safeCastToU24

function safeCastToU24(uint256 _x) internal pure returns (uint24);

isCodeHashEVM

function isCodeHashEVM(bytes32 _bytecodeHash) internal pure returns (bool);

Returns

NameTypeDescription
<none>boolIf this bytecode hash for EVM contract or not

bytecodeLenInBytes

function bytecodeLenInBytes(bytes32 _bytecodeHash)
  internal
  pure
  returns (uint256 codeLengthInBytes);

Returns

NameTypeDescription
codeLengthInBytesuint256The bytecode length in bytes

bytecodeLenInWords

function bytecodeLenInWords(bytes32 _bytecodeHash)
  internal
  pure
  returns (uint256 codeLengthInWords);

Returns

NameTypeDescription
codeLengthInWordsuint256The bytecode length in machine words

isContractConstructed

Denotes whether bytecode hash corresponds to a contract that already constructed

function isContractConstructed(bytes32 _bytecodeHash)
  internal
  pure
  returns (bool);

isContractConstructing

Denotes whether bytecode hash corresponds to a contract that is on constructor or has already been constructed

function isContractConstructing(bytes32 _bytecodeHash)
  internal
  pure
  returns (bool);

constructingBytecodeHash

Sets "isConstructor" flag to TRUE for the bytecode hash

function constructingBytecodeHash(bytes32 _bytecodeHash)
  internal
  pure
  returns (bytes32);

Parameters

NameTypeDescription
_bytecodeHashbytes32The bytecode hash for which it is needed to set the constructing flag

Returns

NameTypeDescription
<none>bytes32The bytecode hash with "isConstructor" flag set to TRUE

constructedBytecodeHash

Sets "isConstructor" flag to FALSE for the bytecode hash

function constructedBytecodeHash(bytes32 _bytecodeHash)
  internal
  pure
  returns (bytes32);

Parameters

NameTypeDescription
_bytecodeHashbytes32The bytecode hash for which it is needed to set the constructing flag

Returns

NameTypeDescription
<none>bytes32The bytecode hash with "isConstructor" flag set to FALSE

hashL2Bytecode

Validate the bytecode format and calculate its hash.

function hashL2Bytecode(bytes calldata _bytecode)
  internal
  view
  returns (bytes32 hashedBytecode);

Parameters

NameTypeDescription
_bytecodebytesThe bytecode to hash.

Returns

NameTypeDescription
hashedBytecodebytes32The 32-byte hash of the bytecode. Note: The function reverts the execution if the bytecode has non expected format: - Bytecode bytes length is not a multiple of 32 - Bytecode bytes length is not less than 2^21 bytes (2^16 words) - Bytecode words length is not odd

hashEVMBytecode

Validate the bytecode format and calculate its hash.

function hashEVMBytecode(
  uint256 _evmBytecodeLen,
  bytes calldata _paddedBytecode
) internal view returns (bytes32 hashedEVMBytecode);

Parameters

NameTypeDescription
_evmBytecodeLenuint256The length of original EVM bytecode in bytes
_paddedBytecodebytesThe padded EVM bytecode to hash.

Returns

NameTypeDescription
hashedEVMBytecodebytes32The 32-byte hash of the EVM bytecode. Note: The function reverts the execution if the bytecode has non expected format: - Bytecode bytes length is not a multiple of 32 - Bytecode bytes length is greater than 2^16 - 1 bytes - Bytecode words length is not odd

getNewAddressCreate2EVM

Calculates the address of a deployed contract via create2 on the EVM

function getNewAddressCreate2EVM(
  address _sender,
  bytes32 _salt,
  bytes32 _bytecodeHash
) internal pure returns (address newAddress);

Parameters

NameTypeDescription
_senderaddressThe account that deploys the contract.
_saltbytes32The create2 salt.
_bytecodeHashbytes32The hash of the init code of the new contract.

Returns

NameTypeDescription
newAddressaddressThe derived address of the account.

getNewAddressCreateEVM

Calculates the address of a deployed contract via create

function getNewAddressCreateEVM(address _sender, uint256 _senderNonce)
  internal
  pure
  returns (address newAddress);

Parameters

NameTypeDescription
_senderaddressThe account that deploys the contract.
_senderNonceuint256The deploy nonce of the sender's account.