Snapshot notice
These contracts target protocol version 29, commit65234ab0
.
[!NOTE] 🛠️ This is a development repository for interfaces only. If you're looking for contract implementations, see 👉 matter-labs/era-contracts
📦 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
- API reference: https://docs.zksync.io
- Canonical source: matter-labs/era-contracts
🤝 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.
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
-
Add the package
# Hardhat / npm / bun npm add @matterlabs/zksync-contracts # or Foundry forge install matter-labs/zksync-contracts
-
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 }
-
Build & test
- Hardhat
npx hardhat compile
- Foundry
forge build
- Hardhat
Contents
Contents
- asset-router
- interfaces
- ntv
- EthTransferFailed
- NativeTokenVaultAlreadySet
- WrongMsgLength
- ZeroAmountToTransfer
- WrongAmountTransferred
- EmptyToken
- ClaimFailedDepositFailed
- WrongL2Sender
- WrongCounterpart
Contents
IAssetRouterBase
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
Name | Type | Description |
---|---|---|
_assetRegistrationData | bytes32 | The asset data which may include the asset address and any additional required data or encodings. |
_assetHandlerAddress | address | The 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the transaction to check. |
_assetId | bytes32 | The bridged asset ID. |
_transferData | bytes | The 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
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
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 toaddress(0)
and the sender has NO deployed bytecode on L1, the refund will be sent to themsg.sender
address. - If
_refundRecipient
is set toaddress(0)
and the sender has deployed bytecode on L1, the refund will be sent to the aliasedmsg.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
Name | Type | Description |
---|---|---|
_originalCaller | address | The msg.sender address from the external call that initiated current one. |
_l2Receiver | address | The account address that should receive funds on L2. |
_l1Token | address | The L1 token address which is deposited. |
_amount | uint256 | The total amount of tokens to be bridged. |
_l2TxGasLimit | uint256 | The L2 gas limit to be used in the corresponding L2 transaction. |
_l2TxGasPerPubdataByte | uint256 | The gasPerPubdataByteLimit to be used in the corresponding L2 transaction. |
_refundRecipient | address | The address on L2 that will receive the refund for the transaction. |
Returns
Name | Type | Description |
---|---|---|
txHash | bytes32 | The 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);
ETH_TOKEN_ASSET_ID
function ETH_TOKEN_ASSET_ID() external view returns (bytes32);
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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The ZK chain id to which the deposit was initiated. |
_depositSender | address | The address of the entity that initiated the deposit. |
_assetId | bytes32 | The unique identifier of the deposited L1 token. |
_assetData | bytes | The 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The ZK chain id to which deposit was initiated. |
_depositSender | address | The address of the entity that initiated the deposit. |
_assetId | bytes32 | The unique identifier of the deposited L1 token. |
_assetData | bytes | The encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information. |
_l2TxHash | bytes32 | The L2 transaction hash of the failed deposit finalization. |
_l2BatchNumber | uint256 | The L2 batch number where the deposit finalization was processed. |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_l2TxNumberInBatch | uint16 | The L2 transaction number in a batch, in which the log was sent. |
_merkleProof | bytes32[] | 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
Name | Type | Description |
---|---|---|
_assetId | bytes32 | |
_amount | uint256 | The asset amount to be transferred to native token vault. |
_originalCaller | address | The 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the transaction to check |
_l2BatchNumber | uint256 | The L2 batch number where the withdrawal was processed |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message |
_l2TxNumberInBatch | uint16 | The L2 transaction number in the batch, in which the log was sent |
_message | bytes | The L2 withdraw data, stored in an L2 -> L1 message |
_merkleProof | bytes32[] | 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the ZK chain to which deposit. |
_originalCaller | address | The msg.sender address from the external call that initiated current one. |
_value | uint256 | The msg.value on the target chain tx. |
_data | bytes | The calldata for the second bridge deposit. |
Returns
Name | Type | Description |
---|---|---|
request | L2TransactionRequestTwoBridgesInner | The 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
Name | Type | Description |
---|---|---|
_sender | address | The address of the deposit initiator. |
_assetId | bytes32 | The deposited asset ID. |
_assetData | bytes | The encoded data, which is used by the asset handler to determine L2 recipient and amount. Might include extra information. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes | Returns 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the ZK chain to which deposit. |
_assetId | bytes32 | The deposited asset ID. |
_originalCaller | address | The msg.sender address from the external call that initiated current one. |
_amount | uint256 | The 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the ZK chain to which confirm the deposit. |
_txDataHash | bytes32 | The keccak256 hash of 0x01 |
_txHash | bytes32 | The 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
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
Name | Type | Description |
---|---|---|
_assetId | bytes32 | The assetId of the legacy token. |
Events
WithdrawalInitiatedAssetRouter
event WithdrawalInitiatedAssetRouter(
uint256 chainId,
address indexed l2Sender,
bytes32 indexed assetId,
bytes assetData
);
Contents
- AssetHandlerModifiers
- IAssetHandler
- IBridgedStandardToken
- IL1AssetDeploymentTracker
- IL1AssetHandler
- IL1BaseTokenAssetHandler
- IL1ERC20Bridge
- FinalizeL1DepositParams
- IL1Nullifier
- IL1SharedBridgeLegacy
- IL2SharedBridgeLegacy
- IL2SharedBridgeLegacyFunctions
- IL2WrappedBaseToken
- IWETH9
IAssetHandler
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
Name | Type | Description |
---|---|---|
_chainId | uint256 | the chainId that the message is from |
_assetId | bytes32 | the assetId of the asset being bridged |
_data | bytes | the 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | the chainId that the message will be sent to |
_msgValue | uint256 | the msg.value of the L2 transaction. For now it is always 0. |
_assetId | bytes32 | the assetId of the asset being bridged |
_originalCaller | address | the original caller of the |
_data | bytes | the actual data specified for the function |
Returns
Name | Type | Description |
---|---|---|
_bridgeMintData | bytes | The 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
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
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
bridgeCheckCounterpartAddress
function bridgeCheckCounterpartAddress(
uint256 _chainId,
bytes32 _assetId,
address _originalCaller,
address _assetHandlerAddressOnCounterpart
) external view;
IL1AssetHandler
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
Name | Type | Description |
---|---|---|
_chainId | uint256 | the chainId that the message will be sent to |
_assetId | bytes32 | the assetId of the asset being bridged |
_depositSender | address | the address of the entity that initiated the deposit. |
_data | bytes | the actual data specified for the function |
IL1BaseTokenAssetHandler
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
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
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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The ZK chain id to which deposit was initiated. |
_depositSender | address | The address of the entity that initiated the deposit. |
_assetId | bytes32 | The unique identifier of the deposited L1 token. |
_assetData | bytes | The encoded transfer data, which includes both the deposit amount and the address of the L2 receiver. Might include extra information. |
_l2TxHash | bytes32 | The L2 transaction hash of the failed deposit finalization. |
_l2BatchNumber | uint256 | The L2 batch number where the deposit finalization was processed. |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_l2TxNumberInBatch | uint16 | The L2 transaction number in a batch, in which the log was sent. |
_merkleProof | bytes32[] | 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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain ID of the transaction to check |
_l2BatchNumber | uint256 | The L2 batch number where the withdrawal was processed |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message |
_l2TxNumberInBatch | uint16 | The L2 transaction number in the batch, in which the log was sent |
_message | bytes | The L2 withdraw data, stored in an L2 -> L1 message |
_merkleProof | bytes32[] | 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
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
l2BridgeAddress
function l2BridgeAddress(uint256 _chainId) external view returns (address);
IL2SharedBridgeLegacy
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
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
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
Functions
deposit
function deposit() external payable;
withdraw
function withdraw(uint256 wad) external;
Contents
IL1NativeTokenVault
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
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
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
error EthTransferFailed();
NativeTokenVaultAlreadySet
error NativeTokenVaultAlreadySet();
WrongMsgLength
error WrongMsgLength(uint256 expected, uint256 length);
ZeroAmountToTransfer
error ZeroAmountToTransfer();
WrongAmountTransferred
error WrongAmountTransferred(uint256 balance, uint256 nullifierChainBalance);
EmptyToken
error EmptyToken();
ClaimFailedDepositFailed
error ClaimFailedDepositFailed();
WrongL2Sender
error WrongL2Sender(address providedL2Sender);
WrongCounterpart
error WrongCounterpart();
Contents
- L2TransactionRequestDirect
- L2TransactionRequestTwoBridgesOuter
- L2TransactionRequestTwoBridgesInner
- BridgehubMintCTMAssetData
- BridgehubBurnCTMAssetData
- IBridgehub
- ICTMDeploymentTracker
- IChainAssetHandler
- IMessageRoot
- AlreadyCurrentSL
- ChainExists
- ChainIdAlreadyPresent
- ChainNotLegacy
- ChainNotPresentInCTM
- HyperchainNotRegistered
- IncorrectChainAssetId
- IncorrectSender
- MessageRootNotRegistered
- NoEthAllowed
- NotAssetRouter
- NotChainAssetHandler
- NotCurrentSL
- NotInGatewayMode
- NotL1
- NotOwner
- NotOwnerViaRouter
- NotRelayedSender
- OnlyBridgehub
- OnlyBridgehubOrChainAssetHandler
- OnlyChain
- SecondBridgeAddressTooLow
- SLNotWhitelisted
- WrongCounterPart
IBridgehub
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
Name | Type | Description |
---|---|---|
_newPendingAdmin | address | Address 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);
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,
address _chainAssetHandler
) external;
setChainAssetHandler
function setChainAssetHandler(address _chainAssetHandler) 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);
chainAssetHandler
function chainAssetHandler() external view returns (address);
registerAlreadyDeployedZKChain
function registerAlreadyDeployedZKChain(uint256 _chainId, address _hyperchain)
external;
registerLegacyChain
function registerLegacyChain(uint256 _chainId) external;
pauseMigration
function pauseMigration() external;
unpauseMigration
function unpauseMigration() external;
forwardedBridgeBurnSetSettlementLayer
function forwardedBridgeBurnSetSettlementLayer(
uint256 _chainId,
uint256 _newSettlementLayerChainId
) external returns (address zkChain, address ctm);
forwardedBridgeMint
function forwardedBridgeMint(
bytes32 _assetId,
uint256 _chainId,
bytes32 _baseTokenAssetId
) external returns (address zkChain, address ctm);
registerNewZKChain
function registerNewZKChain(
uint256 _chainId,
address _zkChain,
bool _checkMaxNumberOfZKChains
) external;
forwardedBridgeRecoverFailedTransfer
function forwardedBridgeRecoverFailedTransfer(uint256 _chainId)
external
returns (address zkChain, address ctm);
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
);
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
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
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;
historicalRoot
function historicalRoot(uint256 _blockNumber) external view returns (bytes32);
IChainAssetHandler
Inherits: IAssetHandler, IL1AssetHandler
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Events
MigrationStarted
Emitted when the bridging to the chain is started.
event MigrationStarted(
uint256 indexed chainId,
bytes32 indexed assetId,
uint256 indexed settlementLayerChainId
);
Parameters
Name | Type | Description |
---|---|---|
chainId | uint256 | Chain ID of the ZK chain |
assetId | bytes32 | Asset ID of the token for the zkChain's CTM |
settlementLayerChainId | uint256 | The 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
Name | Type | Description |
---|---|---|
chainId | uint256 | Chain ID of the ZK chain |
assetId | bytes32 | Asset ID of the token for the zkChain's CTM |
zkChain | address | The address of the ZK chain on the chain where it is migrated to. |
Contents
- interfaces
- l2-helpers
- libraries
- PriorityTreeCommitment
- ZKChainCommitment
- Config constants
- AccessToFallbackDenied
- AccessToFunctionDenied
- AddressAlreadySet
- AddressHasNoCode
- AddressMismatch
- AlreadyPermanentRollup
- AlreadyWhitelisted
- AmountMustBeGreaterThanZero
- AssetHandlerDoesNotExist
- AssetHandlerNotRegistered
- AssetIdAlreadyRegistered
- AssetIdMismatch
- AssetIdNotSupported
- AssetRouterAllowanceNotZero
- BaseTokenGasPriceDenominatorNotSet
- BatchHashMismatch
- BatchNotExecuted
- BatchNumberMismatch
- BridgeHubAlreadyRegistered
- BridgeMintNotImplemented
- BurningNativeWETHNotSupported
- BytecodeAlreadyPublished
- CallerNotTimerAdmin
- CallNotAllowed
- CanOnlyProcessOneBatch
- CantExecuteUnprovenBatches
- CantRevertExecutedBatch
- ChainAlreadyLive
- ChainIdAlreadyExists
- ChainIdCantBeCurrentChain
- ChainIdMismatch
- ChainIdNotRegistered
- ChainIdTooBig
- CTMAlreadyRegistered
- CTMNotRegistered
- DeadlineNotYetPassed
- DefaultAdminTransferNotAllowed
- DelegateCallFailed
- DenominatorIsZero
- DeployFailed
- DeployingBridgedTokenForNativeToken
- DepositDoesNotExist
- DepositExists
- DiamondAlreadyFrozen
- DiamondNotFrozen
- EmptyAddress
- EmptyAssetId
- EmptyBytes32
- EmptyData
- EmptyDeposit
- EmptyPrecommitData
- EmptyProofLength
- ETHDepositNotSupported
- FacetExists
- GasPerPubdataMismatch
- GenesisBatchCommitmentZero
- GenesisBatchHashZero
- GenesisIndexStorageZero
- GenesisUpgradeZero
- HashedLogIsDefault
- HashMismatch
- IncorrectBatchBounds
- IncorrectBridgeHubAddress
- IncorrectTokenAddressFromNTV
- InsufficientChainBalance
- InvalidBatchNumber
- InvalidCaller
- InvalidDAForPermanentRollup
- InvalidDelay
- InvalidLogSender
- InvalidMessageRoot
- InvalidNTVBurnData
- InvalidNumberOfBlobs
- InvalidPackedPrecommitmentLength
- InvalidProof
- InvalidProofLengthForFinalNode
- InvalidProtocolVersion
- InvalidPubdataPricingMode
- InvalidSelector
- InvalidSystemLogsLength
- InvalidUpgradeTxn
- L2TimestampTooBig
- L2WithdrawalMessageWrongLength
- LegacyBridgeNotSet
- LegacyBridgeUsesNonNativeToken
- LegacyEncodingUsedForNonL1Token
- LegacyMethodForNonL1Token
- LengthIsNotDivisibleBy32
- LogAlreadyProcessed
- MalformedBytecode
- MerkleIndexOrHeightMismatch
- MerkleIndexOutOfBounds
- MerkleNothingToProve
- MerklePathEmpty
- MerklePathLengthMismatch
- MerklePathOutOfBounds
- MerkleWrongIndex
- MerkleWrongLength
- MigrationPaused
- MigrationsNotPaused
- MissingSystemLogs
- MsgValueMismatch
- MsgValueTooLow
- NewDeadlineExceedsMaxDeadline
- NewDeadlineNotGreaterThanCurrent
- NoCallsProvided
- NoCTMForAssetId
- NoFunctionsForDiamondCut
- NoFundsTransferred
- NoLegacySharedBridge
- NonEmptyCalldata
- NonEmptyMsgValue
- NonIncreasingTimestamp
- NonSequentialBatch
- NonSequentialVersion
- NotAllowed
- NotARestriction
- NotAZKChain
- NotInitializedReentrancyGuard
- NotWhitelisted
- OnlyEraSupported
- OnlySelfAllowed
- OperationExists
- OperationMustBePending
- OperationMustBeReady
- OriginChainIdNotFound
- PrecommitmentMismatch
- PreviousOperationNotExecuted
- PriorityOperationsRollingHashMismatch
- PriorityTxPubdataExceedsMaxPubDataPerBatch
- ProtocolIdMismatch
- ProtocolIdNotGreater
- PubdataGreaterThanLimit
- QueueIsEmpty
- Reentrancy
- RemoveFunctionFacetAddressNotZero
- RemoveFunctionFacetAddressZero
- RemovingPermanentRestriction
- ReplaceFunctionFacetAddressZero
- RestrictionWasAlreadyPresent
- RestrictionWasNotPresent
- RevertedBatchNotAfterNewLastBatch
- RoleAccessDenied
- SelectorsMustAllHaveSameFreezability
- SettlementLayersMustSettleOnL1
- SharedBridgeNotSet
- SharedBridgeValueNotSet
- SlotOccupied
- SystemLogsSizeTooBig
- TimeNotReached
- TimerAlreadyStarted
- TimestampError
- TokenIsLegacy
- TokenNotLegacy
- TokenNotSupported
- TokensWithFeesNotSupported
- TooHighDeploymentNonce
- TooManyFactoryDeps
- TooMuchGas
- TransactionNotAllowed
- TxHashMismatch
- TxnBodyGasLimitNotEnoughGas
- UnallowedImplementation
- Unauthorized
- UndefinedDiamondCutAction
- UnexpectedSystemLog
- UnknownVerifierType
- UnsupportedCommitBatchEncoding
- UnsupportedEncodingVersion
- UnsupportedExecuteBatchEncoding
- UnsupportedProofBatchEncoding
- UpgradeBatchNumberIsNotZero
- ValidateTxnNotEnoughGas
- ValueMismatch
- VerifiedBatchesExceedsCommittedBatches
- WithdrawalAlreadyFinalized
- WithdrawFailed
- WrappedBaseTokenAlreadyRegistered
- WrongMagicValue
- ZeroAddress
- ZeroChainId
- ZKChainLimitReached
- SharedBridgeKey
- BytecodeError
- UpgradeTxVerifyParam
- TxStatus
- L2Log
- L2Message
- WritePriorityOpParams
- L2CanonicalTransaction
- BridgehubL2TransactionRequest
- InteropRoot
IL2ContractDeployer
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
Name | Type | Description |
---|---|---|
_salt | bytes32 | The create2 salt. |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_input | bytes | The constructor calldata. |
setAllowedBytecodeTypesToDeploy
Changes what types of bytecodes are allowed to be deployed on the chain.
function setAllowedBytecodeTypesToDeploy(
AllowedBytecodeTypes newAllowedBytecodeTypes
) external;
Parameters
Name | Type | Description |
---|---|---|
newAllowedBytecodeTypes | AllowedBytecodeTypes | The 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
Name | Type | Description |
---|---|---|
bytecodeHash | bytes32 | The bytecode hash to put on an address. |
newAddress | address | The address on which to deploy the bytecodehash to. |
callConstructor | bool | Whether to run the constructor on the force deployment. |
value | uint256 | The msg.value with which to initialize a contract. |
input | bytes | The constructor calldata. |
IL2InteropRootStorage
Author: Matter Labs
The interface of the L2 InteropRootStorage contract, responsible for storing the message roots of other chains on the L2.
Note: security-contact: security@matterlabs.dev
Functions
interopRoots
Mapping of chain ID to block or batch number to message root.
function interopRoots(uint256 chainId, uint256 blockOrBatchNumber)
external
view
returns (bytes32);
IOwnable
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
owner
function owner() external view returns (address);
transferOwnership
function transferOwnership(address newOwner) external;
pendingOwner
function pendingOwner() external view returns (address);
acceptOwnership
function acceptOwnership() external;
L2Helpers
IL2ToL1Messenger
Author: Matter Labs
The interface of the L1 Messenger contract, responsible for sending messages to L1.
by default ZkSync can send fixed-length messages on L1.
A fixed length message has 4 parameters senderAddress
, isService
, key
, value
,
the first one is taken from the context, the other three are chosen by the sender.
*To send a variable-length message we use this trick:
- This system contract accepts an arbitrary length message and sends a fixed length message with
parameters
senderAddress == this
,isService == true
,key == msg.sender
,value == keccak256(message)
. - The contract on L1 accepts all sent messages and if the message came from this system contract
it requires the preimage of
value
to be provided.*
Note: security-contact: security@matterlabs.dev
Functions
sendToL1
Sends an arbitrary length message to L1.
function sendToL1(bytes calldata _message) external returns (bytes32);
Parameters
Name | Type | Description |
---|---|---|
_message | bytes | The variable length message to be sent to L1. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | Returns the keccak256 hashed value of the message. |
sendL2ToL1Log
Sends L2ToL1Log.
Can be called only by a system contract.
function sendL2ToL1Log(bool _isService, bytes32 _key, bytes32 _value)
external
returns (uint256 logIdInMerkleTree);
Parameters
Name | Type | Description |
---|---|---|
_isService | bool | The isService flag. |
_key | bytes32 | The key part of the L2Log. |
_value | bytes32 | The value part of the L2Log. |
requestBytecodeL1Publication
This function is expected to be called only by the KnownCodesStorage system contract
function requestBytecodeL1Publication(bytes32 _bytecodeHash) external;
Events
L1MessageSent
event L1MessageSent(
address indexed _sender, bytes32 indexed _hash, bytes _message
);
L2ContractAddresses
L2ContractHelper
Author: Matter Labs
Helper library for working with L2 contracts on L1.
Note: security-contact: security@matterlabs.dev
State Variables
CREATE2_PREFIX
The prefix used to create CREATE2 addresses.
bytes32 private constant CREATE2_PREFIX = keccak256("zksyncCreate2");
CREATE_PREFIX
Prefix used during derivation of account addresses using CREATE
keccak256("zksyncCreate")
bytes32 private constant CREATE_PREFIX =
0x63bae3a9951d38e8a3fbb7b70909afc1200610fc5bc55ade242f815974674f23;
Functions
sendMessageToL1
Sends L2 -> L1 arbitrary-long message through the system contract messenger.
function sendMessageToL1(bytes memory _message) internal returns (bytes32);
Parameters
Name | Type | Description |
---|---|---|
_message | bytes | Data to be sent to L1. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | keccak256 hash of the sent message. |
hashL2Bytecode
Validate the bytecode format and calculate its hash.
function hashL2Bytecode(bytes memory _bytecode)
internal
pure
returns (bytes32 hashedBytecode);
Parameters
Name | Type | Description |
---|---|---|
_bytecode | bytes | The bytecode to hash. |
Returns
Name | Type | Description |
---|---|---|
hashedBytecode | bytes32 | The 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 |
hashL2BytecodeCalldata
Validate the bytecode format and calculate its hash.
function hashL2BytecodeCalldata(bytes calldata _bytecode)
internal
pure
returns (bytes32 hashedBytecode);
Parameters
Name | Type | Description |
---|---|---|
_bytecode | bytes | The bytecode to hash. |
Returns
Name | Type | Description |
---|---|---|
hashedBytecode | bytes32 | The 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 |
validateBytecodeHash
Validates the format of the given bytecode hash.
Due to the specification of the L2 bytecode hash, not every 32 bytes could be a legit bytecode hash.
The function reverts on invalid bytecode hash format.
function validateBytecodeHash(bytes32 _bytecodeHash) internal pure;
Parameters
Name | Type | Description |
---|---|---|
_bytecodeHash | bytes32 | The hash of the bytecode to validate. |
bytecodeLen
Returns the length of the bytecode associated with the given hash.
function bytecodeLen(bytes32 _bytecodeHash)
internal
pure
returns (uint256 codeLengthInWords);
Parameters
Name | Type | Description |
---|---|---|
_bytecodeHash | bytes32 | The hash of the bytecode. |
Returns
Name | Type | Description |
---|---|---|
codeLengthInWords | uint256 | The length of the bytecode in words. |
computeCreate2Address
Computes the create2 address for a Layer 2 contract.
function computeCreate2Address(
address _sender,
bytes32 _salt,
bytes32 _bytecodeHash,
bytes32 _constructorInputHash
) internal pure returns (address);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | The address of the sender. |
_salt | bytes32 | The salt value to use in the create2 address computation. |
_bytecodeHash | bytes32 | The contract bytecode hash. |
_constructorInputHash | bytes32 | The hash of the constructor input data. |
Returns
Name | Type | Description |
---|---|---|
<none> | address | The create2 address of the contract. NOTE: L2 create2 derivation is different from L1 derivation! |
computeCreateAddress
Calculates the address of a deployed contract via create
function computeCreateAddress(address _sender, uint256 _senderNonce)
internal
pure
returns (address);
Parameters
Name | Type | Description |
---|---|---|
_sender | address | The account that deploys the contract. |
_senderNonce | uint256 | The deploy nonce of the sender's account. NOTE: L2 create derivation is different from L1 derivation! |
hashFactoryDeps
Hashes the L2 bytecodes and returns them in the format in which they are processed by the bootloader
function hashFactoryDeps(bytes[] memory _factoryDeps)
internal
pure
returns (uint256[] memory hashedFactoryDeps);
Contents
- restriction
- Call
- IAccessControlRestriction
- IChainAdmin
- IChainAdminOwnable
- IGovernance
- IPermanentRestriction
Contents
IRestriction
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
Name | Type | Description |
---|---|---|
<none> | bytes32 | Returns 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
Name | Type | Description |
---|---|---|
_call | Call | The call data. |
_invoker | address | The address of the invoker. |
Constants
RESTRICTION_MAGIC
The magic value that has to be returned by the getSupportsRestrictionMagic
bytes32 constant RESTRICTION_MAGIC = keccak256("Restriction");
IAccessControlRestriction
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
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
Name | Type | Description |
---|---|---|
_restriction | address | The address of the restriction contract. |
addRestriction
Adds a new restriction to the active restrictions set.
function addRestriction(address _restriction) external;
Parameters
Name | Type | Description |
---|---|---|
_restriction | address | The 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
Name | Type | Description |
---|---|---|
_restriction | address | The 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
Name | Type | Description |
---|---|---|
_calls | Call[] | Array of Call structures defining target, value, and data for each call. |
_requireSuccess | bool | If 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
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
Name | Type | Description |
---|---|---|
target | address | The address to which the call will be made. |
value | uint256 | The amount of Ether (in wei) to be sent along with the call. |
data | bytes | The calldata to be executed on the target address. |
IGovernance
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
Name | Type | Description |
---|---|---|
calls | Call[] | An array of Call structs, each representing a call to be made during the operation. |
predecessor | bytes32 | The hash of the predecessor operation, that should be executed before this operation. |
salt | bytes32 | A bytes32 value used for creating unique operation hashes. |
Enums
OperationState
This enumeration includes the following states:
enum OperationState {
Unset,
Waiting,
Ready,
Done
}
IPermanentRestriction
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
- chain-deps
- chain-interfaces
- l2-deps
- libraries
- ChainTypeManagerInitializeData
- ChainCreationParams
- IChainTypeManager
- IValidatorTimelock
- AdminZero
- AlreadyMigrated
- BlobHashBlobCommitmentMismatchValue
- CommitBasedInteropNotSupported
- ContractNotDeployed
- DependencyRootsRollingHashMismatch
- ExecutedIsNotConsistentWithVerified
- InitialForceDeploymentMismatch
- InvalidBatchesDataLength
- InvalidChainId
- InvalidCommitment
- InvalidL2DAOutputHash
- InvalidNextLeafIndex
- InvalidNumberOfBatchHashes
- InvalidNumberOfBlobs
- InvalidPubdataHash
- InvalidPubdataSource
- InvalidStartIndex
- InvalidUnprocessedIndex
- L1DAValidatorAddressIsZero
- L1DAValidatorInvalidSender
- L2DAValidatorAddressIsZero
- LocalRootIsZero
- LocalRootMustBeZero
- MessageRootIsZero
- MismatchL2DAValidator
- MismatchNumberOfLayer1Txs
- NotAllBatchesExecuted
- NotChainAdmin
- NotHistoricalRoot
- NotHyperchain
- NotL1
- NotMigrated
- NotSettlementLayer
- OnlyOneBlobWithCalldataAllowed
- OperatorDAInputTooSmall
- OutdatedProtocolVersion
- ProtocolVersionNotUpToDate
- PubdataInputTooSmall
- PubdataLengthTooBig
- UnsupportedProofMetadataVersion
- ValL1DAWrongInputLength
- VerifiedIsNotConsistentWithCommitted
IValidatorTimelock
Inherits: IExecutor
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
PRECOMMITTER_ROLE
Role hash for addresses allowed to precommit batches on a chain.
function PRECOMMITTER_ROLE() external view returns (bytes32);
COMMITTER_ROLE
Role hash for addresses allowed to commit batches on a chain.
function COMMITTER_ROLE() external view returns (bytes32);
REVERTER_ROLE
Role hash for addresses allowed to revert batches on a chain.
function REVERTER_ROLE() external view returns (bytes32);
PROVER_ROLE
Role hash for addresses allowed to prove batches on a chain.
function PROVER_ROLE() external view returns (bytes32);
EXECUTOR_ROLE
Role hash for addresses allowed to execute batches on a chain.
function EXECUTOR_ROLE() external view returns (bytes32);
OPTIONAL_PRECOMMITTER_ADMIN_ROLE
Optional admin role hash for managing PRECOMMITTER_ROLE assignments.
Note, that it is optional, meaning that by default the admin role is held by the chain admin
function OPTIONAL_PRECOMMITTER_ADMIN_ROLE() external view returns (bytes32);
OPTIONAL_COMMITTER_ADMIN_ROLE
Optional admin role hash for managing COMMITTER_ROLE assignments.
Note, that it is optional, meaning that by default the admin role is held by the chain admin
function OPTIONAL_COMMITTER_ADMIN_ROLE() external view returns (bytes32);
OPTIONAL_REVERTER_ADMIN_ROLE
Optional admin role hash for managing REVERTER_ROLE assignments.
Note, that it is optional, meaning that by default the admin role is held by the chain admin
function OPTIONAL_REVERTER_ADMIN_ROLE() external view returns (bytes32);
OPTIONAL_PROVER_ADMIN_ROLE
Optional admin role hash for managing PROVER_ROLE assignments.
Note, that it is optional, meaning that by default the admin role is held by the chain admin
function OPTIONAL_PROVER_ADMIN_ROLE() external view returns (bytes32);
OPTIONAL_EXECUTOR_ADMIN_ROLE
Optional admin role hash for managing EXECUTOR_ROLE assignments.
Note, that it is optional, meaning that by default the admin role is held by the chain admin
function OPTIONAL_EXECUTOR_ADMIN_ROLE() external view returns (bytes32);
BRIDGE_HUB
The address of the bridgehub
function BRIDGE_HUB() external view returns (IBridgehub);
executionDelay
The delay between committing and executing batches.
function executionDelay() external view returns (uint32);
getName
Part of the IBase interface. Not used in this contract.
function getName() external pure returns (string memory);
initialize
Initializer for the contract.
Expected to be delegatecalled in the constructor of the TransparentUpgradeableProxy
function initialize(address _initialOwner, uint32 _initialExecutionDelay)
external;
Parameters
Name | Type | Description |
---|---|---|
_initialOwner | address | The initial owner of the Validator timelock. |
_initialExecutionDelay | uint32 | The initial execution delay, i.e. minimal time between a batch is committed and executed. |
setExecutionDelay
Set the delay between committing and executing batches.
function setExecutionDelay(uint32 _executionDelay) external;
getCommittedBatchTimestamp
Returns the timestamp when _l2BatchNumber
was committed.
function getCommittedBatchTimestamp(
address _chainAddress,
uint256 _l2BatchNumber
) external view returns (uint256);
removeValidatorRoles
Revokes the specified validator roles for a given validator on the target chain.
Note that the access control is managed by the inner revokeRole
functions.
function removeValidatorRoles(
address _chainAddress,
address _validator,
ValidatorRotationParams memory params
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address identifier of the ZK chain. |
_validator | address | The address of the validator to update. |
params | ValidatorRotationParams | Flags indicating which roles to revoke. |
removeValidator
Convenience wrapper to revoke all validator roles for a given validator on the target chain.
function removeValidator(address _chainAddress, address _validator) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address identifier of the ZK chain. |
_validator | address | The address of the validator to remove. |
removeValidatorForChainId
Convenience wrapper to revoke all validator roles for a given validator on the target chain.
function removeValidatorForChainId(uint256 _chainId, address _validator)
external;
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain Id of the ZK chain. |
_validator | address | The address of the validator to remove. |
addValidatorRoles
Grants the specified validator roles for a given validator on the target chain.
function addValidatorRoles(
address _chainAddress,
address _validator,
ValidatorRotationParams memory params
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address identifier of the ZK chain. |
_validator | address | The address of the validator to update. |
params | ValidatorRotationParams | Flags indicating which roles to grant. |
addValidator
Convenience wrapper to grant all validator roles for a given validator on the target chain.
function addValidator(address _chainAddress, address _validator) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address identifier of the ZK chain. |
_validator | address | The address of the validator to add. |
addValidatorForChainId
Convenience wrapper to grant all validator roles for a given validator on the target chain.
function addValidatorForChainId(uint256 _chainId, address _validator) external;
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain Id of the ZK chain. |
_validator | address | The address of the validator to add. |
hasRoleForChainId
Convenience wrapper to retrieve whether a certain address has a role for a chain.
function hasRoleForChainId(uint256 _chainId, bytes32 _role, address _address)
external
view
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain Id of the ZK chain. |
_role | bytes32 | The bytes32 ID of the role. |
_address | address | The address that may have the role. |
precommitSharedBridge
Make a call to the zkChain diamond contract with the same calldata.
function precommitSharedBridge(
address _chainAddress,
uint256 _l2BlockNumber,
bytes calldata _l2Block
) external;
commitBatchesSharedBridge
Records the timestamp for all provided committed batches and make a call to the zkChain diamond contract with the same calldata.
function commitBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _batchData
) external;
revertBatchesSharedBridge
Make a call to the zkChain diamond contract with the same calldata. Note: If the batch is reverted, it needs to be committed first before the execution. So it's safe to not override the committed batches.
function revertBatchesSharedBridge(address _chainAddress, uint256 _newLastBatch)
external;
proveBatchesSharedBridge
Make a call to the zkChain diamond contract with the same calldata. Note: We don't track the time when batches are proven, since all information about the batch is known on the commit stage and the proved is not finalized (may be reverted).
function proveBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _proofData
) external;
executeBatchesSharedBridge
Check that batches were committed at least X time ago and make a call to the zkChain diamond contract with the same calldata.
function executeBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _batchData
) external;
Events
NewExecutionDelay
The delay between committing and executing batches is changed.
event NewExecutionDelay(uint256 _newExecutionDelay);
Structs
ValidatorRotationParams
Struct specifying which validator roles to grant or revoke in a single call.
struct ValidatorRotationParams {
bool rotatePrecommitterRole;
bool rotateCommitterRole;
bool rotateReverterRole;
bool rotateProverRole;
bool rotateExecutorRole;
}
Properties
Name | Type | Description |
---|---|---|
rotatePrecommitterRole | bool | Whether to rotate the PRECOMMITTER_ROLE. |
rotateCommitterRole | bool | Whether to rotate the COMMITTER_ROLE. |
rotateReverterRole | bool | Whether to rotate the REVERTER_ROLE. |
rotateProverRole | bool | Whether to rotate the PROVER_ROLE. |
rotateExecutorRole | bool | Whether to rotate the EXECUTOR_ROLE. |
IChainTypeManager
Functions
BRIDGE_HUB
function BRIDGE_HUB() external view returns (address);
setPendingAdmin
function setPendingAdmin(address _newPendingAdmin) external;
acceptAdmin
function acceptAdmin() external;
getZKChain
function getZKChain(uint256 _chainId) external view returns (address);
getHyperchain
function getHyperchain(uint256 _chainId) external view returns (address);
getZKChainLegacy
function getZKChainLegacy(uint256 _chainId) external view returns (address);
storedBatchZero
function storedBatchZero() external view returns (bytes32);
initialCutHash
function initialCutHash() external view returns (bytes32);
l1GenesisUpgrade
function l1GenesisUpgrade() external view returns (address);
upgradeCutHash
function upgradeCutHash(uint256 _protocolVersion)
external
view
returns (bytes32);
protocolVersion
function protocolVersion() external view returns (uint256);
protocolVersionDeadline
function protocolVersionDeadline(uint256 _protocolVersion)
external
view
returns (uint256);
protocolVersionIsActive
function protocolVersionIsActive(uint256 _protocolVersion)
external
view
returns (bool);
getProtocolVersion
function getProtocolVersion(uint256 _chainId) external view returns (uint256);
initialize
function initialize(ChainTypeManagerInitializeData calldata _initializeData)
external;
setLegacyValidatorTimelock
function setLegacyValidatorTimelock(address _validatorTimelock) external;
setValidatorTimelockPostV29
function setValidatorTimelockPostV29(address _validatorTimelockPostV29)
external;
setChainCreationParams
function setChainCreationParams(
ChainCreationParams calldata _chainCreationParams
) external;
getChainAdmin
function getChainAdmin(uint256 _chainId) external view returns (address);
createNewChain
function createNewChain(
uint256 _chainId,
bytes32 _baseTokenAssetId,
address _admin,
bytes calldata _initData,
bytes[] calldata _factoryDeps
) external returns (address);
setNewVersionUpgrade
function setNewVersionUpgrade(
Diamond.DiamondCutData calldata _cutData,
uint256 _oldProtocolVersion,
uint256 _oldProtocolVersionDeadline,
uint256 _newProtocolVersion
) external;
setUpgradeDiamondCut
function setUpgradeDiamondCut(
Diamond.DiamondCutData calldata _cutData,
uint256 _oldProtocolVersion
) external;
executeUpgrade
function executeUpgrade(
uint256 _chainId,
Diamond.DiamondCutData calldata _diamondCut
) external;
setPriorityTxMaxGasLimit
function setPriorityTxMaxGasLimit(uint256 _chainId, uint256 _maxGasLimit)
external;
freezeChain
function freezeChain(uint256 _chainId) external;
unfreezeChain
function unfreezeChain(uint256 _chainId) external;
setTokenMultiplier
function setTokenMultiplier(
uint256 _chainId,
uint128 _nominator,
uint128 _denominator
) external;
changeFeeParams
function changeFeeParams(uint256 _chainId, FeeParams calldata _newFeeParams)
external;
setValidator
function setValidator(uint256 _chainId, address _validator, bool _active)
external;
setPorterAvailability
function setPorterAvailability(uint256 _chainId, bool _zkPorterIsAvailable)
external;
upgradeChainFromVersion
function upgradeChainFromVersion(
uint256 _chainId,
uint256 _oldProtocolVersion,
Diamond.DiamondCutData calldata _diamondCut
) external;
getSemverProtocolVersion
function getSemverProtocolVersion()
external
view
returns (uint32, uint32, uint32);
forwardedBridgeBurn
function forwardedBridgeBurn(uint256 _chainId, bytes calldata _data)
external
returns (bytes memory _bridgeMintData);
forwardedBridgeMint
function forwardedBridgeMint(uint256 _chainId, bytes calldata _data)
external
returns (address);
forwardedBridgeRecoverFailedTransfer
function forwardedBridgeRecoverFailedTransfer(
uint256 _chainId,
bytes32 _assetInfo,
address _depositSender,
bytes calldata _ctmData
) external;
Events
NewZKChain
Emitted when a new ZKChain is added
event NewZKChain(uint256 indexed _chainId, address indexed _zkChainContract);
GenesisUpgrade
emitted when an chain registers and a GenesisUpgrade happens
event GenesisUpgrade(
address indexed _zkChain,
L2CanonicalTransaction _l2Transaction,
uint256 indexed _protocolVersion
);
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);
NewValidatorTimelock
ValidatorTimelock changed
event NewValidatorTimelock(
address indexed oldValidatorTimelock, address indexed newValidatorTimelock
);
NewValidatorTimelockPostV29
ValidatorTimelockPostV29 changed
event NewValidatorTimelockPostV29(
address indexed oldValidatorTimelockPostV29,
address indexed newvalidatorTimelockPostV29
);
NewServerNotifier
ServerNotifier changed
event NewServerNotifier(
address indexed oldServerNotifier, address indexed newServerNotifier
);
NewChainCreationParams
chain creation parameters changed
event NewChainCreationParams(
address genesisUpgrade,
bytes32 genesisBatchHash,
uint64 genesisIndexRepeatedStorageChanges,
bytes32 genesisBatchCommitment,
Diamond.DiamondCutData newInitialCut,
bytes32 newInitialCutHash,
bytes forceDeploymentsData,
bytes32 forceDeploymentHash
);
NewUpgradeCutHash
New UpgradeCutHash
event NewUpgradeCutHash(
uint256 indexed protocolVersion, bytes32 indexed upgradeCutHash
);
NewUpgradeCutData
New UpgradeCutData
event NewUpgradeCutData(
uint256 indexed protocolVersion, Diamond.DiamondCutData diamondCutData
);
NewProtocolVersion
New ProtocolVersion
event NewProtocolVersion(
uint256 indexed oldProtocolVersion, uint256 indexed newProtocolVersion
);
UpdateProtocolVersionDeadline
Updated ProtocolVersion deadline
event UpdateProtocolVersionDeadline(
uint256 indexed protocolVersion, uint256 deadline
);
L1StateTransitionErrors
Contents
- IAdmin
- InitializeData
- InitializeDataNewChain
- IDiamondInit
- SystemLogKey
- LogProcessingOutput
- IExecutor
- IExecutor constants
- IGetters
- PubdataSource
- L1DAValidatorOutput
- IL1DAValidator
- ILegacyGetters
- IMailbox
- IMailboxImpl
- IMessageVerification
- ITransactionFilterer
- VerifierParams
- IVerifier
- IVerifierV2
- IZKChain
- IZKChainBase
IAdmin
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
Name | Type | Description |
---|---|---|
_newPendingAdmin | address | Address 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
Name | Type | Description |
---|---|---|
_validator | address | Validator address |
_active | bool | Active flag |
setPorterAvailability
Change zk porter availability
function setPorterAvailability(bool _zkPorterIsAvailable) external;
Parameters
Name | Type | Description |
---|---|---|
_zkPorterIsAvailable | bool | The availability of zk porter shard |
setPriorityTxMaxGasLimit
Change the max L2 gas limit for L1 -> L2 transactions
function setPriorityTxMaxGasLimit(uint256 _newPriorityTxMaxGasLimit) external;
Parameters
Name | Type | Description |
---|---|---|
_newPriorityTxMaxGasLimit | uint256 | The 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
Name | Type | Description |
---|---|---|
_newFeeParams | FeeParams | The 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
Name | Type | Description |
---|---|---|
_pricingMode | PubdataPricingMode | The 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
Name | Type | Description |
---|---|---|
_protocolVersion | uint256 | The current protocol version from which upgrade is executed |
_cutData | Diamond.DiamondCutData | The 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
Name | Type | Description |
---|---|---|
_diamondCut | Diamond.DiamondCutData | The 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;
getRollupDAManager
Returns address of the RollupDAManager of the ZK Chain.
function getRollupDAManager() external view returns (address);
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
Name | Type | Description |
---|---|---|
_l1DAValidator | address | The address of the L1 DA validator |
_l2DAValidator | address | The 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
Functions
initialize
function initialize(InitializeData calldata _initData)
external
returns (bytes32);
IExecutor
Inherits: IZKChainBase
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
precommitSharedBridge
Precommits the status of all L2 transactions for the next batch on the shared bridge.
function precommitSharedBridge(
address _chainAddress,
uint256 _batchNumber,
bytes calldata _precommitData
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address of the DiamondProxy of the chain. Note, that it is not used in the implementation, because it is expected to be equal to the address(this) , but it is kept here to maintain the same interface on both ValidatorTimelock and Executor for easier and cheaper implementation of the timelock. |
_batchNumber | uint256 | The sequential batch number to precommit (must equal s.totalBatchesCommitted + 1 ). |
_precommitData | bytes | ABI‐encoded transaction status list for the precommit. |
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(
address _chainAddress,
uint256 _processFrom,
uint256 _processTo,
bytes calldata _commitData
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address of the DiamondProxy of the chain. Note, that it is not used in the implementation, because it is expected to be equal to the address(this) , but it is kept here to maintain the same interface on both ValidatorTimelock and Executor for easier and cheaper implementation of the timelock. |
_processFrom | uint256 | The batch number from which the processing starts. |
_processTo | uint256 | The batch number at which the processing ends. |
_commitData | bytes | The encoded data of the new batches to be committed. |
proveBatchesSharedBridge
Batches commitment verification.
Only verifies batch commitments without any other processing.
function proveBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _proofData
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address of the DiamondProxy of the chain. Note, that it is not used in the implementation, because it is expected to be equal to the address(this) , but it is kept here to maintain the same interface on both ValidatorTimelock and Executor for easier and cheaper implementation of the timelock. |
_processBatchFrom | uint256 | The batch number from which the verification starts. |
_processBatchTo | uint256 | The batch number at which the verification ends. |
_proofData | bytes | The 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(
address _chainAddress,
uint256 _processFrom,
uint256 _processTo,
bytes calldata _executeData
) external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address of the DiamondProxy of the chain. Note, that it is not used in the implementation, because it is expected to be equal to the address(this) , but it is kept here to maintain the same interface on both ValidatorTimelock and Executor for easier and cheaper implementation of the timelock. |
_processFrom | uint256 | The batch number from which the execution starts. |
_processTo | uint256 | The batch number at which the execution ends. |
_executeData | bytes | The encoded data of the new batches to be executed. |
revertBatchesSharedBridge
Reverts unexecuted batches
When the _newLastBatch is equal to the number of committed batches, only the precommitment is erased. NOTE: Doesn't delete the stored data about batches, but only decreases counters that are responsible for the number of batches
function revertBatchesSharedBridge(address _chainAddress, uint256 _newLastBatch)
external;
Parameters
Name | Type | Description |
---|---|---|
_chainAddress | address | The address of the DiamondProxy of the chain. |
_newLastBatch | uint256 | batch number after which batches should be reverted |
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
Name | Type | Description |
---|---|---|
batchNumber | uint256 | Number of the batch committed |
batchHash | bytes32 | Hash of the L2 batch |
commitment | bytes32 | Calculated 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
Name | Type | Description |
---|---|---|
previousLastVerifiedBatch | uint256 | Batch number of the previous last verified batch |
currentLastVerifiedBatch | uint256 | Batch 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
Name | Type | Description |
---|---|---|
batchNumber | uint256 | Number of the batch executed |
batchHash | bytes32 | Hash of the L2 batch |
commitment | bytes32 | Verified 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
Name | Type | Description |
---|---|---|
totalBatchesCommitted | uint256 | Total number of committed batches after the revert |
totalBatchesVerified | uint256 | Total number of verified batches after the revert |
totalBatchesExecuted | uint256 | Total number of executed batches |
BatchPrecommitmentSet
Emitted when a new precommitment is set for a batch.
event BatchPrecommitmentSet(
uint256 indexed batchNumber,
uint256 indexed untrustedLastL2BlockNumberHint,
bytes32 precommitment
);
Parameters
Name | Type | Description |
---|---|---|
batchNumber | uint256 | The batch number for which the precommitment was recorded. |
untrustedLastL2BlockNumberHint | uint256 | The hint to what L2 block number the precommitment should correspond to. Note, that there are no guarantees on its correctness, it is just a way for the server to make external nodes' indexing simpler. |
precommitment | bytes32 | The resulting rolling hash of all transaction statuses. |
Structs
StoredBatchInfo
Rollup batch stored data
struct StoredBatchInfo {
uint64 batchNumber;
bytes32 batchHash;
uint64 indexRepeatedStorageChanges;
uint256 numberOfLayer1Txs;
bytes32 priorityOperationsHash;
bytes32 dependencyRootsRollingHash;
bytes32 l2LogsTreeRoot;
uint256 timestamp;
bytes32 commitment;
}
Properties
Name | Type | Description |
---|---|---|
batchNumber | uint64 | Rollup batch number |
batchHash | bytes32 | Hash of L2 batch |
indexRepeatedStorageChanges | uint64 | The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more |
numberOfLayer1Txs | uint256 | Number of priority operations to be processed |
priorityOperationsHash | bytes32 | Hash of all priority operations from this batch |
dependencyRootsRollingHash | bytes32 | |
l2LogsTreeRoot | bytes32 | Root hash of tree that contains L2 -> L1 messages from this batch |
timestamp | uint256 | Rollup batch timestamp, have the same format as Ethereum batch constant |
commitment | bytes32 | Verified input for the ZKsync circuit |
LegacyStoredBatchInfo
Legacy StoredBatchInfo struct
dependencyRootsRollingHash is not included in the struct
struct LegacyStoredBatchInfo {
uint64 batchNumber;
bytes32 batchHash;
uint64 indexRepeatedStorageChanges;
uint256 numberOfLayer1Txs;
bytes32 priorityOperationsHash;
bytes32 l2LogsTreeRoot;
uint256 timestamp;
bytes32 commitment;
}
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
Name | Type | Description |
---|---|---|
batchNumber | uint64 | Number of the committed batch |
timestamp | uint64 | Unix timestamp denoting the start of the batch execution |
indexRepeatedStorageChanges | uint64 | The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more |
newStateRoot | bytes32 | The state root of the full state tree |
numberOfLayer1Txs | uint256 | Number of priority operations to be processed |
priorityOperationsHash | bytes32 | Hash of all priority operations from this batch |
bootloaderHeapInitialContentsHash | bytes32 | Hash of the initial contents of the bootloader heap. In practice it serves as the commitment to the transactions in the batch. |
eventsQueueStateHash | bytes32 | Hash of the events queue state. In practice it serves as the commitment to the events in the batch. |
systemLogs | bytes | concatenation of all L2 -> L1 system logs in the batch |
operatorDAInput | bytes | Packed pubdata commitments/data. |
PrecommitInfo
Container for a list of transaction statuses to precommit.
struct PrecommitInfo {
bytes packedTxsCommitments;
uint256 untrustedLastL2BlockNumberHint;
}
Properties
Name | Type | Description |
---|---|---|
packedTxsCommitments | bytes | |
untrustedLastL2BlockNumberHint | uint256 | The "hint" for what the last L2 block number that these txs represent is. |
Constants
MAX_LOG_KEY
Maximal value that SystemLogKey variable can have.
uint256 constant MAX_LOG_KEY = uint256(type(SystemLogKey).max);
L2_LOG_ADDRESS_OFFSET
Offset used to pull Address From Log. Equal to 4 (bytes for shardId, isService and txNumberInBatch)
uint256 constant L2_LOG_ADDRESS_OFFSET = 4;
L2_LOG_KEY_OFFSET
Offset used to pull Key From Log. Equal to 4 (bytes for shardId, isService and txNumberInBatch) + 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 shardId, isService and txNumberInBatch) + 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
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
Name | Type | Description |
---|---|---|
<none> | address | The address of the verifier smart contract |
getAdmin
function getAdmin() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The address of the current admin |
getPendingAdmin
function getPendingAdmin() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The address of the pending admin |
getBridgehub
function getBridgehub() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The address of the bridgehub |
getChainTypeManager
function getChainTypeManager() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The address of the state transition |
getChainId
function getChainId() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The chain ID |
getBaseToken
function getBaseToken() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The address of the base token |
getBaseTokenAssetId
function getBaseTokenAssetId() external view returns (bytes32);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The address of the base token |
getTotalBatchesCommitted
function getTotalBatchesCommitted() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of batches that were committed |
getTotalBatchesVerified
function getTotalBatchesVerified() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of batches that were committed & verified |
getTotalBatchesExecuted
function getTotalBatchesExecuted() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of batches that were committed & verified & executed |
getTransactionFilterer
function getTransactionFilterer() external view returns (address);
getTotalPriorityTxs
function getTotalPriorityTxs() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of priority operations that were added to the priority queue, including all processed ones |
getPriorityTreeStartIndex
function getPriorityTreeStartIndex() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | The root hash of the priority tree |
isPriorityQueueActive
function isPriorityQueueActive() external view returns (bool);
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
<none> | uint256 | Index of the oldest priority operation that wasn't processed yet |
getPriorityQueueSize
function getPriorityQueueSize() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The number of priority operations currently in the queue |
isValidator
function isValidator(address _address) external view returns (bool);
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether the address has a validator access |
l2LogsRootHash
function l2LogsRootHash(uint256 _batchNumber)
external
view
returns (bytes32 merkleRoot);
Returns
Name | Type | Description |
---|---|---|
merkleRoot | bytes32 | Merkle 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | The hash of committed L2 batch. |
getL2BootloaderBytecodeHash
function getL2BootloaderBytecodeHash() external view returns (bytes32);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | Bytecode hash of bootloader program. |
getL2DefaultAccountBytecodeHash
function getL2DefaultAccountBytecodeHash() external view returns (bytes32);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | Bytecode hash of default account (bytecode for EOA). |
getL2EvmEmulatorBytecodeHash
function getL2EvmEmulatorBytecodeHash() external view returns (bytes32);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | Bytecode hash of EVM emulator. |
getVerifierParams
This function is deprecated and will soon be removed.
function getVerifierParams() external view returns (VerifierParams memory);
Returns
Name | Type | Description |
---|---|---|
<none> | VerifierParams | Verifier parameters. |
isDiamondStorageFrozen
function isDiamondStorageFrozen() external view returns (bool);
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether the diamond is frozen or not |
getProtocolVersion
function getProtocolVersion() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The current packed protocol version. To access human-readable version, use getSemverProtocolVersion function. |
getSemverProtocolVersion
function getSemverProtocolVersion()
external
view
returns (uint32, uint32, uint32);
Returns
Name | Type | Description |
---|---|---|
<none> | uint32 | The tuple of (major, minor, patch) protocol version. |
<none> | uint32 | |
<none> | uint32 |
getL2SystemContractsUpgradeTxHash
function getL2SystemContractsUpgradeTxHash() external view returns (bytes32);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The L2 batch number in which the upgrade transaction was processed. |
getPriorityTxMaxGasLimit
function getPriorityTxMaxGasLimit() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
_l2BatchNumber | uint256 | The L2 batch number within which the withdrawal happened. |
_l2MessageIndex | uint256 | The index of the L2->L1 message denoting the withdrawal. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether a withdrawal has been finalized. |
getPubdataPricingMode
function getPubdataPricingMode() external view returns (PubdataPricingMode);
Returns
Name | Type | Description |
---|---|---|
<none> | PubdataPricingMode | The pubdata pricing mode. |
baseTokenGasPriceMultiplierNominator
function baseTokenGasPriceMultiplierNominator() external view returns (uint128);
Returns
Name | Type | Description |
---|---|---|
<none> | uint128 | the baseTokenGasPriceMultiplierNominator, used to compare the baseTokenPrice to ether for L1->L2 transactions |
baseTokenGasPriceMultiplierDenominator
function baseTokenGasPriceMultiplierDenominator()
external
view
returns (uint128);
Returns
Name | Type | Description |
---|---|---|
<none> | uint128 | the baseTokenGasPriceMultiplierDenominator, used to compare the baseTokenPrice to ether for L1->L2 transactions |
facets
function facets() external view returns (Facet[] memory);
Returns
Name | Type | Description |
---|---|---|
<none> | Facet[] | result All facet addresses and their function selectors |
facetFunctionSelectors
function facetFunctionSelectors(address _facet)
external
view
returns (bytes4[] memory);
Returns
Name | Type | Description |
---|---|---|
<none> | bytes4[] | NON-sorted array with function selectors supported by a specific facet |
facetAddresses
function facetAddresses() external view returns (address[] memory facets);
Returns
Name | Type | Description |
---|---|---|
facets | address[] | NON-sorted array of facet addresses supported on diamond |
facetAddress
function facetAddress(bytes4 _selector) external view returns (address facet);
Returns
Name | Type | Description |
---|---|---|
facet | address | The 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
Name | Type | Description |
---|---|---|
<none> | bool | Whether the selector can be frozen by the admin or always accessible |
isFacetFreezable
function isFacetFreezable(address _facet)
external
view
returns (bool isFreezable);
Returns
Name | Type | Description |
---|---|---|
isFreezable | bool | Whether the facet can be frozen by the admin or always accessible |
getSettlementLayer
function getSettlementLayer() external view returns (address);
Returns
Name | Type | Description |
---|---|---|
<none> | address | The 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
Name | Type | Description |
---|---|---|
addr | address | The address of the facet contract |
selectors | bytes4[] | The NON-sorted array with selectors associated with facet |
IL1DAValidator
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
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain id of the chain that is being committed. |
_batchNumber | uint256 | The batch number for which the data availability is being checked. |
_l2DAValidatorOutputHash | bytes32 | The hash of that was returned by the l2DAValidator. |
_operatorDAInput | bytes | The DA input by the operator provided on L1. |
_maxBlobsSupported | uint256 | The 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
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
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of batches that were committed |
getTotalBlocksVerified
It is a deprecated method, please use getTotalBatchesVerified
instead.
function getTotalBlocksVerified() external view returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The L2 batch number in which the upgrade transaction was processed. |
IMailbox
Inherits: IMessageVerification, IMailboxImpl
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
ITransactionFilterer
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
Name | Type | Description |
---|---|---|
sender | address | The sender of the transaction |
contractL2 | address | The L2 receiver address |
mintValue | uint256 | The value of the L1 transaction |
l2Value | uint256 | The msg.value of the L2 transaction |
l2Calldata | bytes | The calldata of the L2 transaction |
refundRecipient | address | The address to refund the excess value |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether the transaction is allowed |
IVerifier
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
Name | Type | Description |
---|---|---|
<none> | bool | A 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | vkHash The keccak256 hash of the loaded verification keys. |
IVerifierV2
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
Name | Type | Description |
---|---|---|
<none> | bool | A 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | vkHash The keccak256 hash of the loaded verification keys. |
IZKChain
Inherits: IAdmin, IExecutor, IGetters, IMailbox
Events
ProposeTransparentUpgrade
event ProposeTransparentUpgrade(
Diamond.DiamondCutData diamondCut,
uint256 indexed proposalId,
bytes32 proposalSalt
);
IZKChainBase
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
getName
function getName() external view returns (string memory);
Returns
Name | Type | Description |
---|---|---|
<none> | string | Returns facet name. |
IMailboxImpl
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
Name | Type | Description |
---|---|---|
_batchNumber | uint256 | The executed L2 batch number in which the message appeared. |
_index | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_message | L2Message | Information about the sent message: sender address, the message itself, tx index in the L2 batch where the message was sent. |
_proof | bytes32[] | Merkle proof for inclusion of L2 log that was sent with the message. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Boolean specifying whether 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 calldata _log,
bytes32[] calldata _proof
) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_batchNumber | uint256 | The executed L2 batch number in which the log appeared. |
_index | uint256 | The position of the l2log in the L2 logs Merkle tree. |
_log | L2Log | Information about the sent log. |
_proof | bytes32[] | Merkle proof for inclusion of the L2 log. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
_l2TxHash | bytes32 | The L2 canonical transaction hash. |
_l2BatchNumber | uint256 | The L2 batch number where the transaction was processed. |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_l2TxNumberInBatch | uint16 | The L2 transaction number in the batch, in which the log was sent. |
_merkleProof | bytes32[] | The Merkle proof of the processing L1 -> L2 transaction. |
_status | TxStatus | The execution status of the L1 -> L2 transaction (true - success & 0 - fail). |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
_l2BatchNumber | uint256 | The L2 batch number where the withdrawal was processed. |
_l2MessageIndex | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_l2TxNumberInBatch | uint16 | The L2 transaction number in a batch, in which the log was sent. |
_message | bytes | The L2 withdraw data, stored in an L2 -> L1 message. |
_merkleProof | bytes32[] | 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 toaddress(0)
and the sender has NO deployed bytecode on L1, the refund will be sent to themsg.sender
address. - If
_refundRecipient
is set toaddress(0)
and the sender has deployed bytecode on L1, the refund will be sent to the aliasedmsg.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
Name | Type | Description |
---|---|---|
_contractL2 | address | The L2 receiver address. |
_l2Value | uint256 | msg.value of L2 transaction. |
_calldata | bytes | The input of the L2 transaction. |
_l2GasLimit | uint256 | Maximum amount of L2 gas that transaction can consume during execution on L2. |
_l2GasPerPubdataByteLimit | uint256 | The maximum amount L2 gas that the operator may charge the user for single byte of pubdata. |
_factoryDeps | bytes[] | An array of L2 bytecodes that will be marked as known on L2. |
_refundRecipient | address | The address on L2 that will receive the refund for the transaction. |
Returns
Name | Type | Description |
---|---|---|
canonicalTxHash | bytes32 | The hash of the requested L2 transaction. This hash can be used to follow the transaction status. |
bridgehubRequestL2Transaction
Request execution of L2 transaction through the Bridgehub.
Only accessible from L1, this is getting checked in the Bridgehub.
function bridgehubRequestL2Transaction(
BridgehubL2TransactionRequest calldata _request
) external returns (bytes32 canonicalTxHash);
Parameters
Name | Type | Description |
---|---|---|
_request | BridgehubL2TransactionRequest | the request for the L2 transaction. |
bridgehubRequestL2TransactionOnGateway
The chain's mailbox receives the tx from the Bridgehub on Gateway.
function bridgehubRequestL2TransactionOnGateway(
bytes32 _canonicalTxHash,
uint64 _expirationTimestamp
) external;
Parameters
Name | Type | Description |
---|---|---|
_canonicalTxHash | bytes32 | the canonical transaction hash. |
_expirationTimestamp | uint64 | the expiration timestamp for the transaction. |
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
Name | Type | Description |
---|---|---|
_contractL2 | address | The L2 receiver address. |
_l2Calldata | bytes | The input of the L2 transaction. |
requestL2TransactionToGatewayMailbox
On L1 we have to forward to the Gateway's mailbox which sends to the Bridgehub on the Gateway.
function requestL2TransactionToGatewayMailbox(
uint256 _chainId,
bytes32 _canonicalTxHash,
uint64 _expirationTimestamp
) external returns (bytes32 canonicalTxHash);
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | the chainId of the chain. |
_canonicalTxHash | bytes32 | the canonical transaction hash. |
_expirationTimestamp | uint64 | the 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
Name | Type | Description |
---|---|---|
_gasPrice | uint256 | expected L1 gas price at which the user requests the transaction execution. |
_l2GasLimit | uint256 | Maximum amount of L2 gas that transaction can consume during execution on L2. |
_l2GasPerPubdataByteLimit | uint256 | The maximum amount of L2 gas that the operator may charge the user for a single byte of pubdata. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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 _leafProofMask,
bytes32 _leaf,
bytes32[] calldata _proof
) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_batchNumber | uint256 | The batch number of the leaf to be proven. |
_leafProofMask | uint256 | The leaf proof mask. |
_leaf | bytes32 | The leaf to be proven. |
_proof | bytes32[] | The proof. |
Events
NewPriorityRequest
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
Name | Type | Description |
---|---|---|
txId | uint256 | Serial number of the priority operation. |
txHash | bytes32 | keccak256 hash of encoded transaction representation. |
expirationTimestamp | uint64 | Timestamp up to which priority request should be processed. |
transaction | L2CanonicalTransaction | The whole transaction structure that is requested to be executed on L2. |
factoryDeps | bytes[] | 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
Name | Type | Description |
---|---|---|
txId | uint256 | Serial number of the priority operation. |
txHash | bytes32 | keccak256 hash of encoded transaction representation. |
expirationTimestamp | uint64 | Timestamp up to which priority request should be processed. |
IMessageVerification
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
proveL2MessageInclusionShared
Prove that a specific arbitrary-length message was sent in a specific L2 batch/block number.
function proveL2MessageInclusionShared(
uint256 _chainId,
uint256 _blockOrBatchNumber,
uint256 _index,
L2Message calldata _message,
bytes32[] calldata _proof
) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain id of the L2 where the message comes from. |
_blockOrBatchNumber | uint256 | The executed L2 batch/block number in which the message appeared. |
_index | uint256 | The position in the L2 logs Merkle tree of the l2Log that was sent with the message. |
_message | L2Message | Information about the sent message: sender address, the message itself, tx index in the L2 batch where the message was sent. |
_proof | bytes32[] | Merkle proof for inclusion of L2 log that was sent with the message. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Boolean specifying whether the proof is valid. |
proveL2LogInclusionShared
Prove that a specific L2 log was sent in a specific L2 batch.
function proveL2LogInclusionShared(
uint256 _chainId,
uint256 _blockOrBatchNumber,
uint256 _index,
L2Log calldata _log,
bytes32[] calldata _proof
) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain id of the L2 where the log comes from. |
_blockOrBatchNumber | uint256 | The executed L2 batch/block number in which the log appeared. |
_index | uint256 | The position of the l2log in the L2 logs Merkle tree. |
_log | L2Log | Information about the sent log. |
_proof | bytes32[] | Merkle proof for inclusion of the L2 log. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether the proof is correct and L2 log is included in batch. |
proveL2LeafInclusionShared
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 proveL2LeafInclusionShared(
uint256 _chainId,
uint256 _blockOrBatchNumber,
uint256 _leafProofMask,
bytes32 _leaf,
bytes32[] calldata _proof
) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_chainId | uint256 | The chain id of the L2 where the leaf comes from. |
_blockOrBatchNumber | uint256 | The batch/block number of the leaf to be proven. |
_leafProofMask | uint256 | The leaf proof mask. |
_leaf | bytes32 | The leaf to be proven. |
_proof | bytes32[] | The proof. |
Contents
- IComplexUpgrader
- IL2GatewayUpgrade
- ForceDeployment
- ZKChainSpecificForceDeploymentsData
- FixedForceDeploymentsData
- IL2GenesisUpgrade
- ISystemContext
IComplexUpgrader
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
Functions
upgrade
function upgrade(
IL2ContractDeployer.ForceDeployment[] calldata _forceDeployments,
address _ctmDeployer,
bytes calldata _fixedForceDeploymentsData,
bytes calldata _additionalForceDeploymentsData
) external payable;
IL2GenesisUpgrade
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
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
setChainId
function setChainId(uint256 _newChainId) external;
Contents
AddressAliasHelper
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
Name | Type | Description |
---|---|---|
l1Address | address | the address in the L1 that triggered the tx to L2 |
Returns
Name | Type | Description |
---|---|---|
l2Address | address | L2 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
Name | Type | Description |
---|---|---|
l2Address | address | L2 address as viewed in msg.sender |
Returns
Name | Type | Description |
---|---|---|
l1Address | address | the 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
Name | Type | Description |
---|---|---|
_refundRecipient | address | the address that should receive the refund |
_originalCaller | address | the address that triggered the tx to L2 |
Returns
Name | Type | Description |
---|---|---|
_recipient | address | the corrected address that should receive the refund |
Contents
- data-availability
- errors
- interfaces
- vendor
- IL1Messenger
- IContractDeployer
- IBaseToken
- ICompressor
- IPubdataChunkPublisher
- L2ContractHelper
- Transaction
- L2ContractHelper constants
- CalldataForwardingMode
- U32CastOverflow
- Utils
- SystemContractsCaller
- SystemContractsCaller constants
Contents
- IConsensusRegistry
- ForceDeployment
- IContractDeployer
- IL2DAValidator
- ExecutionResult
- IPaymaster
- IPaymaster constants
- IPaymasterFlow
IConsensusRegistry
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
add
Adds a new validator to the registry.
Fails if validator owner already exists.
Fails if a validator with the same public key already exists.
function add(
address _validatorOwner,
bool _validatorIsLeader,
uint32 _validatorWeight,
BLS12_381PublicKey calldata _validatorPubKey,
BLS12_381Signature calldata _validatorPoP
) external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the validator's owner. |
_validatorIsLeader | bool | Flag indicating if the validator is a leader. |
_validatorWeight | uint32 | The voting weight of the validator. |
_validatorPubKey | BLS12_381PublicKey | The BLS12-381 public key of the validator. |
_validatorPoP | BLS12_381Signature | The proof-of-possession (PoP) of the validator's public key. |
remove
Removes a validator from the registry.
Only callable by the contract owner.
Verifies that the validator owner exists in the registry.
function remove(address _validatorOwner) external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the owner of the validator to be removed. |
changeValidatorActive
Changes the active status of a validator, determining whether it can participate in committees.
Only callable by the contract owner or the validator owner.
Verifies that the validator owner exists in the registry.
function changeValidatorActive(address _validatorOwner, bool _isActive)
external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the owner of the validator whose active status will be changed. |
_isActive | bool | The new active status to assign to the validator. |
changeValidatorLeader
Changes the validator's leader status in the registry.
Only callable by the contract owner.
Verifies that the validator owner exists in the registry.
function changeValidatorLeader(address _validatorOwner, bool _isLeader)
external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the owner of the validator whose leader status will be changed. |
_isLeader | bool | The new leader status to assign to the validator. |
changeValidatorWeight
Changes the validator weight of a validator in the registry.
Only callable by the contract owner.
Verifies that the validator owner exists in the registry.
function changeValidatorWeight(address _validatorOwner, uint32 _weight)
external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the owner of the validator whose weight will be changed. |
_weight | uint32 | The new validator weight to assign to the validator. |
changeValidatorKey
Changes the validator's public key and proof-of-possession in the registry.
Only callable by the contract owner or the validator owner.
Verifies that the validator owner exists in the registry.
function changeValidatorKey(
address _validatorOwner,
BLS12_381PublicKey calldata _pubKey,
BLS12_381Signature calldata _pop
) external;
Parameters
Name | Type | Description |
---|---|---|
_validatorOwner | address | The address of the owner of the validator whose key and PoP will be changed. |
_pubKey | BLS12_381PublicKey | The new BLS12-381 public key to assign to the validator. |
_pop | BLS12_381Signature | The new proof-of-possession (PoP) to assign to the validator. |
commitValidatorCommittee
Adds a new commit to the validator committee using the current block number plus delay.
The committee will become active after committeeActivationDelay blocks.
Only callable by the contract owner.
Reverts if validatorsCommitBlock is still in the future.
function commitValidatorCommittee() external;
getValidatorCommittee
Returns an array of ValidatorAttr
structs representing the current validator committee and the current leader selection configuration.
Collects active and non-removed validators based on the latest commit to the committee.
function getValidatorCommittee()
external
view
returns (CommitteeValidator[] memory, LeaderSelectionAttr memory);
getNextValidatorCommittee
Returns an array of ValidatorAttr
structs representing the pending validator committee and the pending leader selection configuration.
Collects active and non-removed validators that will form the next committee after the current commit becomes active.
Reverts if there is no pending committee (when block.number >= validatorsCommitBlock).
function getNextValidatorCommittee()
external
view
returns (CommitteeValidator[] memory, LeaderSelectionAttr memory);
setCommitteeActivationDelay
Updates the delay for committee activation
Only callable by the contract owner
function setCommitteeActivationDelay(uint256 _delay) external;
Parameters
Name | Type | Description |
---|---|---|
_delay | uint256 | The new delay in blocks |
updateLeaderSelection
Updates the leader selection configuration
Only callable by the contract owner
function updateLeaderSelection(uint64 _frequency, bool _weighted) external;
Parameters
Name | Type | Description |
---|---|---|
_frequency | uint64 | The number of views between leader changes. If it is 0 then the leader never rotates. |
_weighted | bool | Whether leaders are selected proportionally to their weight. If false, then the leader is selected round-robin. |
Events
ValidatorAdded
event ValidatorAdded(
address indexed validatorOwner,
uint32 validatorWeight,
BLS12_381PublicKey validatorPubKey,
BLS12_381Signature validatorPoP
);
ValidatorRemoved
event ValidatorRemoved(address indexed validatorOwner);
ValidatorDeleted
event ValidatorDeleted(address indexed validatorOwner);
ValidatorActiveStatusChanged
event ValidatorActiveStatusChanged(
address indexed validatorOwner, bool isActive
);
ValidatorLeaderStatusChanged
event ValidatorLeaderStatusChanged(
address indexed validatorOwner, bool isLeader
);
ValidatorWeightChanged
event ValidatorWeightChanged(address indexed validatorOwner, uint32 newWeight);
ValidatorKeyChanged
event ValidatorKeyChanged(
address indexed validatorOwner,
BLS12_381PublicKey newPubKey,
BLS12_381Signature newPoP
);
ValidatorsCommitted
event ValidatorsCommitted(
uint32 validatorsCommit, uint256 validatorsCommitBlock
);
CommitteeActivationDelayChanged
event CommitteeActivationDelayChanged(uint256 newDelay);
LeaderSelectionChanged
event LeaderSelectionChanged(LeaderSelectionAttr newLeaderSelection);
Errors
UnauthorizedOnlyOwnerOrValidatorOwner
error UnauthorizedOnlyOwnerOrValidatorOwner();
ValidatorOwnerExists
error ValidatorOwnerExists();
ValidatorOwnerDoesNotExist
error ValidatorOwnerDoesNotExist();
ValidatorOwnerNotFound
error ValidatorOwnerNotFound();
ValidatorPubKeyExists
error ValidatorPubKeyExists();
InvalidInputValidatorOwnerAddress
error InvalidInputValidatorOwnerAddress();
InvalidInputBLS12_381PublicKey
error InvalidInputBLS12_381PublicKey();
InvalidInputBLS12_381Signature
error InvalidInputBLS12_381Signature();
NoPendingCommittee
error NoPendingCommittee();
PreviousCommitStillPending
error PreviousCommitStillPending();
NoActiveLeader
error NoActiveLeader();
Structs
Validator
Represents a validator in the consensus protocol.
struct Validator {
uint32 ownerIdx;
uint32 lastSnapshotCommit;
uint32 previousSnapshotCommit;
ValidatorAttr latest;
ValidatorAttr snapshot;
ValidatorAttr previousSnapshot;
}
Properties
Name | Type | Description |
---|---|---|
ownerIdx | uint32 | Index of the validator owner within the array of validator owners. |
lastSnapshotCommit | uint32 | The validatorsCommit value when the last snapshot of this validator was made. |
previousSnapshotCommit | uint32 | The validatorsCommit value when the previous snapshot of this validator was made. |
latest | ValidatorAttr | Validator attributes to read if validatorsCommit > validator.lastSnapshotCommit . |
snapshot | ValidatorAttr | Validator attributes to read if validatorsCommit > validator.previousSnapshot . |
previousSnapshot | ValidatorAttr | Validator attributes to read for older commits. |
ValidatorAttr
Represents the attributes of a validator.
struct ValidatorAttr {
bool active;
bool removed;
bool leader;
uint32 weight;
BLS12_381PublicKey pubKey;
BLS12_381Signature proofOfPossession;
}
Properties
Name | Type | Description |
---|---|---|
active | bool | A flag stating if the validator is active. |
removed | bool | A flag stating if the validator has been removed (and is pending a deletion). |
leader | bool | A flag stating if the validator is eligible to be a leader. |
weight | uint32 | Validator's voting weight. |
pubKey | BLS12_381PublicKey | Validator's BLS12-381 public key. |
proofOfPossession | BLS12_381Signature | Validator's Proof-of-possession (a signature over the public key). |
LeaderSelection
Represents the leader selection process in the consensus protocol.
struct LeaderSelection {
uint32 lastSnapshotCommit;
uint32 previousSnapshotCommit;
LeaderSelectionAttr latest;
LeaderSelectionAttr snapshot;
LeaderSelectionAttr previousSnapshot;
}
Properties
Name | Type | Description |
---|---|---|
lastSnapshotCommit | uint32 | The validatorsCommit value when the last snapshot was made. |
previousSnapshotCommit | uint32 | The validatorsCommit value when the previous snapshot was made. |
latest | LeaderSelectionAttr | LeaderSelectionAttr to read if validatorsCommit > lastSnapshotCommit . |
snapshot | LeaderSelectionAttr | LeaderSelectionAttr to read if validatorsCommit > previousSnapshot . |
previousSnapshot | LeaderSelectionAttr | LeaderSelectionAttr to read for older commits. |
LeaderSelectionAttr
Attributes for the validator leader selection process.
struct LeaderSelectionAttr {
uint64 frequency;
bool weighted;
}
Properties
Name | Type | Description |
---|---|---|
frequency | uint64 | The number of views between leader changes. If it is 0 then the leader never rotates. |
weighted | bool | Whether leaders are selectedproportionally to their weight. If false, then the leader is selected round-robin. |
CommitteeValidator
Represents a validator within a committee.
struct CommitteeValidator {
bool leader;
uint32 weight;
BLS12_381PublicKey pubKey;
BLS12_381Signature proofOfPossession;
}
Properties
Name | Type | Description |
---|---|---|
leader | bool | A flag stating if the validator is eligible to be a leader. |
weight | uint32 | Validator's voting weight. |
pubKey | BLS12_381PublicKey | Validator's BLS12-381 public key. |
proofOfPossession | BLS12_381Signature | Validator'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
Name | Type | Description |
---|---|---|
a | bytes32 | First component of the BLS12-381 public key. |
b | bytes32 | Second component of the BLS12-381 public key. |
c | bytes32 | Third component of the BLS12-381 public key. |
BLS12_381Signature
Represents BLS12_381 signature.
struct BLS12_381Signature {
bytes32 a;
bytes16 b;
}
Properties
Name | Type | Description |
---|---|---|
a | bytes32 | First component of the BLS12-381 signature. |
b | bytes16 | Second component of the BLS12-381 signature. |
IL2DAValidator
Functions
validatePubdata
function validatePubdata(
bytes32 _chainedLogsHash,
bytes32 _logsRootHash,
bytes32 _chainedMessagesHash,
bytes32 _chainedBytecodesHash,
bytes calldata _totalL2ToL1PubdataAndStateDiffs
) external returns (bytes32 outputHash);
IPaymaster
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
Name | Type | Description |
---|---|---|
_txHash | bytes32 | The hash of the transaction |
_suggestedSignedHash | bytes32 | The hash of the transaction that is signed by an EOA |
_transaction | Transaction | The transaction itself. |
Returns
Name | Type | Description |
---|---|---|
magic | bytes4 | The value that should be equal to the signature of the validateAndPayForPaymasterTransaction if the paymaster agrees to pay for the transaction. |
context | bytes | The "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
Name | Type | Description |
---|---|---|
_context | bytes | |
_transaction | Transaction | |
_txHash | bytes32 | |
_suggestedSignedHash | bytes32 | |
_txResult | ExecutionResult | |
_maxRefundedGas | uint256 |
Constants
PAYMASTER_VALIDATION_SUCCESS_MAGIC
bytes4 constant PAYMASTER_VALIDATION_SUCCESS_MAGIC =
IPaymaster.validateAndPayForPaymasterTransaction.selector;
IPaymasterFlow
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
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
Name | Type | Description |
---|---|---|
l1Address | address | the address in the L1 that triggered the tx to L2 |
Returns
Name | Type | Description |
---|---|---|
l2Address | address | L2 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
Name | Type | Description |
---|---|---|
l2Address | address | L2 address as viewed in msg.sender |
Returns
Name | Type | Description |
---|---|---|
l1Address | address | the address in the L1 that triggered the tx to L2 |
Contents
- interfaces
- libraries
- SystemLogKey
- Constants
- AddressHasNoCode
- CallerMustBeBootloader
- CallerMustBeEvmContract
- CallerMustBeSystemContract
- CompressionValueAddError
- CompressionValueTransformError
- CompressionValueSubError
- CompressorInitialWritesProcessedNotEqual
- CompressorEnumIndexNotEqual
- DerivedKeyNotEqualToCompressedValue
- DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo
- EmptyBytes32
- EncodedAndRealBytecodeChunkNotEqual
- EncodedLengthNotFourTimesSmallerThanOriginal
- EVMBytecodeHash
- EVMBytecodeHashUnknown
- EVMEmulationNotSupported
- FailedToChargeGas
- FailedToPayOperator
- HashIsNonZero
- HashMismatch
- IndexOutOfBounds
- IndexSizeError
- InsufficientFunds
- InvalidCall
- InvalidCodeHash
- InvalidInput
- InvalidNonceOrderingChange
- InvalidSig
- Keccak256InvalidReturnData
- MalformedBytecode
- NonceAlreadyUsed
- NonceIncreaseError
- NonceNotUsed
- NonEmptyAccount
- NonEmptyMsgValue
- NotAllowedToDeployInKernelSpace
- Overflow
- ReconstructionMismatch
- ShaInvalidReturnData
- StateDiffLengthMismatch
- SystemCallFlagRequired
- TooMuchPubdata
- Unauthorized
- UnknownCodeHash
- UnsupportedOperation
- UnsupportedPaymasterFlow
- UnsupportedTxType
- ValueMismatch
- ZeroNonceError
- SloadContractBytecodeUnknown
- PreviousBytecodeUnknown
- InvalidChainId
- UpgradeTransactionMustBeFirst
- L2BlockNumberZero
- PreviousL2BlockHashIsIncorrect
- CannotInitializeFirstVirtualBlock
- L2BlockAndBatchTimestampMismatch
- InconsistentNewBatchTimestamp
- NoVirtualBlocks
- CannotReuseL2BlockNumberFromPreviousBatch
- IncorrectSameL2BlockTimestamp
- IncorrectSameL2BlockPrevBlockHash
- IncorrectVirtualBlockInsideMiniblock
- IncorrectL2BlockHash
- NonMonotonicL2BlockTimestamp
- CurrentBatchNumberMustBeGreaterThanZero
- TimestampsShouldBeIncremental
- ProvidedBatchNumberIsNotCorrect
- CodeOracleCallFailed
- ReturnedBytecodeDoesNotMatchExpectedHash
- SecondCallShouldHaveCostLessGas
- ThirdCallShouldHaveSameGasCostAsSecondCall
- CallToKeccakShouldHaveSucceeded
- KeccakReturnDataSizeShouldBe32Bytes
- KeccakResultIsNotCorrect
- KeccakShouldStartWorkingAgain
- KeccakMismatchBetweenNumberOfInputsAndOutputs
- KeccakHashWasNotCalculatedCorrectly
- TransactionFailed
- NotEnoughGas
- TooMuchGas
- InvalidNewL2BlockNumber
- InvalidNonceKey
- CodeHashReason
- SigField
- PubdataField
- BytecodeError
Contents
- IAccount
- IAccount constants
- IAccountCodeStorage
- IBaseToken
- IBootloaderUtilities
- IBridgedStandardERC20
- IBridgehub
- IComplexUpgrader
- ICompressor
- ICompressor constants
- ForceDeployment
- IContractDeployer
- ICreate2Factory
- IEvmHashesStorage
- ImmutableData
- IImmutableSimulator
- IKnownCodesStorage
- L2ToL1Log
- IL1Messenger
- IL1Messenger constants
- IL2AssetRouter
- IL2DAValidator
- ZKChainSpecificForceDeploymentsData
- FixedForceDeploymentsData
- IL2GenesisUpgrade
- IL2NativeTokenVault
- IL2SharedBridgeLegacy
- IL2StandardToken
- IL2WrappedBaseToken
- IMailbox
- IMessageRoot
- INonceHolder
- ExecutionResult
- IPaymaster
- IPaymaster constants
- IPaymasterFlow
- IPubdataChunkPublisher
- ISystemContext
- ISystemContextDeprecated
IAccount
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
Name | Type | Description |
---|---|---|
_txHash | bytes32 | The hash of the transaction to be used in the explorer |
_suggestedSignedHash | bytes32 | The hash of the transaction is signed by EOAs |
_transaction | Transaction | The transaction itself |
Returns
Name | Type | Description |
---|---|---|
magic | bytes4 | The 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
ACCOUNT_VALIDATION_SUCCESS_MAGIC
bytes4 constant ACCOUNT_VALIDATION_SUCCESS_MAGIC =
IAccount.validateTransaction.selector;
IAccountCodeStorage
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
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
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
getTransactionHashes
function getTransactionHashes(Transaction calldata _transaction)
external
view
returns (bytes32 txHash, bytes32 signedTxHash);
IBridgehub
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
setAddresses
function setAddresses(
address _assetRouter,
address _ctmDeployer,
address _messageRoot,
address _chainAssetHandler
) external;
setChainAssetHandler
function setChainAssetHandler(address _chainAssetHandler) external;
owner
function owner() external view returns (address);
l1CtmDeployer
function l1CtmDeployer() external returns (address);
IComplexUpgrader
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
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
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
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
Name | Type | Description |
---|---|---|
mode | AllowedBytecodeTypes | The 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
Name | Type | Description |
---|---|---|
_sender | address | The account that deploys the contract. |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_salt | bytes32 | The create2 salt. |
_input | bytes | The constructor data. |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_sender | address | The account that deploys the contract. |
_senderNonce | uint256 | The deploy nonce of the sender's account. |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_salt | bytes32 | The CREATE2 salt |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_input | bytes | The constructor calldata |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_salt | bytes32 | The CREATE2 salt |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_input | bytes | The constructor calldata. |
_aaVersion | AccountAbstractionVersion | The account abstraction version to use. |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_salt | bytes32 | A 32-byte salt. |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_input | bytes | The constructor calldata |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | |
_bytecodeHash | bytes32 | The correctly formatted hash of the bytecode. |
_input | bytes | The constructor calldata. |
_aaVersion | AccountAbstractionVersion | The account abstraction version to use. |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The derived address of the contract. |
getAccountInfo
Returns information about a certain account.
function getAccountInfo(address _address)
external
view
returns (AccountInfo memory info);
Parameters
Name | Type | Description |
---|---|---|
_address | address | The address of the account. |
Returns
Name | Type | Description |
---|---|---|
info | AccountInfo | The 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
Name | Type | Description |
---|---|---|
_address | address | The address of the account. |
Returns
Name | Type | Description |
---|---|---|
<none> | AccountAbstractionVersion | The 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
Name | Type | Description |
---|---|---|
_version | AccountAbstractionVersion | The 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
Name | Type | Description |
---|---|---|
_deployments | ForceDeployment[] | 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
Name | Type | Description |
---|---|---|
_initCode | bytes | The init code for the contract. |
Returns
Name | Type | Description |
---|---|---|
evmGasUsed | uint256 | The amount of EVM gas used. |
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_salt | bytes32 | The CREATE2 salt. |
_initCode | bytes | The init code for the contract. |
Returns
Name | Type | Description |
---|---|---|
evmGasUsed | uint256 | The amount of EVM gas used. |
newAddress | address | The address of created contract. |
setAllowedBytecodeTypesToDeploy
Changes what types of bytecodes are allowed to be deployed on the chain.
function setAllowedBytecodeTypesToDeploy(
AllowedBytecodeTypes newAllowedBytecodeTypes
) external;
Parameters
Name | Type | Description |
---|---|---|
newAllowedBytecodeTypes | AllowedBytecodeTypes | The 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
Name | Type | Description |
---|---|---|
deployerAddress | address | The address of the deployer. |
bytecodeHash | bytes32 | The formatted hash of the bytecode that was deployed. |
contractAddress | address | The 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
Name | Type | Description |
---|---|---|
accountAddress | address | The address of the account. |
nonceOrdering | AccountNonceOrdering | The new nonce ordering of the account. |
AccountVersionUpdated
Emitted when account's AA version is updated.
event AccountVersionUpdated(
address indexed accountAddress, AccountAbstractionVersion aaVersion
);
Parameters
Name | Type | Description |
---|---|---|
accountAddress | address | The address of the contract. |
aaVersion | AccountAbstractionVersion | The 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
Name | Type | Description |
---|---|---|
mode | AllowedBytecodeTypes | The 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 accountVersion1
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 deployedEraVmAndEVM
means that native contracts and EVM contracts can be deployed
enum AllowedBytecodeTypes {
EraVm,
EraVmAndEVM
}
ICreate2Factory
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
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
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
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
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
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
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
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
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
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
Name | Type | Description |
---|---|---|
name_ | string | The name of the token. |
symbol_ | string | The symbol of the token. |
_l2Bridge | address | Address of the L2 bridge |
_l1Address | address | Address 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. |
_baseTokenAssetId | bytes32 |
IMailbox
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
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
Name | Type | Description |
---|---|---|
aggregatedRoot | bytes32 | of the batches from different chains. |
INonceHolder
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
Name | Type | Description |
---|---|---|
_address | address | The account to return the minimal nonce for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
_address | address | The account to return the nonce for. |
_key | uint192 | The key of the nonce to return. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
_address | address | The account to return the raw nonce for |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
_value | uint256 | The number by which to increase the minimal nonce for msg.sender. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | oldMinNonce 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
Name | Type | Description |
---|---|---|
_expectedNonce | uint256 | The 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
Name | Type | Description |
---|---|---|
_expectedNonce | uint256 | The 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
Name | Type | Description |
---|---|---|
_address | address | The address to return the deploy nonce of. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | deploymentNonce 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
Name | Type | Description |
---|---|---|
_address | address | The address of the account which to return the deploy nonce for. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | prevDeploymentNonce 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
Name | Type | Description |
---|---|---|
_address | address | The address the nonce of which is being checked. |
_key | uint256 | The nonce value which is tested. |
_shouldBeUsed | bool | The 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
Name | Type | Description |
---|---|---|
_address | address | The address the nonce of which is being checked. |
_nonce | uint256 | The nonce value which is checked. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | true if the nonce has been used, false otherwise. |
Events
ValueSetUnderNonce
event ValueSetUnderNonce(
address indexed accountAddress, uint256 indexed key, uint256 value
);
IPaymaster
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
Name | Type | Description |
---|---|---|
_txHash | bytes32 | The hash of the transaction |
_suggestedSignedHash | bytes32 | The hash of the transaction that is signed by an EOA |
_transaction | Transaction | The transaction itself. |
Returns
Name | Type | Description |
---|---|---|
magic | bytes4 | The value that should be equal to the signature of the validateAndPayForPaymasterTransaction if the paymaster agrees to pay for the transaction. |
context | bytes | The "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
Name | Type | Description |
---|---|---|
_context | bytes | |
_transaction | Transaction | |
_txHash | bytes32 | |
_suggestedSignedHash | bytes32 | |
_txResult | ExecutionResult | |
_maxRefundedGas | uint256 |
Constants
PAYMASTER_VALIDATION_SUCCESS_MAGIC
bytes4 constant PAYMASTER_VALIDATION_SUCCESS_MAGIC =
IPaymaster.validateAndPayForPaymasterTransaction.selector;
IPaymasterFlow
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
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
view
returns (bytes32[] memory blobLinearHashes);
Parameters
Name | Type | Description |
---|---|---|
_pubdata | bytes | The total l2 to l1 pubdata that will be sent via L1 blobs. |
ISystemContext
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
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
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);
IBridgedStandardERC20
Author: Matter Labs
The interface for the BridgedStandardERC20 contract
Note: security-contact: security@matterlabs.dev
Functions
reinitializeToken
A method to be called by the governor to update the token's metadata.
The _version must be exactly the version higher by 1 than the current version. This is needed to ensure that the governor can not accidentally disable future reinitialization of the token.
function reinitializeToken(
ERC20Getters calldata _availableGetters,
string calldata _newName,
string calldata _newSymbol,
uint8 _version
) external;
Parameters
Name | Type | Description |
---|---|---|
_availableGetters | ERC20Getters | The getters that the token has. |
_newName | string | The new name of the token. |
_newSymbol | string | The new symbol of the token. |
_version | uint8 | The version of the token that will be initialized. |
Structs
ERC20Getters
Used to explicitly separate which getters the token has and which it does not.
Different tokens in L1 can implement or not implement getter function as name
/symbol
/decimals
,
Our goal is to store all the getters that L1 token implements, and for others, we keep it as an unimplemented method.
Describes whether there is a specific getter in the token.
struct ERC20Getters {
bool ignoreName;
bool ignoreSymbol;
bool ignoreDecimals;
}
IL2AssetRouter
Author: Matter Labs
The interface for the L2AssetRouter contract
Note: security-contact: security@matterlabs.dev
Functions
L2_LEGACY_SHARED_BRIDGE
function L2_LEGACY_SHARED_BRIDGE() external view returns (address);
IL2NativeTokenVault
Author: Matter Labs
The interface for the L2NativeTokenVault contract
Note: security-contact: security@matterlabs.dev
Functions
tokenAddress
function tokenAddress(bytes32 _assetId) external view returns (address);
Errors
AddressHasNoCode
error AddressHasNoCode(address);
CallerMustBeBootloader
error CallerMustBeBootloader();
CallerMustBeEvmContract
error CallerMustBeEvmContract();
CallerMustBeSystemContract
error CallerMustBeSystemContract();
CompressionValueAddError
error CompressionValueAddError(uint256 expected, uint256 actual);
CompressionValueTransformError
error CompressionValueTransformError(uint256 expected, uint256 actual);
CompressionValueSubError
error CompressionValueSubError(uint256 expected, uint256 actual);
CompressorInitialWritesProcessedNotEqual
error CompressorInitialWritesProcessedNotEqual(uint256 expected, uint256 actual);
CompressorEnumIndexNotEqual
error CompressorEnumIndexNotEqual(uint256 expected, uint256 actual);
DerivedKeyNotEqualToCompressedValue
error DerivedKeyNotEqualToCompressedValue(bytes32 expected, bytes32 provided);
DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo
error DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo();
EmptyBytes32
error EmptyBytes32();
EncodedAndRealBytecodeChunkNotEqual
error EncodedAndRealBytecodeChunkNotEqual(uint64 expected, uint64 provided);
EncodedLengthNotFourTimesSmallerThanOriginal
error EncodedLengthNotFourTimesSmallerThanOriginal();
EVMBytecodeHash
error EVMBytecodeHash();
EVMBytecodeHashUnknown
error EVMBytecodeHashUnknown();
EVMEmulationNotSupported
error EVMEmulationNotSupported();
FailedToChargeGas
error FailedToChargeGas();
FailedToPayOperator
error FailedToPayOperator();
HashIsNonZero
error HashIsNonZero(bytes32);
HashMismatch
error HashMismatch(bytes32 expected, bytes32 actual);
IndexOutOfBounds
error IndexOutOfBounds();
IndexSizeError
error IndexSizeError();
InsufficientFunds
error InsufficientFunds(uint256 required, uint256 actual);
InvalidCall
error InvalidCall();
InvalidCodeHash
error InvalidCodeHash(CodeHashReason);
InvalidInput
error InvalidInput();
InvalidNonceOrderingChange
error InvalidNonceOrderingChange();
InvalidSig
error InvalidSig(SigField, uint256);
Keccak256InvalidReturnData
error Keccak256InvalidReturnData();
MalformedBytecode
error MalformedBytecode(BytecodeError);
NonceAlreadyUsed
error NonceAlreadyUsed(address account, uint256 nonce);
NonceIncreaseError
error NonceIncreaseError(uint256 min, uint256 max, uint256 proposed);
NonceJumpError
NonceNotUsed
error NonceNotUsed(address account, uint256 nonce);
NonEmptyAccount
error NonEmptyAccount();
NonEmptyMsgValue
error NonEmptyMsgValue();
NotAllowedToDeployInKernelSpace
error NotAllowedToDeployInKernelSpace();
Overflow
error Overflow();
ReconstructionMismatch
error ReconstructionMismatch(PubdataField, bytes32 expected, bytes32 actual);
ShaInvalidReturnData
error ShaInvalidReturnData();
StateDiffLengthMismatch
error StateDiffLengthMismatch();
SystemCallFlagRequired
error SystemCallFlagRequired();
TooMuchPubdata
error TooMuchPubdata(uint256 limit, uint256 supplied);
Unauthorized
error Unauthorized(address);
UnknownCodeHash
error UnknownCodeHash(bytes32);
UnsupportedOperation
error UnsupportedOperation();
UnsupportedPaymasterFlow
error UnsupportedPaymasterFlow();
UnsupportedTxType
error UnsupportedTxType(uint256);
ValueMismatch
error ValueMismatch(uint256 expected, uint256 actual);
ZeroNonceError
error ZeroNonceError();
SloadContractBytecodeUnknown
error SloadContractBytecodeUnknown();
PreviousBytecodeUnknown
error PreviousBytecodeUnknown();
InvalidChainId
error InvalidChainId();
UpgradeTransactionMustBeFirst
error UpgradeTransactionMustBeFirst();
L2BlockNumberZero
error L2BlockNumberZero();
PreviousL2BlockHashIsIncorrect
error PreviousL2BlockHashIsIncorrect(
bytes32 correctPrevBlockHash, bytes32 expectedPrevL2BlockHash
);
CannotInitializeFirstVirtualBlock
error CannotInitializeFirstVirtualBlock();
L2BlockAndBatchTimestampMismatch
error L2BlockAndBatchTimestampMismatch(
uint128 l2BlockTimestamp, uint128 currentBatchTimestamp
);
InconsistentNewBatchTimestamp
error InconsistentNewBatchTimestamp(
uint128 newBatchTimestamp, uint128 lastL2BlockTimestamp
);
NoVirtualBlocks
error NoVirtualBlocks();
CannotReuseL2BlockNumberFromPreviousBatch
error CannotReuseL2BlockNumberFromPreviousBatch();
IncorrectSameL2BlockTimestamp
error IncorrectSameL2BlockTimestamp(
uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp
);
IncorrectSameL2BlockPrevBlockHash
error IncorrectSameL2BlockPrevBlockHash(
bytes32 expectedPrevL2BlockHash, bytes32 latestL2blockHash
);
IncorrectVirtualBlockInsideMiniblock
error IncorrectVirtualBlockInsideMiniblock();
IncorrectL2BlockHash
error IncorrectL2BlockHash(
bytes32 expectedPrevL2BlockHash, bytes32 pendingL2BlockHash
);
NonMonotonicL2BlockTimestamp
error NonMonotonicL2BlockTimestamp(
uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp
);
CurrentBatchNumberMustBeGreaterThanZero
error CurrentBatchNumberMustBeGreaterThanZero();
TimestampsShouldBeIncremental
error TimestampsShouldBeIncremental(
uint128 newTimestamp, uint128 previousBatchTimestamp
);
ProvidedBatchNumberIsNotCorrect
error ProvidedBatchNumberIsNotCorrect(
uint128 previousBatchNumber, uint128 _expectedNewNumber
);
CodeOracleCallFailed
error CodeOracleCallFailed();
ReturnedBytecodeDoesNotMatchExpectedHash
error ReturnedBytecodeDoesNotMatchExpectedHash(
bytes32 returnedBytecode, bytes32 expectedBytecodeHash
);
SecondCallShouldHaveCostLessGas
error SecondCallShouldHaveCostLessGas(
uint256 secondCallCost, uint256 firstCallCost
);
ThirdCallShouldHaveSameGasCostAsSecondCall
error ThirdCallShouldHaveSameGasCostAsSecondCall(
uint256 thirdCallCost, uint256 secondCallCost
);
CallToKeccakShouldHaveSucceeded
error CallToKeccakShouldHaveSucceeded();
KeccakReturnDataSizeShouldBe32Bytes
error KeccakReturnDataSizeShouldBe32Bytes(uint256 returnDataSize);
KeccakResultIsNotCorrect
error KeccakResultIsNotCorrect(bytes32 result);
KeccakShouldStartWorkingAgain
error KeccakShouldStartWorkingAgain();
KeccakMismatchBetweenNumberOfInputsAndOutputs
error KeccakMismatchBetweenNumberOfInputsAndOutputs(
uint256 testInputsLength, uint256 expectedOutputsLength
);
KeccakHashWasNotCalculatedCorrectly
error KeccakHashWasNotCalculatedCorrectly(
bytes32 result, bytes32 expectedOutputs
);
TransactionFailed
error TransactionFailed();
NotEnoughGas
error NotEnoughGas();
TooMuchGas
error TooMuchGas();
InvalidNewL2BlockNumber
error InvalidNewL2BlockNumber(uint256 l2BlockNumber);
CodeHashReason
enum CodeHashReason {
NotContractOnConstructor,
NotConstructedContract
}
SigField
enum SigField {
Length,
V,
S
}
PubdataField
enum PubdataField {
NumberOfLogs,
LogsHash,
MsgHash,
Bytecode,
InputDAFunctionSig,
InputLogsHash,
InputLogsRootHash,
InputMsgsHash,
InputBytecodeHash,
Offset,
Length
}
BytecodeError
enum BytecodeError {
Version,
NumberOfWords,
Length,
WordsMustBeOdd,
DictionaryLength,
EvmBytecodeLength,
EvmBytecodeLengthTooBig
}
Constants
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
IL2AssetRouter constant L2_ASSET_ROUTER =
IL2AssetRouter(address(USER_CONTRACTS_OFFSET + 0x03));
L2_BRIDGE_HUB
IBridgehub constant L2_BRIDGE_HUB =
IBridgehub(address(USER_CONTRACTS_OFFSET + 0x02));
L2_NATIVE_TOKEN_VAULT
IL2NativeTokenVault constant L2_NATIVE_TOKEN_VAULT =
IL2NativeTokenVault(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);
L2_CHAIN_ASSET_HANDLER
address constant L2_CHAIN_ASSET_HANDLER = address(USER_CONTRACTS_OFFSET + 0x0a);
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
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,
MESSAGE_ROOT_ROLLING_HASH_KEY,
L2_TXS_STATUS_ROLLING_HASH_KEY,
EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY
}
Contents
DynamicIncrementalMerkle
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
Name | Type | Description |
---|---|---|
self | Bytes32PushTree | |
zero | bytes32 | The value that represents an empty leaf. |
Returns
Name | Type | Description |
---|---|---|
initialRoot | bytes32 | The 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
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
Name | Type | Description |
---|---|---|
_path | bytes32[] | Merkle path from the leaf to the root |
_index | uint256 | Leaf index in the tree |
_itemHash | bytes32 | Hash of leaf content |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
_path | bytes32[] | Merkle path from the leaf to the root |
_index | uint256 | Leaf index in the tree. |
_itemHash | bytes32 | Hash of leaf content |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
_startPath | bytes32[] | Merkle path from the first element of the range to the root |
_endPath | bytes32[] | Merkle path from the last element of the range to the root |
_startIndex | uint256 | Index of the first element of the range in the tree |
_itemHashes | bytes32[] | Hashes of the elements in the range |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
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
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
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
Name | Type | Description |
---|---|---|
diamondStorage | DiamondStorage | The 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
Name | Type | Description |
---|---|---|
_diamondCut | DiamondCutData | Diamond'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 inDiamondStorage.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
Name | Type | Description |
---|---|---|
facetAddress | address | address of the facet which is connected with selector |
selectorPosition | uint16 | index in FacetToSelectors.selectors array, where is selector stored |
isFreezable | bool | denotes whether the selector can be frozen. |
FacetToSelectors
Utility struct that contains associated selectors & meta information of facet
struct FacetToSelectors {
bytes4[] selectors;
uint16 facetPosition;
}
Properties
Name | Type | Description |
---|---|---|
selectors | bytes4[] | list of all selectors that belong to the facet |
facetPosition | uint16 | index 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
Name | Type | Description |
---|---|---|
selectorToFacet | mapping(bytes4 selector => SelectorToFacet selectorInfo) | A mapping from the selector to the facet address and its meta information |
facetToSelectors | mapping(address facetAddress => FacetToSelectors facetInfo) | A mapping from facet address to its selectors with meta information |
facets | address[] | The array of all unique facet addresses that belong to the diamond proxy |
isFrozen | bool | Denotes 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
Name | Type | Description |
---|---|---|
facet | address | The address of facet that's affected by the cut |
action | Action | The action that is made on the facet |
isFreezable | bool | Denotes whether the facet & all their selectors can be frozen |
selectors | bytes4[] | 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
Name | Type | Description |
---|---|---|
facetCuts | FacetCut[] | The set of changes (adding/removing/replacement) of implementation contracts |
initAddress | address | The address that's delegate called after setting up new facet changes |
initCalldata | bytes | Calldata for the delegate call to initAddress |
Enums
Action
Type of change over diamond: add/replace/remove facets
enum Action {
Add,
Replace,
Remove
}
PriorityQueue
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
Name | Type | Description |
---|---|---|
<none> | uint256 | Index of the oldest priority operation that wasn't processed yet |
getTotalPriorityTxs
function getTotalPriorityTxs(Queue storage _queue)
internal
view
returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The total number of unprocessed priority operations in a priority queue |
isEmpty
function isEmpty(Queue storage _queue) internal view returns (bool);
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Whether 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
Name | Type | Description |
---|---|---|
<none> | PriorityOperation | The 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
Name | Type | Description |
---|---|---|
priorityOperation | PriorityOperation | that 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
Name | Type | Description |
---|---|---|
data | mapping(uint256 priorityOpId => PriorityOperation priorityOp) | The inner mapping that saves priority operation by its index |
tail | uint256 | The pointer to the free slot |
head | uint256 | The pointer to the first unprocessed priority operation, equal to the tail if the queue is empty |
PriorityTree
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
Name | Type | Description |
---|---|---|
<none> | uint256 | Index of the oldest priority operation that wasn't processed yet |
getTotalPriorityTxs
function getTotalPriorityTxs(Tree storage _tree)
internal
view
returns (uint256);
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | bytes32 | Returns the tree root. |
isHistoricalRoot
function isHistoricalRoot(Tree storage _tree, bytes32 _root)
internal
view
returns (bool);
Parameters
Name | Type | Description |
---|---|---|
_tree | Tree | |
_root | bytes32 | The root to check. |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | Returns 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
Name | Type | Description |
---|---|---|
_tree | Tree | |
_lastUnprocessed | uint256 | The 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;
}
BatchDecoder
Author: Matter Labs
Utility library for decoding and validating batch data.
This library decodes commit, proof, and execution batch data and verifies batch number bounds. It reverts with custom errors when the data is invalid or unsupported encoding is used.
Note: security-contact: security@matterlabs.dev
State Variables
SUPPORTED_ENCODING_VERSION
The currently supported encoding version.
uint8 internal constant SUPPORTED_ENCODING_VERSION = 1;
Functions
_decodeCommitData
Decodes commit data from a calldata bytes into the last committed batch data and an array of new batch data.
function _decodeCommitData(bytes calldata _commitData)
private
pure
returns (
IExecutor.StoredBatchInfo memory lastCommittedBatchData,
IExecutor.CommitBatchInfo[] memory newBatchesData
);
Parameters
Name | Type | Description |
---|---|---|
_commitData | bytes | The calldata byte array containing the data for committing batches. |
Returns
Name | Type | Description |
---|---|---|
lastCommittedBatchData | IExecutor.StoredBatchInfo | The data for the batch before newly committed batches. |
newBatchesData | IExecutor.CommitBatchInfo[] | An array containing the newly committed batches. |
decodeAndCheckPrecommitData
Decodes and validates precommit data for a batch, ensuring the encoding version is supported.
The first byte of _precommitData
is interpreted as the encoding version and must equal SUPPORTED_ENCODING_VERSION
.
If it does, the remainder of the data is decoded into an IExecutor.PrecommitInfo
struct. Otherwise, this call reverts.
function decodeAndCheckPrecommitData(bytes calldata _precommitData)
internal
pure
returns (IExecutor.PrecommitInfo memory precommitInfo);
Parameters
Name | Type | Description |
---|---|---|
_precommitData | bytes | ABI-encoded bytes where the first byte is the encoding version, followed by the encoded PrecommitInfo . |
Returns
Name | Type | Description |
---|---|---|
precommitInfo | IExecutor.PrecommitInfo | The decoded PrecommitInfo containing transaction status commitments. |
decodeAndCheckCommitData
Decodes the commit data and checks that the provided batch bounds are correct.
Note that it only checks that the last and the first batches in the array correspond to the provided bounds. The fact that the batches inside the array are provided in the correct order should be checked by the caller.
function decodeAndCheckCommitData(
bytes calldata _commitData,
uint256 _processBatchFrom,
uint256 _processBatchTo
)
internal
pure
returns (
IExecutor.StoredBatchInfo memory lastCommittedBatchData,
IExecutor.CommitBatchInfo[] memory newBatchesData
);
Parameters
Name | Type | Description |
---|---|---|
_commitData | bytes | The calldata byte array containing the data for committing batches. |
_processBatchFrom | uint256 | The expected batch number of the first commit batch in the array. |
_processBatchTo | uint256 | The expected batch number of the last commit batch in the array. |
Returns
Name | Type | Description |
---|---|---|
lastCommittedBatchData | IExecutor.StoredBatchInfo | The data for the batch before newly committed batches. |
newBatchesData | IExecutor.CommitBatchInfo[] | An array containing the newly committed batches. |
_decodeProofData
Decodes proof data from a calldata byte array into the previous batch, an array of proved batches, and a proof array.
function _decodeProofData(bytes calldata _proofData)
private
pure
returns (
IExecutor.StoredBatchInfo memory prevBatch,
IExecutor.StoredBatchInfo[] memory provedBatches,
uint256[] memory proof
);
Parameters
Name | Type | Description |
---|---|---|
_proofData | bytes | The calldata byte array containing the data for proving batches. |
Returns
Name | Type | Description |
---|---|---|
prevBatch | IExecutor.StoredBatchInfo | The batch information before the batches to be verified. |
provedBatches | IExecutor.StoredBatchInfo[] | An array containing the the batches to be verified. |
proof | uint256[] | An array containing the proof for the verifier. |
decodeAndCheckProofData
Decodes the commit data and checks that the provided batch bounds are correct.
Note that it only checks that the last and the first batches in the array correspond to the provided bounds. The fact that the batches inside the array are provided in the correct order should be checked by the caller.
function decodeAndCheckProofData(
bytes calldata _proofData,
uint256 _processBatchFrom,
uint256 _processBatchTo
)
internal
pure
returns (
IExecutor.StoredBatchInfo memory prevBatch,
IExecutor.StoredBatchInfo[] memory provedBatches,
uint256[] memory proof
);
Parameters
Name | Type | Description |
---|---|---|
_proofData | bytes | The commit data to decode. |
_processBatchFrom | uint256 | The expected batch number of the first batch in the array. |
_processBatchTo | uint256 | The expected batch number of the last batch in the array. |
Returns
Name | Type | Description |
---|---|---|
prevBatch | IExecutor.StoredBatchInfo | The batch information before the batches to be verified. |
provedBatches | IExecutor.StoredBatchInfo[] | An array containing the the batches to be verified. |
proof | uint256[] | An array containing the proof for the verifier. |
_decodeExecuteData
Decodes execution data from a calldata byte array into an array of stored batch information.
function _decodeExecuteData(bytes calldata _executeData)
private
pure
returns (
IExecutor.StoredBatchInfo[] memory executeData,
PriorityOpsBatchInfo[] memory priorityOpsData,
InteropRoot[][] memory dependencyRoots
);
Parameters
Name | Type | Description |
---|---|---|
_executeData | bytes | The calldata byte array containing the execution data to decode. |
Returns
Name | Type | Description |
---|---|---|
executeData | IExecutor.StoredBatchInfo[] | An array containing the stored batch information for execution. |
priorityOpsData | PriorityOpsBatchInfo[] | Merkle proofs of the priority operations for each batch. |
dependencyRoots | InteropRoot[][] |
decodeAndCheckExecuteData
Decodes the execute data and checks that the provided batch bounds are correct.
Note that it only checks that the last and the first batches in the array correspond to the provided bounds. The fact that the batches inside the array are provided in the correct order should be checked by the caller.
function decodeAndCheckExecuteData(
bytes calldata _executeData,
uint256 _processBatchFrom,
uint256 _processBatchTo
)
internal
pure
returns (
IExecutor.StoredBatchInfo[] memory executeData,
PriorityOpsBatchInfo[] memory priorityOpsData,
InteropRoot[][] memory dependencyRoots
);
Parameters
Name | Type | Description |
---|---|---|
_executeData | bytes | The calldata byte array containing the execution data to decode. |
_processBatchFrom | uint256 | The expected batch number of the first batch in the array. |
_processBatchTo | uint256 | The expected batch number of the last batch in the array. |
Returns
Name | Type | Description |
---|---|---|
executeData | IExecutor.StoredBatchInfo[] | An array containing the stored batch information for execution. |
priorityOpsData | PriorityOpsBatchInfo[] | Merkle proofs of the priority operations for each batch. |
dependencyRoots | InteropRoot[][] |
TransactionValidator
Author: Matter Labs
Note: security-contact: security@matterlabs.dev
Functions
validateL1ToL2Transaction
Used to validate key properties of an L1->L2 transaction
function validateL1ToL2Transaction(
L2CanonicalTransaction memory _transaction,
bytes memory _encoded,
uint256 _priorityTxMaxGasLimit,
uint256 _priorityTxMaxPubdata
) internal pure;
Parameters
Name | Type | Description |
---|---|---|
_transaction | L2CanonicalTransaction | The transaction to validate |
_encoded | bytes | The abi encoded bytes of the transaction |
_priorityTxMaxGasLimit | uint256 | The max gas limit, generally provided from Storage.sol |
_priorityTxMaxPubdata | uint256 | The maximal amount of pubdata that a single L1->L2 transaction can emit |
validateUpgradeTransaction
Used to validate upgrade transactions
function validateUpgradeTransaction(L2CanonicalTransaction memory _transaction)
internal
pure;
Parameters
Name | Type | Description |
---|---|---|
_transaction | L2CanonicalTransaction | The transaction to validate |
getMinimalPriorityTransactionGasLimit
Calculates the approximate minimum gas limit required for executing a priority transaction.
function getMinimalPriorityTransactionGasLimit(
uint256 _encodingLength,
uint256 _numberOfFactoryDependencies,
uint256 _l2GasPricePerPubdata
) internal pure returns (uint256);
Parameters
Name | Type | Description |
---|---|---|
_encodingLength | uint256 | The length of the priority transaction encoding in bytes. |
_numberOfFactoryDependencies | uint256 | The number of new factory dependencies that will be added. |
_l2GasPricePerPubdata | uint256 | The L2 gas price for publishing the priority transaction on L2. |
Returns
Name | Type | Description |
---|---|---|
<none> | uint256 | The minimum gas limit required to execute the priority transaction. Note: The calculation includes the main cost of the priority transaction, however, in reality, the operator can spend a little more gas on overheads. |
getTransactionBodyGasLimit
Based on the full L2 gas limit (that includes the batch overhead) and other properties of the transaction, returns the l2GasLimit for the body of the transaction (the actual execution).
function getTransactionBodyGasLimit(
uint256 _totalGasLimit,
uint256 _encodingLength
) internal pure returns (uint256 txBodyGasLimit);
Parameters
Name | Type | Description |
---|---|---|
_totalGasLimit | uint256 | The L2 gas limit that includes both the overhead for processing the batch and the L2 gas needed to process the transaction itself (i.e. the actual l2GasLimit that will be used for the transaction). |
_encodingLength | uint256 | The length of the ABI-encoding of the transaction. |
getOverheadForTransaction
Based on the total L2 gas limit and several other parameters of the transaction returns the part of the L2 gas that will be spent on the batch's overhead.
The details of how this function works can be checked in the documentation
of the fee model of ZKsync. The appropriate comments are also present
in the Rust implementation description of function get_maximal_allowed_overhead
.
function getOverheadForTransaction(uint256 _encodingLength)
internal
pure
returns (uint256 batchOverheadForTransaction);
Parameters
Name | Type | Description |
---|---|---|
_encodingLength | uint256 | The length of the binary encoding of the transaction in bytes |
SystemContractsCaller
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
Functions
safeCastToU32
function safeCastToU32(uint256 _x) internal pure returns (uint32);
Contents
- EfficientCall
- RLPEncoder
- ZkSyncMeta
- Global
- SystemContractHelper
- SystemContractHelper constants
- CalldataForwardingMode
- SystemContractsCaller
- SystemContractsCaller constants
- Transaction
- TransactionHelper
- TransactionHelper constants
- Utils
Constants
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
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:
ptr.add
- Transformsptr.offset
intoptr.offset + u32(_value)
. If overflow happens then it panics.ptr.sub
- Transformsptr.offset
intoptr.offset - u32(_value)
. If underflow happens then it panics.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.ptr.shrink
- Transformsptr.length
intoptr.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
ptr.start
is transformed intoptr.offset + ptr.start
ptr.length
is transformed intoptr.length - ptr.offset
ptr.offset
is transformed into0
*
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
Name | Type | Description |
---|---|---|
_data | bytes | The preimage data. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The keccak256 hash. |
sha
Call the sha256
precompile without copying calldata to memory.
function sha(bytes calldata _data) internal view returns (bytes32);
Parameters
Name | Type | Description |
---|---|---|
_data | bytes | The preimage data. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_value | uint256 | The msg.value to send. |
_data | bytes | The calldata to use for the call. |
_isSystem | bool | Whether the call should contain the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
_whoToMimic | address | The msg.sender for the next call. |
_isConstructor | bool | Whether the call should contain the isConstructor flag. |
_isSystem | bool | Whether the call should contain the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_value | uint256 | The msg.value to send. |
_data | bytes | The calldata to use for the call. |
_isSystem | bool | Whether the call should contain the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
success | bool | whether 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
Returns
Name | Type | Description |
---|---|---|
success | bool | whether 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
Returns
Name | Type | Description |
---|---|---|
success | bool | whether 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to use for the call. |
_address | address | The address to call. |
_data | bytes | The calldata to use for the call. |
_whoToMimic | address | The msg.sender for the next call. |
_isConstructor | bool | Whether the call should contain the isConstructor flag. |
_isSystem | bool | Whether the call should contain the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
success | bool | whether 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
Name | Type | Description |
---|---|---|
_success | bool | Whether the call was successful. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
_gas | uint256 | The gas to be passed to the call. |
_data | bytes | The calldata to be passed to the call. |
_isConstructor | bool | Whether the call is a constructor call. |
_isSystem | bool | Whether the call is a system call. |
RLPEncoder
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
Name | Type | Description |
---|---|---|
_len | uint64 | The 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
Name | Type | Description |
---|---|---|
_len | uint64 | The 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
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
Name | Type | Description |
---|---|---|
_isService | bool | The isService flag. |
_key | bytes32 | The key part of the L2Log. |
_value | bytes32 | The 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
Name | Type | Description |
---|---|---|
_inputMemoryOffset | uint32 | The memory offset in 32-byte words for the input data for calling the precompile. |
_inputMemoryLength | uint32 | The length of the input data in words. |
_outputMemoryOffset | uint32 | The memory offset in 32-byte words for the output data. |
_outputMemoryLength | uint32 | The length of the output data in words. |
_perPrecompileInterpreted | uint64 | The 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
Name | Type | Description |
---|---|---|
_rawParams | uint256 | The packed precompile params. They can be retrieved by the packPrecompileParams method. |
_gasToBurn | uint32 | The number of gas to burn during this call. |
_pubdataToSpend | uint32 | The number of pubdata bytes to burn during the call. |
Returns
Name | Type | Description |
---|---|---|
success | bool | Whether 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
Name | Type | Description |
---|---|---|
_value | uint128 | The msg.value that will be used for the next call. |
eventInitialize
Initialize a new event.
function eventInitialize(uint256 initializer, uint256 value1) internal;
Parameters
Name | Type | Description |
---|---|---|
initializer | uint256 | The event initializing value. |
value1 | uint256 | The first topic or data chunk. |
eventWrite
Continue writing the previously initialized event.
function eventWrite(uint256 value1, uint256 value2) internal;
Parameters
Name | Type | Description |
---|---|---|
value1 | uint256 | The first topic or data chunk. |
value2 | uint256 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
offset | uint256 | The offset of the bits. |
size | uint256 | The size of the extracted number in bits. |
Returns
Name | Type | Description |
---|---|---|
result | uint256 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
pubdataPublished | uint32 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
heapSize | uint32 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
auxHeapSize | uint32 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
shardId | uint8 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
callerShardId | uint8 | The 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
Name | Type | Description |
---|---|---|
meta | uint256 | Packed representation of the ZkSyncMeta. |
Returns
Name | Type | Description |
---|---|---|
codeShardId | uint8 | The 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
Name | Type | Description |
---|---|---|
meta | ZkSyncMeta | The 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
Name | Type | Description |
---|---|---|
callFlags | uint256 | The 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
Name | Type | Description |
---|---|---|
ptr | uint256 | The 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
Name | Type | Description |
---|---|---|
extraAbiData | uint256 | The 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
Name | Type | Description |
---|---|---|
<none> | bool | true 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
Name | Type | Description |
---|---|---|
_address | address | The address to test |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | true 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
Name | Type | Description |
---|---|---|
<none> | bool | true 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
Name | Type | Description |
---|---|---|
_gasToPay | uint32 | The number of gas to burn. |
_pubdataToSpend | uint32 | The 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
Name | Type | Description |
---|---|---|
_to | address | The address to call. |
_whoToMimic | address | The address to mimic. |
_data | bytes | The data to pass to the call. |
Returns
Name | Type | Description |
---|---|---|
success | bool | Whether the call was successful. |
returndata | bytes | The 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
Name | Type | Description |
---|---|---|
_addr | address | The address to force-deploy the bytecodehash to. |
_bytecodeHash | bytes32 | The 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
Name | Type | Description |
---|---|---|
_to | address | The address to call. |
_whoToMimic | address | The address to mimic. |
_data | bytes | The data to pass to the call. |
Constants
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
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
enum Global {
CalldataPtr,
CallFlags,
ExtraABIData1,
ExtraABIData2,
ReturndataPtr
}
SystemContractsCaller
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
Name | Type | Description |
---|---|---|
gasLimit | uint32 | The gas limit for the call. |
to | address | The address to call. |
value | uint256 | The value to pass with the transaction. |
data | bytes | The calldata. |
Returns
Name | Type | Description |
---|---|---|
success | bool | Whether 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
Name | Type | Description |
---|---|---|
gasLimit | uint32 | The gas limit for the call. |
to | address | The address to call. |
value | uint128 | The value to pass with the transaction. |
data | bytes | The calldata. |
Returns
Name | Type | Description |
---|---|---|
success | bool | Whether the transaction has been successful. |
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
gasLimit | uint32 | The gas limit for the call. |
to | address | The address to call. |
value | uint128 | The value to pass with the transaction. |
data | bytes | The calldata. |
Returns
Name | Type | Description |
---|---|---|
returnData | bytes | The 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
Name | Type | Description |
---|---|---|
dataOffset | uint32 | Calldata offset in memory. Provide 0 unless using custom pointer. |
memoryPage | uint32 | Memory page to use. Provide 0 unless using custom pointer. |
dataStart | uint32 | The start of the calldata slice. Provide the offset in memory if not using custom pointer. |
dataLength | uint32 | The calldata length. Provide the length of the calldata in bytes unless using custom pointer. |
gasPassed | uint32 | The gas to pass with the call. |
shardId | uint8 | Of the account to call. Currently only 0 is supported. |
forwardingMode | CalldataForwardingMode | The forwarding mode to use: - provide CalldataForwardingMode.UseHeap when using your current memory - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer. |
isConstructorCall | bool | Whether the call will be a call to the constructor (ignored when the caller is not a system contract). |
isSystemCall | bool | Whether the call will have the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
farCallAbi | uint256 | The 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
Name | Type | Description |
---|---|---|
gasPassed | uint32 | The gas to pass with the call. |
shardId | uint8 | Of the account to call. Currently only 0 is supported. |
forwardingMode | CalldataForwardingMode | The forwarding mode to use: - provide CalldataForwardingMode.UseHeap when using your current memory - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer. |
isConstructorCall | bool | Whether the call will be a call to the constructor (ignored when the caller is not a system contract). |
isSystemCall | bool | Whether the call will have the isSystem flag. |
Returns
Name | Type | Description |
---|---|---|
farCallAbiWithEmptyFatPtr | uint256 | The far call ABI with zero fat pointer fields. |
Constants
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
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
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
Name | Type | Description |
---|---|---|
<none> | bool | If this bytecode hash for EVM contract or not |
bytecodeLenInBytes
function bytecodeLenInBytes(bytes32 _bytecodeHash)
internal
pure
returns (uint256 codeLengthInBytes);
Returns
Name | Type | Description |
---|---|---|
codeLengthInBytes | uint256 | The bytecode length in bytes |
bytecodeLenInWords
function bytecodeLenInWords(bytes32 _bytecodeHash)
internal
pure
returns (uint256 codeLengthInWords);
Returns
Name | Type | Description |
---|---|---|
codeLengthInWords | uint256 | The 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
Name | Type | Description |
---|---|---|
_bytecodeHash | bytes32 | The bytecode hash for which it is needed to set the constructing flag |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
_bytecodeHash | bytes32 | The bytecode hash for which it is needed to set the constructing flag |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes32 | The 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
Name | Type | Description |
---|---|---|
_bytecode | bytes | The bytecode to hash. |
Returns
Name | Type | Description |
---|---|---|
hashedBytecode | bytes32 | The 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
Name | Type | Description |
---|---|---|
_evmBytecodeLen | uint256 | The length of original EVM bytecode in bytes |
_paddedBytecode | bytes | The padded EVM bytecode to hash. |
Returns
Name | Type | Description |
---|---|---|
hashedEVMBytecode | bytes32 | The 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
Name | Type | Description |
---|---|---|
_sender | address | The account that deploys the contract. |
_salt | bytes32 | The create2 salt. |
_bytecodeHash | bytes32 | The hash of the init code of the new contract. |
Returns
Name | Type | Description |
---|---|---|
newAddress | address | The 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
Name | Type | Description |
---|---|---|
_sender | address | The account that deploys the contract. |
_senderNonce | uint256 | The deploy nonce of the sender's account. |