Проверенный контрактТочноеMIT
PermissionlessValidator
Адрес0xbec65e124ecea2801e655db9ee029bd45db9216a
- Баланс
0 ETH
- Транзакций
0
- Компилятор
solc 0.8.28
- Тот же код
ещё 5 контрактов
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 9 999 999 прогонов
- Версия EVM
- prague
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 25 444 238
- Транзакция создания
- 0x6663fc0592…3d0cc2094c
11 файлов
- contracts/state-transition/validators/PermissionlessValidator.solглавный2,62 КБ
- ../system-contracts/contracts/Constants.sol10,57 КБ
- contracts/common/Config.sol15,2 КБ
- contracts/common/L1ContractErrors.sol14,13 КБ
- contracts/common/Messaging.sol21,68 КБ
- contracts/common/ReentrancyGuard.sol4,06 КБ
- contracts/state-transition/chain-interfaces/ICommitter.sol7,94 КБ
- contracts/state-transition/chain-interfaces/IExecutor.sol9,89 КБ
- contracts/state-transition/chain-interfaces/IZKChainBase.sol507 Б
- lib/openzeppelin-contracts-upgradeable-v4/contracts/proxy/utils/Initializable.sol6,64 КБ
- lib/openzeppelin-contracts-upgradeable-v4/contracts/utils/AddressUpgradeable.sol9,38 КБ
contracts/state-transition/validators/PermissionlessValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {ReentrancyGuard} from "../../common/ReentrancyGuard.sol";
import {IExecutor} from "../chain-interfaces/IExecutor.sol";
import {ICommitter} from "../chain-interfaces/ICommitter.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable-v4/proxy/utils/Initializable.sol";
/// @author Matter Labs
/// @custom:security-contact [email protected]
/// @notice Smart contract used as an entry point for settling batches in Priority Mode.
/// It allows anyone to commit, prove, and execute batches in one go.
///
/// @dev The smart contract is intended to be used for Stage 1 ZK chains when their operators
/// fail to process priority transactions and priority mode is activated.
/// The chain contract is responsible for enforcing proper access control
/// (i.e., ensuring that only this contract can settle batches after Priority Mode is entered).
/// @dev Expected to be deployed as a TransparentUpgradeableProxy.
contract PermissionlessValidator is ReentrancyGuard, Initializable {
constructor() {
// Disable initialization to prevent Parity hack.
_disableInitializers();
}
/// @notice Initializes the contract.
function initialize() external initializer reentrancyGuardInitializer {}
/// @notice Commit, prove, and execute the same batch range atomically.
/// @param _chainAddress The ZKsync chain contract address where to settle batches.
/// @param _processBatchFrom The first batch in the range.
/// @param _processBatchTo The last batch in the range.
/// @param _commitData The calldata blob for the commit step.
/// @param _proveData The calldata blob for the prove step.
/// @param _executeData The calldata blob for the execute step.
function settleBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _commitData,
bytes calldata _proveData,
bytes calldata _executeData
) external nonReentrant {
ICommitter(_chainAddress).commitBatchesSharedBridge(
_chainAddress,
_processBatchFrom,
_processBatchTo,
_commitData
);
IExecutor(_chainAddress).proveBatchesSharedBridge(
_chainAddress,
_processBatchFrom,
_processBatchTo,
_proveData
);
IExecutor(_chainAddress).executeBatchesSharedBridge(
_chainAddress,
_processBatchFrom,
_processBatchTo,
_executeData
);
}
}
../system-contracts/contracts/Constants.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.20;
/// @notice This file contains pure value constants and enums.
/// Interface-typed constants (e.g. IContractDeployer constant DEPLOYER_SYSTEM_CONTRACT) are in Contracts.sol.
/// @dev 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; // 2^15
/// @dev 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;
/// @dev 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; // 2^16 - 1
/// @dev The offset from which the built-in, but user space contracts are located.
uint160 constant USER_CONTRACTS_OFFSET = MAX_SYSTEM_CONTRACT_ADDRESS + 1;
address constant ECRECOVER_SYSTEM_CONTRACT = address(0x01);
address constant SHA256_SYSTEM_CONTRACT = address(0x02);
address constant IDENTITY_SYSTEM_CONTRACT = address(0x04);
address constant MODEXP_SYSTEM_CONTRACT = address(0x05);
address constant ECADD_SYSTEM_CONTRACT = address(0x06);
address constant ECMUL_SYSTEM_CONTRACT = address(0x07);
address constant ECPAIRING_SYSTEM_CONTRACT = address(0x08);
/// @dev 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;
/// @dev 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;
address payable constant BOOTLOADER_FORMAL_ADDRESS = payable(address(SYSTEM_CONTRACTS_OFFSET + 0x01));
// A contract that is allowed to deploy any codehash
// on any address. To be used only during an upgrade.
address constant FORCE_DEPLOYER = address(SYSTEM_CONTRACTS_OFFSET + 0x07);
address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09);
// It will be a different value for tests, while shouldn't. But for now, this constant is not used by other contracts, so that's fine.
address constant EVENT_WRITER_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x0d);
// Hardcoded because even for tests we should keep the address. (Instead `SYSTEM_CONTRACTS_OFFSET + 0x10`)
// Precompile call depends on it.
// And we don't want to mock this contract.
address constant KECCAK256_SYSTEM_CONTRACT = address(0x8010);
address constant CODE_ORACLE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x12);
address constant EVM_GAS_MANAGER = address(SYSTEM_CONTRACTS_OFFSET + 0x13);
address constant EVM_PREDEPLOYS_MANAGER = address(SYSTEM_CONTRACTS_OFFSET + 0x14);
address constant L2_DA_VALIDATOR = address(SYSTEM_CONTRACTS_OFFSET + 0x16);
address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(USER_CONTRACTS_OFFSET + 0x04);
// Note, that on its own this contract does not provide much functionality, but having it on a constant address
// serves as a convenient storage for its bytecode to be accessible via `extcodehash`.
address constant SLOAD_CONTRACT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x06);
address constant WRAPPED_BASE_TOKEN_IMPL_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x07);
address constant L2_CHAIN_ASSET_HANDLER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0a);
address constant L2_UPGRADEABLE_BEACON_DEPLOYER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0b);
address constant L2_SYSTEM_CONTRACT_PROXY_ADMIN_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0c);
address constant L2_INTEROP_CENTER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0d);
address constant L2_INTEROP_HANDLER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0e);
address constant L2_ASSET_TRACKER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x0f);
address constant GW_ASSET_TRACKER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x10);
/// @dev 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;
/// @dev The maximal msg.value that context can have
uint256 constant MAX_MSG_VALUE = type(uint128).max;
/// @dev Prefix used during derivation of account addresses using CREATE2
/// @dev keccak256("zksyncCreate2")
bytes32 constant CREATE2_PREFIX = 0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494;
/// @dev Prefix used during derivation of account addresses using CREATE
/// @dev keccak256("zksyncCreate")
bytes32 constant CREATE_PREFIX = 0x63bae3a9951d38e8a3fbb7b70909afc1200610fc5bc55ade242f815974674f23;
/// @dev Prefix used during derivation of account addresses using CREATE2 within the EVM
bytes1 constant CREATE2_EVM_PREFIX = 0xff;
/// @dev 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;
/// @dev Bytes in raw L2 to L1 log
/// @dev 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;
/// @dev The value of default leaf hash for L2 to L1 logs Merkle tree
/// @dev An incomplete fixed-size tree is filled with this value to be a full binary tree
/// @dev Actually equal to the `keccak256(new bytes(L2_TO_L1_LOG_SERIALIZE_SIZE))`
bytes32 constant L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH = 0x72abee45b59e344af8a6e520241c4744aff26ed411f4c4b00f8af09adada43ba;
/// @dev The current version of state diff compression being used.
uint256 constant STATE_DIFF_COMPRESSION_VERSION_NUMBER = 1;
/// @dev Enum used for system logs emitted by the bootloader.
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,
// Note, that it is important that `PREV_BATCH_HASH_KEY` has position
// `4` since it is the same as it was in the previous protocol version and
// it is the only one that is emitted before the system contracts are upgraded.
PREV_BATCH_HASH_KEY,
L2_DA_VALIDATOR_OUTPUT_HASH_KEY,
USED_L2_DA_VALIDATION_COMMITMENT_SCHEME_KEY,
MESSAGE_ROOT_ROLLING_HASH_KEY,
L2_TXS_STATUS_ROLLING_HASH_KEY,
SETTLEMENT_LAYER_CHAIN_ID_KEY,
EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY
}
/// @dev 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;
uint256 constant L2_TO_L1_LOGS_MERKLE_TREE_DEPTH = 14 + 1;
/// @dev The length of the derived key in bytes inside compressed state diffs.
uint256 constant DERIVED_KEY_LENGTH = 32;
/// @dev The length of the enum index in bytes inside compressed state diffs.
uint256 constant ENUM_INDEX_LENGTH = 8;
/// @dev The length of value in bytes inside compressed state diffs.
uint256 constant VALUE_LENGTH = 32;
/// @dev The length of the compressed initial storage write in bytes.
uint256 constant COMPRESSED_INITIAL_WRITE_SIZE = DERIVED_KEY_LENGTH + VALUE_LENGTH;
/// @dev The length of the compressed repeated storage write in bytes.
uint256 constant COMPRESSED_REPEATED_WRITE_SIZE = ENUM_INDEX_LENGTH + VALUE_LENGTH;
/// @dev The position from which the initial writes start in the compressed state diffs.
uint256 constant INITIAL_WRITE_STARTING_POSITION = 4;
/// @dev Each storage diffs consists of the following elements:
/// [20bytes address][32bytes key][32bytes derived key][8bytes enum index][32bytes initial value][32bytes final value]
/// @dev The offset of the derived key in a storage diff.
uint256 constant STATE_DIFF_DERIVED_KEY_OFFSET = 52;
/// @dev The offset of the enum index in a storage diff.
uint256 constant STATE_DIFF_ENUM_INDEX_OFFSET = 84;
/// @dev The offset of the final value in a storage diff.
uint256 constant STATE_DIFF_FINAL_VALUE_OFFSET = 124;
/// @dev Total number of bytes in a blob. Blob = 4096 field elements * 31 bytes per field element
/// @dev EIP-4844 defines it as 131_072 but we use 4096 * 31 within our circuits to always fit within a field element
/// @dev Our circuits will prove that a EIP-4844 blob and our internal blob are the same.
uint256 constant BLOB_SIZE_BYTES = 126_976;
/// @dev Max number of blobs currently supported
uint256 constant MAX_NUMBER_OF_BLOBS = 6;
/// @dev Marker of EraVM bytecode
uint8 constant ERA_VM_BYTECODE_FLAG = 1;
/// @dev Marker of EVM bytecode
uint8 constant EVM_BYTECODE_FLAG = 2;
address constant SERVICE_CALL_PSEUDO_CALLER = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
/// @dev Pubdata commitment scheme used for DA.
/// @param NONE Invalid option.
/// @param EMPTY_NO_DA No DA commitment, used by Validiums.
/// @param PUBDATA_KECCAK256 Keccak of stateDiffHash and keccak(pubdata). Can be used by custom DA solutions.
/// @param BLOBS_AND_PUBDATA_KECCAK256 This commitment includes EIP-4844 blobs data. Used by default RollupL1DAValidator.
/// @param BLOBS_ZKSYNC_OS Keccak of blob versioned hashes filled with pubdata. This commitment scheme is used only for ZKsyncOS.
enum L2DACommitmentScheme {
NONE,
EMPTY_NO_DA,
PUBDATA_KECCAK256,
BLOBS_AND_PUBDATA_KECCAK256,
BLOBS_ZKSYNC_OS
}
/// @dev The metadata version that is supported by the ZK Chains to prove that an L2->L1 log was included in a batch.
uint256 constant SUPPORTED_PROOF_METADATA_VERSION = 1;
/// @dev The server has a hardcoded chainId 270 which is updated to the real value in the L2GenesisUpgradeTxs
/// see link: https://github.com/matter-labs/zksync-era/blob/54dc61c6faff53d314227ffe26961b1abfc999a7/core/node/genesis/src/lib.rs#L182
/// https://github.com/matter-labs/zksync-era/blob/54dc61c6faff53d314227ffe26961b1abfc999a7/core/lib/basic_types/src/lib.rs#L228
uint256 constant HARD_CODED_CHAIN_ID = 270;
contracts/common/Config.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
// solhint-disable no-unused-import
import {
L2DACommitmentScheme,
L2_TO_L1_LOG_SERIALIZE_SIZE,
L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH,
L2_TO_L1_LOGS_MERKLE_TREE_DEPTH,
SUPPORTED_PROOF_METADATA_VERSION,
HARD_CODED_CHAIN_ID
} from "system-contracts/contracts/Constants.sol";
// solhint-enable no-unused-import
/// @dev `keccak256("")`
bytes32 constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
/// @dev The maximum length of the bytes array with L2 -> L1 logs
uint256 constant MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES = 4 + L2_TO_L1_LOG_SERIALIZE_SIZE * 512;
bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = bytes32(0);
/// @dev Denotes the type of the ZKsync Era transaction that came from L1.
uint256 constant PRIORITY_OPERATION_L2_TX_TYPE = 255;
/// @dev Denotes the type of the ZKsync Era transaction that is used for system upgrades.
uint256 constant SYSTEM_UPGRADE_L2_TX_TYPE = 254;
/// @dev Denotes the type of the ZKsync OS transaction that came from L1.
uint256 constant ZKSYNC_OS_PRIORITY_OPERATION_L2_TX_TYPE = 127;
/// @dev Denotes the type of the ZKsync OS transaction that is used for system upgrades.
uint256 constant ZKSYNC_OS_SYSTEM_UPGRADE_L2_TX_TYPE = 126;
/// @dev The maximal allowed difference between protocol minor versions in an upgrade. The 100 gap is needed
/// in case a protocol version has been tested on testnet, but then not launched on mainnet, e.g.
/// due to a bug found.
/// We are allowed to jump at most 100 minor versions at a time. The major version is always expected to be 0.
uint256 constant MAX_ALLOWED_MINOR_VERSION_DELTA = 100;
/// @dev Maximum time a priority transaction may remain unprocessed before Priority Mode (escape hatch) can be activated.
/// Note: This is not the full user exit window. The effective exit window is`UPGRADE_NOTICE_PERIOD` - `PRIORITY_EXPIRATION`.
uint256 constant PRIORITY_EXPIRATION = 4 days;
// @dev The chainId of Ethereum Mainnet
uint256 constant MAINNET_CHAIN_ID = 1;
// @dev The chainId of Ethereum Sepolia testnet
uint256 constant SEPOLIA_CHAIN_ID = 11155111;
/// @dev Timestamp - seconds since unix epoch. This value will be used on the mainnet.
uint256 constant MAINNET_COMMIT_TIMESTAMP_NOT_OLDER = 3 days;
/// @dev Timestamp - seconds since unix epoch. This value will be used on testnets.
uint256 constant TESTNET_COMMIT_TIMESTAMP_NOT_OLDER = 30 days;
/// @dev Maximum available error between real commit batch timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 12 seconds)
uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 1 hours;
/// @dev Shift to apply to verify public input before verifying.
uint256 constant PUBLIC_INPUT_SHIFT = 32;
/// @dev The maximum number of L2 gas that a user can request for an L2 transaction
uint256 constant MAX_GAS_PER_TRANSACTION = 80_000_000;
/// @dev Even though the price for 1 byte of pubdata is 16 L1 gas, we have a slightly increased
/// value.
uint256 constant L1_GAS_PER_PUBDATA_BYTE = 17;
/// @dev The intrinsic cost of the L1->l2 transaction in computational L2 gas
uint256 constant L1_TX_INTRINSIC_L2_GAS = 167_157;
/// @dev The intrinsic cost of the L1->l2 transaction in pubdata
uint256 constant L1_TX_INTRINSIC_PUBDATA = 88;
/// @dev The minimal base price for L1 transaction
uint256 constant L1_TX_MIN_L2_GAS_BASE = 173_484;
/// @dev The number of L2 gas the transaction starts costing more with each 544 bytes of encoding
uint256 constant L1_TX_DELTA_544_ENCODING_BYTES = 1656;
/// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency
uint256 constant L1_TX_DELTA_FACTORY_DEPS_L2_GAS = 2473;
/// @dev The number of L2 gas an L1->L2 transaction gains with each new factory dependency
uint256 constant L1_TX_DELTA_FACTORY_DEPS_PUBDATA = 64;
/// @dev The number of pubdata an L1->L2 transaction requires with each new factory dependency
uint256 constant MAX_NEW_FACTORY_DEPS = 64;
/// @dev The L2 gasPricePerPubdata required to be used in bridges.
uint256 constant REQUIRED_L2_GAS_PRICE_PER_PUBDATA = 800;
/// @dev Minimum interval between token multiplier updates.
uint256 constant PRICE_UPDATE_INTERVAL = 1 days;
/// @dev Max allowed price increase per update, as a ratio (e.g. 13/10 = 1.3x).
uint256 constant MAX_PRICE_CHANGE_NUMERATOR = 13;
uint256 constant MAX_PRICE_CHANGE_DENOMINATOR = 10;
/// @dev Reference L1 gas price used for price-change bound calculations.
uint256 constant PRICE_REFERENCE_L1_GAS = 1 gwei;
/// @dev The native price for L1->L2 transactions in ZKsync OS.
uint256 constant ZKSYNC_OS_L1_TX_NATIVE_PRICE = 10;
/// @dev The intrinsic cost of the L1->L2 transaction in computational L2 gas for ZKsync OS.
uint256 constant L1_TX_INTRINSIC_L2_GAS_ZKSYNC_OS = 21000;
/// @dev The cost of calldata byte for the L1->L2 transaction in computational L2 gas for ZKsync OS.
uint256 constant L1_TX_CALLDATA_PRICE_L2_GAS_ZKSYNC_OS = 16;
/// @dev The static part of the L1->l2 transaction native cost for ZKsync OS.
/// It includes hashing (126_000) and coinbase/refund mint_base_token intrinsic native worst case costs.
uint256 constant L1_TX_STATIC_NATIVE_ZKSYNC_OS = 2_875_420;
/// @dev The encoding cost per keccak256 round(136 bytes) of the L1->l2 transaction in native resource for ZKsync OS.
uint256 constant L1_TX_ENCODING_136_BYTES_COST_NATIVE_ZKSYNC_OS = 17500;
/// @dev The cost of calldata byte for the L1->L2 transaction in native resource for ZKsync OS.
uint256 constant L1_TX_CALLDATA_COST_NATIVE_ZKSYNC_OS = 1;
/// @dev The intrinsic cost of the L1->l2 transaction in pubdata for ZKsync OS
/// It includes tx log, coinbase, treasury, refund recipient and asset tracker pubdata.
uint256 constant L1_TX_INTRINSIC_PUBDATA_ZKSYNC_OS = 351;
/// @dev The native per gas ratio for 0 gas price(service/upgrade/gateway) transactions in ZKsync OS.
/// This value is big enough to cover computational native resources usage for any operations.
uint256 constant FREE_TX_NATIVE_PER_GAS = 10_000;
/// @dev The mask which should be applied to the packed batch and L2 block timestamp in order
/// to obtain the L2 block timestamp. Applying this mask is equivalent to calculating modulo 2**128
uint256 constant PACKED_L2_BLOCK_TIMESTAMP_MASK = 0xffffffffffffffffffffffffffffffff;
/// @dev Address of the point evaluation precompile used for EIP-4844 blob verification.
address constant POINT_EVALUATION_PRECOMPILE_ADDR = address(0x0A);
/// @dev The overhead for a transaction slot in L2 gas.
/// It is roughly equal to 80kk/MAX_TRANSACTIONS_IN_BATCH, i.e. how many gas would an L1->L2 transaction
/// need to pay to compensate for the batch being closed.
/// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate
/// the operator in case the batch is closed because of tx slots filling up.
uint256 constant TX_SLOT_OVERHEAD_L2_GAS = 10000;
/// @dev The overhead for each byte of the bootloader memory that the encoding of the transaction.
/// It is roughly equal to 80kk/BOOTLOADER_MEMORY_FOR_TXS, i.e. how many gas would an L1->L2 transaction
/// need to pay to compensate for the batch being closed.
/// @dev It is expected that the L1 contracts will enforce that the L2 gas price will be high enough to compensate
/// the operator in case the batch is closed because of the memory for transactions being filled up.
uint256 constant MEMORY_OVERHEAD_GAS = 10;
/// @dev The maximum gas limit for a priority transaction in L2.
uint256 constant PRIORITY_TX_MAX_GAS_LIMIT = 72_000_000;
/// @dev the address used to identify eth as the base token for chains.
address constant ETH_TOKEN_ADDRESS = address(1);
/// @dev the value returned in bridgehubDeposit in the TwoBridges function.
bytes32 constant TWO_BRIDGES_MAGIC_VALUE = bytes32(uint256(keccak256("TWO_BRIDGES_MAGIC_VALUE")) - 1);
/// @dev https://eips.ethereum.org/EIPS/eip-1352
address constant BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS = address(uint160(type(uint16).max));
/// @dev the maximum number of supported chains, this is an arbitrary limit.
/// @dev Note, that in case of a malicious Bridgehub admin, the total number of chains
/// can be up to 2 times higher. This may be possible, in case the old ChainTypeManager
/// had `100` chains and these were migrated to the Bridgehub only after `MAX_NUMBER_OF_ZK_CHAINS`
/// were added to the bridgehub via creation of new chains.
uint256 constant MAX_NUMBER_OF_ZK_CHAINS = 100;
/// @dev Used as the `msg.sender` for transactions that relayed via a settlement layer.
address constant SETTLEMENT_LAYER_RELAY_SENDER = address(uint160(0x1111111111111111111111111111111111111111));
/// @dev The virtual address of the L1 settlement layer.
address constant L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS = address(
uint160(uint256(keccak256("L1_SETTLEMENT_LAYER_VIRTUAL_ADDRESS")) - 1)
);
struct PriorityTreeCommitment {
uint256 nextLeafIndex;
uint256 startIndex;
uint256 unprocessedIndex;
bytes32[] sides;
}
// Info that allows to restore a chain.
struct ZKChainCommitment {
/// @notice Total number of executed batches i.e. batches[totalBatchesExecuted] points at the latest executed batch
/// (batch 0 is genesis)
uint256 totalBatchesExecuted;
/// @notice Total number of proved batches i.e. batches[totalBatchesProved] points at the latest proved batch
uint256 totalBatchesVerified;
/// @notice Total number of committed batches i.e. batches[totalBatchesCommitted] points at the latest committed
/// batch
uint256 totalBatchesCommitted;
/// @notice The hash of the L2 system contracts ugpgrade transaction.
/// @dev It is non zero if the migration happens while the upgrade is not yet finalized.
bytes32 l2SystemContractsUpgradeTxHash;
/// @notice The batch when the system contracts upgrade transaction was executed.
/// @dev It is non-zero if the migration happens while the batch where the upgrade tx was present
/// has not been finalized (executed) yet.
uint256 l2SystemContractsUpgradeBatchNumber;
/// @notice The hashes of the batches that are needed to keep the blockchain working.
/// @dev The length of the array is equal to the `totalBatchesCommitted - totalBatchesExecuted + 1`, i.e. we need
/// to store all the unexecuted batches' hashes + 1 latest executed one.
bytes32[] batchHashes;
/// @notice Commitment to the priority merkle tree.
PriorityTreeCommitment priorityTree;
/// @notice Whether a chain is a permanent rollup.
bool isPermanentRollup;
/// @notice The precommitment to the transactions of the latest batch.
bytes32 precommitmentForTheLatestBatch;
}
/// @dev Used as the `msg.sender` for system service transactions.
address constant SERVICE_TRANSACTION_SENDER = address(uint160(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF));
/// @dev To avoid higher costs the writes, we avoid making the slot zero.
/// This ensures that the cost of writes is always 5k and avoids the 20k initial write from the non-zero value.
bytes32 constant DEFAULT_PRECOMMITMENT_FOR_THE_LAST_BATCH = bytes32(uint256(1));
/// @dev The length of a packed transaction precommitment in bytes. It consists of two parts: 32-byte tx hash and 1-byte status (0 or 1).
uint256 constant PACKED_L2_PRECOMMITMENT_LENGTH = 33;
/// @dev The L2 data availability commitment scheme that permanent rollups are expected to use.
L2DACommitmentScheme constant ROLLUP_L2_DA_COMMITMENT_SCHEME = L2DACommitmentScheme.BLOBS_AND_PUBDATA_KECCAK256;
/// @dev The start of the pause deposits time window. We pause when migrating to/from gateway.
/// @dev It is set to 0 in this release, since stage1 is not yet supported for chains that settle on top of ZK Gateway.
uint256 constant PAUSE_DEPOSITS_TIME_WINDOW_START_MAINNET = 0;
/// @dev The delay from `pausedDepositsTimestamp` from which the migration is allowed. It equals the PAUSE_DEPOSITS_TIME_WINDOW_START.
/// @dev It is set to 0 in this release, since stage1 is not yet supported for chains that settle on top of ZK Gateway.
uint256 constant CHAIN_MIGRATION_TIME_WINDOW_START_MAINNET = 0;
uint256 constant PAUSE_DEPOSITS_TIME_WINDOW_START_TESTNET = 0;
uint256 constant CHAIN_MIGRATION_TIME_WINDOW_START_TESTNET = 0;
/// @dev Default overhead value in L1 gas for each batch during chain creation.
uint32 constant DEFAULT_BATCH_OVERHEAD_L1_GAS = 1_000_000;
/// @dev Default maximum amount of pubdata per batch during chain creation.
uint32 constant DEFAULT_MAX_PUBDATA_PER_BATCH = 120_000;
/// @dev Default maximum amount of L2 gas per batch during chain creation.
uint32 constant DEFAULT_MAX_L2_GAS_PER_BATCH = 80_000_000;
/// @dev Default maximum amount of pubdata for priority transactions during chain creation.
uint32 constant DEFAULT_PRIORITY_TX_MAX_PUBDATA = 99_000;
/// @dev Default minimum L2 gas price (in wei) for L1->L2 transactions during chain creation.
uint64 constant DEFAULT_MINIMAL_L2_GAS_PRICE = 250_000_000;
/// @notice The struct that describes whether users will be charged for pubdata for L1->L2 transactions.
/// @param Rollup The users are charged for pubdata & it is priced based on the gas price on Ethereum.
/// @param Validium The pubdata is considered free with regard to the L1 gas price.
enum PubdataPricingMode {
Rollup,
Validium
}
/// @dev Default pubdata pricing mode during chain creation.
PubdataPricingMode constant DEFAULT_PUBDATA_PRICING_MODE = PubdataPricingMode.Rollup;
/// @dev Default maximum gas limit for priority transactions during chain creation.
uint64 constant DEFAULT_PRIORITY_TX_MAX_GAS_LIMIT = 72_000_000;
/// @dev The initial balance of the BaseTokenHolder contract (2^127 - 1).
/// @dev Used to derive the real circulating supply: circulatingSupply = INITIAL - TotalSupplyBeforeMigration
uint256 constant INITIAL_BASE_TOKEN_HOLDER_BALANCE = (2 ** 127) - 1;
/// @dev The total number of supported interop attributes.
uint256 constant SUPPORTED_INTEROP_ATTRIBUTES = 5;
/// @dev Migration number used when a chain migrates from L1 to a settlement layer.
uint256 constant MIGRATION_NUMBER_L1_TO_SETTLEMENT_LAYER = 1;
/// @dev Migration number used when a chain returns from a settlement layer back to L1.
uint256 constant MIGRATION_NUMBER_SETTLEMENT_LAYER_TO_L1 = 2;
/// @dev Iterated migrations are not supported; chain can migrate only to settlement layer and back once.
uint256 constant MAX_ALLOWED_NUMBER_OF_MIGRATIONS = 2;
/// @dev The mask that should be applied to the packed log data containing both the number of L2 and L1 transactions
/// processed in the batch. Applying this mask is equivalent to calculating modulo 2**128.
uint256 constant PACKED_NUMBER_OF_L1_TRANSACTIONS_LOG_MASK = 0xffffffffffffffffffffffffffffffff;
/// @dev Bit offset for extracting the upper 128 bits (L2 tx count) from the packed log value.
uint256 constant PACKED_NUMBER_OF_L2_TRANSACTIONS_LOG_SPLIT_BITS = 128;
contracts/common/L1ContractErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import {L2DACommitmentScheme} from "./Config.sol";
// 0x5ecf2d7a
error AccessToFallbackDenied(address target, address invoker);
// 0x3995f750
error AccessToFunctionDenied(address target, bytes4 selector, address invoker);
// 0x0dfb42bf
error AddressAlreadySet(address addr);
// 0x86bb51b8
error AddressHasNoCode(address);
// 0x1f73225f
error AddressMismatch(address expected, address supplied);
// 0x42573d7a
error AddressNotZero();
// 0xb577eb6c
error AlreadyDangerousContract(address);
// 0x2a5989a0
error AlreadyPermanentRollup();
// 0x0bfcef28
error AlreadyWhitelisted(address);
// 0x5e85ae73
error AmountMustBeGreaterThanZero();
// 0xfde974f4
error AssetHandlerDoesNotExist(bytes32 assetId);
// 0x64107968
error AssetHandlerNotRegistered(bytes32 assetId);
// 0xfe919e28
error AssetIdAlreadyRegistered();
// 0x1294e9e1
error AssetIdMismatch(bytes32 expected, bytes32 supplied);
// 0x04a0b7e9
error AssetIdNotSupported(bytes32 assetId);
// 0x11832de8
error AssetRouterAllowanceNotZero();
// 0x9b821ed7
error BadTransferDataLength();
// 0x6ef9a972
error BaseTokenGasPriceDenominatorNotSet();
// 0x764c57db
error BaseTokenHolderAlreadyInitialized();
// 0xd3cd4bd2
error BaseTokenHolderMintFailed();
// 0x7f9159de
error BaseTokenPreV31TotalSupplyAlreadySet();
// 0x00a6b592
error BaseTokenPreV31TotalSupplyNotSet();
// 0xe3ec2bc9
error BaseTokenTransferFailed();
// 0x55ad3fd3
error BatchHashMismatch(bytes32 expected, bytes32 actual);
// 0xbd4455ff
error BatchNumberMismatch(uint256 expectedBatchNumber, uint256 providedBatchNumber);
// 0x41c329f7
error BatchTimestampGreaterThanLastL2BlockTimestamp();
// 0x6cf12312
error BridgeHubAlreadyRegistered();
// 0xdb538614
error BridgeMintNotImplemented();
// 0xaa5f6180
error BurningNativeWETHNotSupported();
// 0x25d8333c
error CallerNotTimerAdmin();
// 0x3331e9c0
error CallNotAllowed(bytes call);
// 0xe85392f9
error CanOnlyProcessOneBatch();
// 0x00c6ead2
error CantExecuteUnprovenBatches();
// 0xe18cb383
error CantRevertExecutedBatch();
// 0x78d2ed02
error ChainAlreadyLive();
// 0x24591d89
error ChainIdAlreadyExists();
// 0x717a1656
error ChainIdCantBeCurrentChain();
// 0x6b617b38
error ChainIdIsHardcoded();
// 0xa179f8c9
error ChainIdMismatch();
// 0x23f3c357
error ChainIdNotRegistered(uint256 chainId);
// 0x8f620a06
error ChainIdTooBig();
// 0x5e361ef9
error ChainRequiresValidatorsSignaturesForCommit();
// 0x8746f42f
error ConstructorsNotSupported();
// 0xec273439
error CTMAlreadyRegistered();
// 0xc630ef3c
error CTMNotRegistered();
// 0x13df796c
error CutDataForProtocolVersionNotAvailable(uint256 oldProtocolVersion);
// 0x907f8e51
error DeadlineNotYetPassed();
// 0xf2885eb3
error DefaultAdminTransferNotAllowed();
// 0xf7a01e4d
error DelegateCallFailed(bytes returnData);
// 0x0a8ed92c
error DenominatorIsZero();
// 0xb4f54111
error DeployFailed();
// 0x138ee1a3
error DeployingBridgedTokenForNativeToken();
// 0x42bce528
error DepositDoesNotExist(bytes32, bytes32);
// 0xad2fa98e
error DepositExists();
// 0x0e7ee319
error DiamondAlreadyFrozen();
// 0xa7151b9a
error DiamondNotFrozen();
// 0x7138356f
error EmptyAddress();
// 0x2d4d012f
error EmptyAssetId();
// 0x1c25715b
error EmptyBytes32();
// 0x99d8fec9
error EmptyData();
// 0x95b66fe9
error EmptyDeposit();
// 0x84286507
error EmptyPrecommitData(uint256 batchNumber);
// 0x456f8f7a
error EmptyProofLength();
// 0x05410cbc
error EmptyPublicInputsLength();
// 0x876e8b23
error EraBytecodeAlreadyPublished(bytes32 bytecodeHash);
// 0x627e0872
error ETHDepositNotSupported();
// 0x61733a89
error EVMBytecodeAlreadyPublished(bytes32 bytecodeHash);
// 0xf4072616
error ExecuteMessageFailed();
// 0xac4a3f98
error FacetExists(bytes4 selector, address);
// 0x3fce21be
error FeeParamsChangeTooLarge(uint256 oldPrice, uint256 newPrice, uint256 maxAllowedPrice);
// 0xc91cf3b1
error GasPerPubdataMismatch();
// 0x5ca97564
error GenesisBatchCommitmentIncorrect();
// 0x6d4a7df8
error GenesisBatchCommitmentZero();
// 0x7940c83f
error GenesisBatchHashZero();
// 0xb4fc6835
error GenesisIndexStorageZero();
// 0x3a1a8589
error GenesisUpgradeZero();
// 0xd356e6ba
error HashedLogIsDefault();
// 0x0b08d5be
error HashMismatch(bytes32 expected, bytes32 actual);
// 0xd7d93e1f
error IncorrectBatchBounds(
uint256 processFromExpected,
uint256 processToExpected,
uint256 processFromProvided,
uint256 processToProvided
);
// 0xc1b4bc7b
error IncorrectBatchChainId(uint256, uint256);
// 0xdd381a4c
error IncorrectBridgeHubAddress(address bridgehub);
// 0x1929b7de
error IncorrectTokenAddressFromNTV(bytes32 assetId, address tokenAddress);
// 0x03eb8b54
error InsufficientFunds(uint256 required, uint256 actual);
// 0x9bf8b9aa
error InvalidBatchNumber(uint256 provided, uint256 expected);
// 0xd438e1fa
error InvalidBlockRange(uint64 batchNumber, uint64 from, uint64 to);
// 0xcbd9d2e0
error InvalidCaller(address);
// 0x7a47c9a2
error InvalidChainId();
// 0x92daded2
error InvalidDAForPermanentRollup();
// 0x4fbe5dba
error InvalidDelay();
// 0x075aaa80
error InvalidInteropCalldata(bytes4);
// 0x3f98a77e
error InvalidL2DACommitmentScheme(L2DACommitmentScheme);
// 0xc1780bd6
error InvalidLogSender(address sender, uint256 logKey);
// 0x6eca2e4b
error InvalidMessage();
// 0xa1ec1876
error InvalidMessageRoot(bytes32 expectedMessageRoot, bytes32 providedMessageRoot);
// 0xd08a97e6
error InvalidMockProofLength();
// 0xde4c0b96
error InvalidNTVBurnData();
// 0xd8e9405c
error InvalidNumberOfBlobs(uint256 expected, uint256 numCommitments, uint256 numHashes);
// 0x99f6cc22
error InvalidPackedPrecommitmentLength(uint256 length);
// 0x09bde339
error InvalidProof();
// 0x5a1c353a
error InvalidProofFormat();
// 0x48c5fa28
error InvalidProofLengthForFinalNode();
// 0x5428eae7
error InvalidProtocolVersion();
// 0x6f1cf752
error InvalidPubdataPricingMode();
// 0x12ba286f
error InvalidSelector(bytes4 func);
// 0xbe7193d4
error InvalidSystemLogsLength();
// 0x7b7a98f1
error InvalidThreshold(uint256 max, uint256 got);
// 0xd857fbc0
error InvalidTxCountInPriorityMode(uint256 l2TxCount, uint256 l1TxCount);
// 0x5f1aa154
error InvalidUpgradeTxn(UpgradeTxVerifyParam);
// 0xfb5c22e6
error L2TimestampTooBig();
// 0x97e1359e
error L2WithdrawalMessageWrongLength(uint256 messageLen);
// 0x8efef97a
error LegacyBridgeNotSet();
// 0x29963361
error LegacyBridgeUsesNonNativeToken();
// 0xfade089a
error LegacyEncodingUsedForNonL1Token();
// 0x767eed08
error LegacyMethodForNonL1Token();
// 0xe37d2c02
error LengthIsNotDivisibleBy32(uint256 length);
// 0x1b6825bb
error LogAlreadyProcessed(uint8);
// 0x43e266b0
error MalformedBytecode(BytecodeError);
// 0xafbb7a4e
error MerkleIndexOrHeightMismatch();
// 0x9bb54c35
error MerkleIndexOutOfBounds();
// 0xc33e6128
error MerkleNothingToProve();
// 0x8e23ac1a
error MerklePathEmpty();
// 0x09aa9830
error MerklePathLengthMismatch(uint256 pathLength, uint256 expectedLength);
// 0x1c500385
error MerklePathOutOfBounds();
// 0x1b582fcf
error MerkleWrongIndex(uint256 index, uint256 maxNodeNumber);
// 0x485cfcaa
error MerkleWrongLength(uint256 newLeavesLength, uint256 leafNumber);
// 0x3312a450
error MigrationPaused();
// 0x4e98b356
error MigrationsNotPaused();
// 0xfa44b527
error MissingSystemLogs(uint256 expected, uint256 actual);
// 0x1508fb47
error MockVerifierNotSupported();
// 0x4a094431
error MsgValueMismatch(uint256 expectedMsgValue, uint256 providedMsgValue);
// 0xb385a3da
error MsgValueTooLow(uint256 required, uint256 provided);
// 0xedd74330
error MustBeEraChain();
// 0x8b7e144a
error NewDeadlineExceedsMaxDeadline();
// 0x6eef58d1
error NewDeadlineNotGreaterThanCurrent();
// 0x79cc2d22
error NoCallsProvided();
// 0xce63ce17
error NoCTMForAssetId(bytes32 assetId);
// 0xa6fef710
error NoFunctionsForDiamondCut();
// 0xcab098d8
error NoFundsTransferred();
// 0xb20b58ce
error NoLegacySharedBridge();
// 0xc4dc2673
error NonCanonicalRepresentation();
// 0xc21b1ab7
error NonEmptyCalldata();
// 0x536ec84b
error NonEmptyMsgValue();
// 0xd018e08e
error NonIncreasingTimestamp();
// 0x0105f9c0
error NonSequentialBatch();
// 0x0ac76f01
error NonSequentialVersion();
// 0x0e0ff4d9
error NonZeroBlobToVerifyZKsyncOS(uint256 index, bytes32 blobLinearHash, bytes32 blobOpeningCommitment);
// 0xfa5cd00f
error NotAllowed(address addr);
// 0x64846fe4
error NotARestriction(address addr);
// 0xf306a770
error NotAssetRouter(address sender, address assetRouter);
// 0xb49df1f2
error NotAZKChain(address addr);
// 0x7fdf8632
error NotCompatibleWithPriorityMode();
// 0x5e67e793
error NotCurrentSettlementLayer();
// 0x2b1dc354
error NotDangerousContract(address);
// 0x230f9d11
error NotEnoughSigners(uint256 provided, uint256 expected);
// 0xdd7e3621
error NotInitializedReentrancyGuard();
// 0xecb34449
error NotL1(uint256 l1ChainId, uint256 blockChainId);
// 0xc5441a63
error NotL2ToL2(uint256 sourceChainId, uint256 destinationChainId);
// 0xdf17e316
error NotWhitelisted(address);
// 0xf3ed9dfa
error OnlyEraSupported();
// 0x9d7bb13f
error OnlyNormalMode();
// 0xd702c443
error OnlyPriorityMode();
// 0x6c167909
error OnlySelfAllowed();
// 0x1a21feed
error OperationExists();
// 0xeda2fbb1
error OperationMustBePending();
// 0xe1c1ff37
error OperationMustBeReady();
// 0xb926450e
error OriginChainIdNotFound();
// 0x97da9c1c
error PayloadTooShort();
// 0x688c63e5
error PrecommitmentMismatch(uint256 batchNumber, bytes32 expected, bytes32 found);
// 0x9b48e060
error PreviousOperationNotExecuted();
// 0x67c198fe
error PriorityModeActivationTooEarly(uint256 earliestActivationTimestamp, uint256 currentTimestamp);
// 0xdbfcbbef
error PriorityModeIsNotAllowed();
// 0x2b9d9c4c
error PriorityModeRequiresPermanentRollup();
// 0xd5a99014
error PriorityOperationsRollingHashMismatch();
// 0xbeda0935
error PriorityOpsRequestTimestampMissing(uint256 requestId);
// 0xa840274f
error PriorityQueueNotReady();
// 0x1a4d284a
error PriorityTxPubdataExceedsMaxPubDataPerBatch();
// 0xa461f651
error ProtocolIdMismatch(uint256 expectedProtocolVersion, uint256 providedProtocolId);
// 0x64f94ec2
error ProtocolIdNotGreater();
// 0x959f26fb
error PubdataGreaterThanLimit(uint256 limit, uint256 length);
// 0x63c36549
error QueueIsEmpty();
// 0x0a6c1a5c
error ReconstructionMismatch(bytes32, bytes32);
// 0xab143c06
error Reentrancy();
// 0x667d17de
error RemoveFunctionFacetAddressNotZero(address facet);
// 0xa2d4b16c
error RemoveFunctionFacetAddressZero();
// 0xf6fd7071
error RemovingPermanentRestriction();
// 0x3580370c
error ReplaceFunctionFacetAddressZero();
// 0xf126e113
error RestrictionWasAlreadyPresent(address restriction);
// 0x52e22c98
error RestrictionWasNotPresent(address restriction);
// 0x9a67c1cb
error RevertedBatchNotAfterNewLastBatch();
// 0xfe0aa4f2
error RoleAccessDenied(address chainAddress, bytes32 role, address account);
// 0xd3b6535b
error SelectorsMustAllHaveSameFreezability();
// 0x02181a13
error SettlementLayersMustSettleOnL1();
// 0x856d5b77
error SharedBridgeNotSet();
// 0x7774d2f9
error SharedBridgeValueNotSet(SharedBridgeKey);
// 0xabdc734e
error SignatureNotValid(address signer);
// 0xa665a34d
error SignaturesLengthMismatch(uint256 expected, uint256 actual);
// 0x3b94fe24
error SignerNotAuthorized(address signer);
// 0xa7781cbb
error SignersNotSorted();
// 0xdf3a8fdd
error SlotOccupied();
// 0xcc0f168b
error SystemContractProxyInitialized();
// 0xae43b424
error SystemLogsSizeTooBig();
// 0x08753982
error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp);
// 0x7a4902ad
error TimerAlreadyStarted();
// 0xf511412f
error TimerNotStarted();
// 0x2d50c33b
error TimestampError();
// 0xa51fa558
error TokenIsLegacy();
// 0xb1e96bbd
error TokenMultiplierChangeTooFrequent(uint256 nextAllowedTimestamp);
// 0x1850b46b
error TokenNotLegacy();
// 0x06439c6b
error TokenNotSupported(address token);
// 0x23830e28
error TokensWithFeesNotSupported();
// 0x8e3ce3cb
error TooHighDeploymentNonce();
// 0x76da24b9
error TooManyFactoryDeps();
// 0xf0b4e88f
error TooMuchGas();
// 0x00c5a6a9
error TransactionNotAllowed();
// 0x4c991078
error TxHashMismatch();
// 0x2e311df8
error TxnBodyGasLimitNotEnoughGas();
// 0xfcb9b2e1
error UnallowedImplementation(bytes32 implementationHash);
// 0x8e4a23d6
error Unauthorized(address caller);
// 0xe52478c7
error UndefinedDiamondCutAction();
// 0x6aa39880
error UnexpectedSystemLog(uint256 logKey);
// 0x8124d8ff
error UnexpectedUpgradeSelector();
// 0xc352bb73
error UnknownVerifierType();
// 0xf3dd1b9c
error UnsupportedCommitBatchEncoding(uint8 version);
// 0x084a1449
error UnsupportedEncodingVersion();
// 0x14d2ed8a
error UnsupportedExecuteBatchEncoding(uint8 version);
// 0xf338f830
error UnsupportedProofBatchEncoding(uint8 version);
// 0x1906f346
error UnsupportedUpgradeType();
// 0xf093c2e5
error UpgradeBatchNumberIsNotZero();
// 0x04d91f9d
error UpgradeTimestampNotReached(uint256 upgradeTimestamp, uint256 currentTimestamp);
// 0x47b3b145
error ValidateTxnNotEnoughGas();
// 0x626ade30
error ValueMismatch(uint256 expected, uint256 actual);
// 0xe1022469
error VerifiedBatchesExceedsCommittedBatches();
// 0xae899454
error WithdrawalAlreadyFinalized();
// 0x750b219c
error WithdrawFailed();
// 0xf20c5c2a
error WrappedBaseTokenAlreadyRegistered();
// 0xf1ff6cf6
error WrongCTMDeployerVariant();
// 0x15e8e429
error WrongMagicValue(uint256 expectedMagicValue, uint256 providedMagicValue);
// 0xd92e233d
error ZeroAddress();
// 0xc84885d4
error ZeroChainId();
// 0x16787758
error ZeroUpgradeTimestamp();
// 0x601b6882
error ZKChainLimitReached();
// 0x646ac57e
error ZKsyncOSNotForceDeployForExistingContract(address);
// 0xb24b1ccb
error ZKsyncOSNotForceDeployToPrecompileAddress(address);
// 0x3d9d4821
error ZKsyncOSPrecommitsNotSupported();
enum SharedBridgeKey {
PostUpgradeFirstBatch,
LegacyBridgeFirstBatch,
LegacyBridgeLastDepositBatch,
LegacyBridgeLastDepositTxn
}
enum BytecodeError {
Version,
NumberOfWords,
Length,
WordsMustBeOdd
}
enum UpgradeTxVerifyParam {
From,
To,
Paymaster,
Value,
MaxFeePerGas,
MaxPriorityFeePerGas,
Reserved0,
Reserved1,
Reserved2,
Reserved3,
Signature,
PaymasterInput,
ReservedDynamic
}
contracts/common/Messaging.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
bytes1 constant BUNDLE_IDENTIFIER = 0x01;
bytes1 constant INTEROP_BUNDLE_VERSION = 0x01;
bytes1 constant INTEROP_CALL_VERSION = 0x01;
/// @dev The enum that represents the transaction execution status
/// @param Failure The transaction execution failed
/// @param Success The transaction execution succeeded
enum TxStatus {
Failure,
Success
}
/// @dev The log passed from L2
/// @param l2ShardId The shard identifier, 0 - rollup, 1 - porter
/// All other values are not used but are reserved for the future
/// @param isService A boolean flag that is part of the log along with `key`, `value`, and `sender` address.
/// This field is required formally but does not have any special meaning
/// @param txNumberInBatch The L2 transaction number in a Batch, in which the log was sent
/// @param sender The L2 address which sent the log
/// @param key The 32 bytes of information that was sent in the log
/// @param value The 32 bytes of information that was sent in the log
// Both `key` and `value` are arbitrary 32-bytes selected by the log sender
struct L2Log {
uint8 l2ShardId;
bool isService;
uint16 txNumberInBatch;
address sender;
bytes32 key;
bytes32 value;
}
/// @dev An arbitrary length message passed from L2
/// @notice Under the hood it is `L2Log` sent from the special system L2 contract
/// @param txNumberInBatch The L2 transaction number in a Batch, in which the message was sent
/// @param sender The address of the L2 account from which the message was passed
/// @param data An arbitrary length message
struct L2Message {
uint16 txNumberInBatch;
address sender;
bytes data;
}
/// @dev Internal structure that contains the parameters for the writePriorityOp internal function.
/// @param txId The id of the priority transaction.
/// @param l2GasPrice The gas price for the l2 priority operation.
/// @param request The external calldata request for the priority operation.
struct WritePriorityOpParams {
uint256 txId;
uint256 l2GasPrice;
BridgehubL2TransactionRequest request;
}
/// @dev Structure that includes all fields of the L2 transaction
/// @dev The hash of this structure is the "canonical L2 transaction hash" and can
/// be used as a unique identifier of a tx
/// @param txType The tx type number, depending on which the L2 transaction can be
/// interpreted differently
/// @param from The sender's address. `uint256` type for possible address format changes
/// and maintaining backward compatibility
/// @param to The recipient's address. `uint256` type for possible address format changes
/// and maintaining backward compatibility
/// @param gasLimit The L2 gas limit for L2 transaction. Analog to the `gasLimit` on an
/// L1 transactions
/// @param gasPerPubdataByteLimit Maximum number of L2 gas that will cost one byte of pubdata
/// (every piece of data that will be stored on L1 as calldata)
/// @param maxFeePerGas The absolute maximum sender willing to pay per unit of L2 gas to get
/// the transaction included in a Batch. Analog to the EIP-1559 `maxFeePerGas` on an L1 transactions
/// @param maxPriorityFeePerGas The additional fee that is paid directly to the validator
/// to incentivize them to include the transaction in a Batch. Analog to the EIP-1559
/// `maxPriorityFeePerGas` on an L1 transactions
/// @param paymaster The address of the EIP-4337 paymaster, that will pay fees for the
/// transaction. `uint256` type for possible address format changes and maintaining backward compatibility
/// @param nonce The nonce of the transaction. For L1->L2 transactions it is the priority
/// operation Id
/// @param value The value to pass with the transaction
/// @param reserved The fixed-length fields for usage in a future extension of transaction
/// formats
/// @param data The calldata that is transmitted for the transaction call
/// @param signature An abstract set of bytes that are used for transaction authorization
/// @param factoryDeps The set of L2 bytecode hashes whose preimages were shown on L1
/// @param paymasterInput The arbitrary-length data that is used as a calldata to the paymaster pre-call
/// @param reservedDynamic The arbitrary-length field for usage in a future extension of transaction formats
struct L2CanonicalTransaction {
uint256 txType;
uint256 from;
uint256 to;
uint256 gasLimit;
uint256 gasPerPubdataByteLimit;
uint256 maxFeePerGas;
uint256 maxPriorityFeePerGas;
uint256 paymaster;
uint256 nonce;
uint256 value;
// In the future, we might want to add some
// new fields to the struct. The `txData` struct
// is to be passed to account and any changes to its structure
// would mean a breaking change to these accounts. To prevent this,
// we should keep some fields as "reserved"
// It is also recommended that their length is fixed, since
// it would allow easier proof integration (in case we will need
// some special circuit for preprocessing transactions)
uint256[4] reserved;
bytes data;
bytes signature;
uint256[] factoryDeps;
bytes paymasterInput;
// Reserved dynamic type for the future use-case. Using it should be avoided,
// But it is still here, just in case we want to enable some additional functionality
bytes reservedDynamic;
}
/// @param sender The sender's address.
/// @param contractL2 The address of the contract on L2 to call.
/// @param mintValue The amount of base token that should be minted on L2 as the result of this transaction.
/// @param l2Value The msg.value of the L2 transaction.
/// @param l2Calldata The calldata for the L2 transaction.
/// @param l2GasLimit The limit of the L2 gas for the L2 transaction
/// @param l2GasPerPubdataByteLimit The price for a single pubdata byte in L2 gas.
/// @param factoryDeps The array of L2 bytecodes that the tx depends on.
/// @param refundRecipient The recipient of the refund for the transaction on L2. If the transaction fails, then
/// this address will receive the `l2Value`.
// solhint-disable-next-line gas-struct-packing
struct BridgehubL2TransactionRequest {
address sender;
address contractL2;
uint256 mintValue;
uint256 l2Value;
bytes l2Calldata;
uint256 l2GasLimit;
uint256 l2GasPerPubdataByteLimit;
bytes[] factoryDeps;
address refundRecipient;
}
/// @dev The structure that contains the parameters for the message root
/// @param chainId The chain id of the dependency chain
/// @param blockOrBatchNumber The block number or the batch number where the message root was created
/// For proof based interop it is block number. For commit based interop it is batch number.
/// @param sides The sides of the dynamic incremental merkle tree emitted in the L2ToL1Messenger for precommit based interop
/// For proof and commit based interop, the sides contain a single root.
struct InteropRoot {
uint256 chainId;
uint256 blockOrBatchNumber;
// We are double overloading this. The sides of the dynamic incremental merkle tree normally contains the root, as well as the sides of the tree.
// Second overloading: if the length is 1, we are importing a chainBatchRoot/messageRoot instead of sides.
bytes32[] sides;
}
/// @param chainId The chain ID of the transaction to check.
/// @param l2BatchNumber The L2 batch number where the withdrawal was processed.
/// @param l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
/// @param l2Sender The address of the message sender on L2 (base token system contract address or asset handler)
/// @param l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent.
/// @param message The L2 withdraw data, stored in an L2 -> L1 message.
/// @param merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization.
struct FinalizeL1DepositParams {
uint256 chainId;
uint256 l2BatchNumber;
uint256 l2MessageIndex;
address l2Sender;
uint16 l2TxNumberInBatch;
bytes message;
bytes32[] merkleProof;
}
/// @dev Struct used to define parameters for adding a single call in an interop bundle.
/// @param to ERC-7930 address to call on the destination chain. Note, that it will have empty ChainReference.
/// This is due to the fact that chain ID is always provided on a bundle level, as a destination chain ID.
/// And in case of sendMessage the chain ID is also provided via the sendMessage interface, so it's redundant to store it here.
/// @param data Calldata payload to send to `to` address on the destination chain.
/// @param callAttributes EIP-7786 Attributes.
struct InteropCallStarter {
bytes to;
bytes data;
bytes[] callAttributes;
}
/// @dev Internal representation of an InteropCallStarter after parsing its parameters.
/// @param to Address to call on the destination chain.
/// @param data Calldata payload to send.
/// @param callAttributes EIP-7786 Attributes.
struct InteropCallStarterInternal {
address to;
bytes data;
CallAttributes callAttributes;
}
/// @param interopCallValue Base token value on destination chain to send for interop call.
/// @param indirectCall An indirect call first calls a contract as specified by the call starter which returns an actual call starter that will be used to form an interop call. In particular, this is used for interop token transfers. In contrast, a direct call uses the call starter to form an interop call.
/// @param indirectCallMessageValue Base token value on sending chain to send for indirect call.
struct CallAttributes {
uint256 interopCallValue;
bool indirectCall;
uint256 indirectCallMessageValue;
}
/// @param executionAddress ERC-7930 Address allowed to execute the bundle on the destination chain. If the byte array is empty then execution is permissionless.
/// @param unbundlerAddress ERC-7930 Address allowed to unbundle the bundle on the destination chain. Note, that it is required to be nonempty, unlike `executionAddress`.
/// @param useFixedFee If true, user pays fixed ZK fees instead of base token fees controlled by chain operator.
/// This is a bundle-level attribute - all calls within a bundle share the same fee mode.
/// Users are free to choose which fee mode to use when creating their bundle.
/// In more details, any user of interop functionality is able to choose between two fee options:
/// - Fixed fee in ZK (ZK_INTEROP_FEE constant in InteropCenter). User pays this fee directly in ZK tokens via ERC20 transfer.
/// - Dynamic fee in base token of source chain where the interop is initiated. This value is fully under control of chain operator via interopProtocolFee in InteropCenter.
/// In any case, gateway settlement fees (gatewaySettlementFee per call, set by governance in GWAssetTracker) are charged from the settlementFeePayer address
/// (encoded within the batch data of executeBatchesSharedBridge) when the chain settles on Gateway via processLogsAndMessages(). The settlementFeePayer must have pre-approved
/// GWAssetTracker to spend wrapped ZK tokens.
/// Note on ZK-as-base-token chains: On chains where ZK is the base token, useFixedFee=true still requires wrapped ZK tokens
/// (paid via ERC20 transfer), while useFixedFee=false accepts native ZK via msg.value. This is intentional behavior.
/// IMPORTANT: useFixedFee=true requires ZK token to be bridged to the source chain. If ZK token is not yet available
/// in the chain's NativeTokenVault, the transaction will revert with ZKTokenNotAvailable().
struct BundleAttributes {
bytes executionAddress;
bytes unbundlerAddress;
bool useFixedFee;
}
/// @dev A single call.
/// @param version Version of the InteropCall.
/// @param shadowAccount If true, execute via a shadow account, otherwise normal. In current release always false, as it's not yet implemented.
/// Shadow accounts help with interop when `to` doesn't support 7786. In this case, a "shadow" account could be deployed, allowing
/// the user to hold funds securely on the destination chain, and interact with anything on destination chain using this shadow account.
/// @param to Destination contract address on the target chain.
/// @param from Original sender address that initiated the call.
/// @param value Amount of base token to send with the call.
/// @param data Calldata payload for the call.
struct InteropCall {
bytes1 version;
bool shadowAccount;
address to;
address from;
uint256 value;
bytes data;
}
/// @dev Execution status of an individual call within a bundle.
/// @param Unprocessed Call not yet processed.
/// @param Executed Call was successfully executed.
/// @param Cancelled Call was cancelled during unbundling.
enum CallStatus {
Unprocessed,
Executed,
Cancelled
}
/// @dev A set of `InteropCall`s to send to another chain.
/// @param version Version of the InteropBundle.
/// @param destinationChainId ChainId of the target chain.
/// @param destinationBaseTokenAssetId Asset ID of the base token of the target chain.
/// @param interopBundleSalt Salt of the interopBundle. It's required to ensure that all bundles have distinct hashes.
/// It's equal to the keccak256(abi.encodePacked(senderOfTheBundle, NumberOfBundleSentByTheSender))
/// @param calls Array of InteropCall structs to execute.
/// @param bundleAttributes Bundle execution and unbundling attributes.
struct InteropBundle {
bytes1 version;
uint256 sourceChainId;
uint256 destinationChainId;
bytes32 destinationBaseTokenAssetId;
bytes32 interopBundleSalt;
InteropCall[] calls;
BundleAttributes bundleAttributes;
}
/// @dev Processing status of an `InteropBundle`.
/// @param Unreceived Bundle is not processed in any way yet.
/// @param Verified Bundle inclusion proof accepted, but not processed.
/// @param FullyExecuted All calls in the bundle have been executed atomically via executeBundle.
/// @param Unbundled Bundle was processed via unbundling flow.
enum BundleStatus {
Unreceived,
Verified,
FullyExecuted,
Unbundled
}
/// @dev Message sent by InteropHandler to GWAssetTracker for each successfully executed interop call.
/// @dev Allows GWAssetTracker to move the corresponding balance from pendingInteropBalance to chainBalance.
/// @param destinationBaseTokenAssetId Asset ID of the base token of the destination chain.
/// @param interopCall The interop call that was executed.
struct InteropCallExecutedMessage {
bytes32 destinationBaseTokenAssetId;
InteropCall interopCall;
}
/// @dev Inclusion proof for a cross-chain message payload (bundle) coming from L2→L1.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2MessageIndex Position in the L2 logs Merkle tree of this message.
/// @param message The raw L2 message payload (including `BUNDLE_IDENTIFIER` prefix).
/// @param proof Merkle‐proof for verifying the message inclusion.
struct MessageInclusionProof {
uint256 chainId;
uint256 l1BatchNumber;
uint256 l2MessageIndex;
L2Message message;
bytes32[] proof;
}
/// @dev Inclusion proof for a single L2 log entry passed to L1.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2LogIndex Position in the L2 logs Merkle tree of this log.
/// @param log The decoded `L2Log` entry.
/// @param proof Merkle‐proof for verifying the log inclusion.
struct LogInclusionProof {
uint256 chainId;
uint256 l1BatchNumber;
uint256 l2LogIndex;
L2Log log;
bytes32[] proof;
}
/// @dev Generic inclusion proof for an arbitrary 32‐byte leaf in the L2→L1 Merkle tree.
/// @param chainId Source chain identifier.
/// @param l1BatchNumber Batch number on L1 where the message root was committed.
/// @param l2LeafProofMask Bitmask indicating this leaf’s position, given as integer.
/// @param leaf The 32-byte leaf whose inclusion is being proven.
/// @param proof Merkle‐proof for verifying the leaf inclusion.
struct LeafInclusionProof {
uint256 chainId;
uint256 l1BatchNumber;
uint256 l2LeafProofMask;
bytes32 leaf;
bytes32[] proof;
}
struct ProofData {
uint256 settlementLayerChainId;
uint256 settlementLayerBatchNumber;
uint256 settlementLayerBatchRootMask;
uint256 batchLeafProofLen;
bytes32 batchSettlementRoot;
bytes32 chainIdLeaf;
uint256 ptr;
bool finalProofNode;
}
/// @dev L2 -> L1 message payload used when migrating token balance from L1 tracking to Gateway tracking.
/// @param version Encoding version.
/// @param originToken Token address on origin chain.
/// @param chainId Chain that is migrating.
/// @param assetId Asset id being migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param chainMigrationNumber Chain migration number this message is tied to.
/// @param assetMigrationNumber Asset migration number currently known on L2. Not yet used, kept for future use.
/// @param totalWithdrawalsToL1 Total withdrawals initiated from L2 to L1 since v31 tracking started.
/// @param totalSuccessfulDepositsFromL1 Total successful deposits finalized on L2 since v31 tracking started.
/// @param totalPreV31TotalSupply Token total supply snapshot captured on L2 before first post-v31 bridge operation.
struct L1ToGatewayTokenBalanceMigrationData {
bytes1 version;
address originToken;
uint256 chainId;
bytes32 assetId;
uint256 tokenOriginChainId;
uint256 chainMigrationNumber;
uint256 assetMigrationNumber;
uint256 totalWithdrawalsToL1;
uint256 totalSuccessfulDepositsFromL1;
uint256 totalPreV31TotalSupply;
}
/// @dev L2 -> L1 message payload used when migrating token balance from Gateway tracking back to L1 tracking.
/// @param version Encoding version.
/// @param originToken Token address on origin chain.
/// @param chainId Chain that is migrating.
/// @param assetId Asset id being migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param amount Chain balance amount to migrate from Gateway to L1.
/// @param chainMigrationNumber Chain migration number this message is tied to.
/// @param assetMigrationNumber Asset migration number currently known on Gateway.
struct GatewayToL1TokenBalanceMigrationData {
bytes1 version;
address originToken;
uint256 chainId;
bytes32 assetId;
uint256 tokenOriginChainId;
uint256 amount;
uint256 chainMigrationNumber;
uint256 assetMigrationNumber;
}
/// @dev L1 -> L2 service transaction payload used to confirm migration processing.
/// @param chainId Chain that was migrated.
/// @param assetId Asset id that was migrated.
/// @param tokenOriginChainId Origin chain for the token.
/// @param originToken Token address on origin chain.
/// @param amount Amount moved during the migration finalization on L1.
/// @param assetMigrationNumber New migration number that should be persisted on L2/Gateway.
/// @param isL1ToGateway Whether this confirmation corresponds to L1 -> Gateway direction.
// solhint-disable-next-line gas-struct-packing
struct MigrationConfirmationData {
uint256 chainId;
bytes32 assetId;
uint256 tokenOriginChainId;
address originToken;
uint256 amount;
uint256 assetMigrationNumber;
bool isL1ToGateway;
}
struct BalanceChange {
bytes1 version;
address originToken;
bytes32 baseTokenAssetId;
uint256 baseTokenAmount;
bytes32 assetId;
uint256 amount;
uint256 tokenOriginChainId;
}
struct AssetBalanceChange {
bytes32 assetId;
uint256 amount;
}
struct InteropBalanceChange {
bytes1 version;
uint256 baseTokenAmount;
AssetBalanceChange[] assetBalanceChanges;
}
/// @param _chainId The ZK chain id to which deposit was initiated.
/// @param _depositSender The address of the entity that initiated the deposit.
/// @param _assetId The unique identifier of the deposited L1 token.
/// @param _assetData The encoded data, which is used by the asset handler to determine L2 recipient and amount. Might include extra information.
/// @param _l2TxHash The L2 transaction hash.
/// @param _l2BatchNumber The L2 batch number where the deposit finalization was processed.
/// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message.
/// @param _l2TxNumberInBatch The L2 transaction number in a batch, in which the log was sent.
/// @param _merkleProof The Merkle proof of the processing L1 -> L2 transaction with deposit finalization.
/// @param _txStatus The status of the transaction.
struct ConfirmTransferResultData {
uint256 _chainId;
address _depositSender;
uint16 _l2TxNumberInBatch;
TxStatus _txStatus;
bytes32 _assetId;
bytes _assetData;
bytes32 _l2TxHash;
uint256 _l2BatchNumber;
uint256 _l2MessageIndex;
bytes32[] _merkleProof;
}
struct TokenMetadata {
string name;
string symbol;
uint256 decimals;
}
struct TokenBridgingData {
bytes32 assetId;
uint256 originChainId;
/// The address of the base token on the origin chain.
address originToken;
}
contracts/common/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
import {NotInitializedReentrancyGuard, Reentrancy, SlotOccupied} from "./L1ContractErrors.sol";
/**
* @custom:security-contact [email protected]
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
abstract contract ReentrancyGuard {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
// keccak256("ReentrancyGuard") - 1;
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4;
// solhint-disable-next-line max-line-length
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
modifier reentrancyGuardInitializer() {
_initializeReentrancyGuard();
_;
}
function _initializeReentrancyGuard() private {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
if (lockSlotOldValue != 0) {
revert SlotOccupied();
}
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
if (_status == 0) {
revert NotInitializedReentrancyGuard();
}
// On the first call to nonReentrant, _NOT_ENTERED will be true
if (_status != _NOT_ENTERED) {
revert Reentrancy();
}
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
contracts/state-transition/chain-interfaces/ICommitter.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
import {IZKChainBase} from "./IZKChainBase.sol";
import {L2DACommitmentScheme} from "../../common/Config.sol";
/// @notice Data needed to commit new batch
/// @param batchNumber Number of the committed batch
/// @param timestamp Unix timestamp denoting the start of the batch execution
/// @param indexRepeatedStorageChanges The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more
/// @param newStateRoot The state root of the full state tree
/// @param numberOfLayer1Txs Number of priority operations to be processed
/// @param priorityOperationsHash Hash of all priority operations from this batch
/// @param bootloaderHeapInitialContentsHash Hash of the initial contents of the bootloader heap. In practice it serves as the commitment to the transactions in the batch.
/// @param eventsQueueStateHash Hash of the events queue state. In practice it serves as the commitment to the events in the batch.
/// @param systemLogs concatenation of all L2 -> L1 system logs in the batch
/// @param operatorDAInput Packed pubdata commitments/data.
/// @dev 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
/// @dev For 2 blobs we will be sending 288 bytes of calldata instead of the full amount for pubdata.
/// @dev 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;
}
/// @notice Commit batch info for ZKsync OS
/// @param batchNumber Number of the committed batch
/// @param newStateCommitment State commitment of the new state.
/// @dev chain state commitment, this preimage is not opened on l1,
/// it's guaranteed that this commitment commits to any state that needed for execution
/// (state root, block number, block hashes)
/// @param numberOfLayer1Txs Number of priority operations to be processed
/// @param numberOfLayer2Txs Number of L2 transactions executed in the batch
/// @param priorityOperationsHash Hash of all priority operations from this batch
/// @param l2LogsTreeRoot Root hash of tree that contains L2 -> L1 messages from this batch
/// @param daCommitmentScheme commitment scheme used to generate pubdata commitment for this batch
/// @param daCommitment commitment to the batch pubdata to validate DA in the l1 da validator
// solhint-disable-next-line gas-struct-packing
struct CommitBatchInfoZKsyncOS {
uint64 batchNumber;
bytes32 newStateCommitment;
uint256 numberOfLayer1Txs;
uint256 numberOfLayer2Txs;
bytes32 priorityOperationsHash;
bytes32 dependencyRootsRollingHash;
bytes32 l2LogsTreeRoot;
L2DACommitmentScheme daCommitmentScheme;
bytes32 daCommitment;
uint64 firstBlockTimestamp;
uint64 firstBlockNumber;
uint64 lastBlockTimestamp;
uint64 lastBlockNumber;
uint256 chainId;
bytes operatorDAInput;
uint256 slChainId;
}
/// @notice Container for a list of transaction statuses to precommit.
/// @param txs A packed array of individual transaction status commitments for the batch. Each is expected to be
/// of length 33 and have the following format: <32-byte tx hash, 1-byte status>. where status is either 0 (failed) or 1 (success).
/// @param untrustedLastL2BlockNumberHint The "hint" for what the last L2 block number that these txs represent is.
struct PrecommitInfo {
bytes packedTxsCommitments;
uint256 untrustedLastL2BlockNumberHint;
}
/// @title The interface of the ZKsync Committer contract responsible for batch commitment operations.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface ICommitter is IZKChainBase {
/// @notice Precommits the status of all L2 transactions for the next batch on the shared bridge.
/// @param _chainAddress 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.
/// @param _batchNumber The sequential batch number to precommit (must equal `s.totalBatchesCommitted + 1`).
/// @param _precommitData ABI‐encoded transaction status list for the precommit.
function precommitSharedBridge(address _chainAddress, uint256 _batchNumber, bytes calldata _precommitData) external;
/// @notice 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.
/// @param _chainAddress 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.
/// @param _processFrom The batch number from which the processing starts.
/// @param _processTo The batch number at which the processing ends.
/// @param _commitData The encoded data of the new batches to be committed.
function commitBatchesSharedBridge(
address _chainAddress,
uint256 _processFrom,
uint256 _processTo,
bytes calldata _commitData
) external;
/// @notice Event emitted when a batch is committed
/// @param batchNumber Number of the batch committed
/// @param batchHash Hash of the L2 batch
/// @param commitment Calculated input for the ZKsync circuit
/// @dev It has the name "BlockCommit" and not "BatchCommit" due to backward compatibility considerations
event BlockCommit(uint256 indexed batchNumber, bytes32 indexed batchHash, bytes32 indexed commitment);
/// @notice Emitted when a new precommitment is set for a batch.
/// @param batchNumber The batch number for which the precommitment was recorded.
/// @param untrustedLastL2BlockNumberHint 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.
/// @param precommitment The resulting rolling hash of all transaction statuses.
event BatchPrecommitmentSet(
uint256 indexed batchNumber,
uint256 indexed untrustedLastL2BlockNumberHint,
bytes32 precommitment
);
/// @notice Reports the block range for a zksync os batch.
/// @dev IMPORTANT: in this release this range is not trusted and provided by the operator while not being included to the proof.
event ReportCommittedBatchRangeZKsyncOS(
uint64 indexed batchNumber,
uint64 indexed firstBlockNumber,
uint64 indexed lastBlockNumber
);
}
contracts/state-transition/chain-interfaces/IExecutor.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
import {IZKChainBase} from "./IZKChainBase.sol";
import {L2Log} from "../../common/Messaging.sol";
// solhint-disable-next-line no-unused-import
import {MAX_NUMBER_OF_BLOBS, SystemLogKey} from "system-contracts/contracts/Constants.sol";
struct LogProcessingOutput {
uint256 numberOfLayer1Txs;
uint256 numberOfLayer2Txs;
bytes32 chainedPriorityTxsHash;
bytes32 previousBatchHash;
bytes32 pubdataHash;
bytes32 stateDiffHash;
bytes32 l2LogsTreeRoot;
uint256 packedBatchAndL2BlockTimestamp;
bytes32 l2DAValidatorOutputHash;
bytes32 l2TxsStatusRollingHash;
bytes32 dependencyRootsRollingHash;
}
/// @dev Maximal value that SystemLogKey variable can have.
uint256 constant MAX_LOG_KEY = uint256(type(SystemLogKey).max);
/// @notice The struct passed to the assetTracker for processing L2 logs and collecting settlement fees.
/// @param logs The L2 logs from the batch.
/// @param messages The L2 messages corresponding to the logs. Note: there can be fewer messages than logs,
/// as not all logs have corresponding messages.
/// @param chainId The chain ID of the settling chain.
/// @param batchNumber The batch number being processed.
/// @param chainBatchRoot The batch root hash for verification.
/// @param multichainBatchRoot The multichain batch root for chain for verification.
/// @param settlementFeePayer Address that pays gateway settlement fees for interop calls in this batch.
///
/// @dev Settlement Fee Payer Requirements:
/// 1. Must have called `setSettlementFeePayerAgreement(chainId, true)` on GWAssetTracker to opt-in for this specific chain
/// 2. Must have sufficient wrapped ZK token balance to cover: gatewaySettlementFee * chargeableInteropCount
/// 3. Must have approved GWAssetTracker to spend wrapped ZK tokens
/// The opt-in mechanism prevents front-running attacks where a malicious operator could
/// make another address pay for their chain's settlements by specifying it as settlementFeePayer.
///
/// @dev Failure Behavior:
/// - If fee collection fails (payer not agreed, insufficient balance, or no approval), batch execution reverts
/// - This ensures fees are always paid atomically with settlement
/// - Operators must ensure their fee payer has agreed and maintains sufficient balance/approval
struct ProcessLogsInput {
L2Log[] logs;
bytes[] messages;
uint256 chainId;
uint256 batchNumber;
bytes32 chainBatchRoot;
bytes32 multichainBatchRoot;
address settlementFeePayer;
}
/// @dev Offset used to pull Address From Log. Equal to 4 (bytes for shardId, isService and txNumberInBatch)
uint256 constant L2_LOG_ADDRESS_OFFSET = 4;
/// @dev 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;
/// @dev 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;
/// @dev 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;
/// @title The interface of the ZKsync Executor contract capable of processing events emitted in the ZKsync protocol.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IExecutor is IZKChainBase {
/// @notice Rollup batch stored data, this structure used for both: Era VM and ZKsync OS batches, however some fields have different meaning
/// @param batchNumber Rollup batch number
/// @param batchHash Hash of L2 batch, for ZKsync OS batches we'll store here full state commitment
/// @param indexRepeatedStorageChanges The serial number of the shortcut index that's used as a unique identifier for storage keys that were used twice or more. For ZKsync OS not used, always set to 0
/// @param numberOfLayer1Txs Number of priority operations to be processed
/// @param priorityOperationsHash Hash of all priority operations from this batch
/// @param l2LogsTreeRoot Root hash of tree that contains L2 -> L1 messages from this batch
/// @param timestamp Rollup batch timestamp, have the same format as Ethereum batch constant. For ZKsync OS not used, always set to 0
/// @param commitment Verified input for the ZKsync circuit. For ZKsync OS batches we'll store batch output hash here
// solhint-disable-next-line gas-struct-packing
struct StoredBatchInfo {
uint64 batchNumber;
bytes32 batchHash; // For ZKsync OS batches we'll store here full state commitment
uint64 indexRepeatedStorageChanges; // For ZKsync OS not used, always set to 0
uint256 numberOfLayer1Txs;
bytes32 priorityOperationsHash;
bytes32 dependencyRootsRollingHash;
bytes32 l2LogsTreeRoot;
uint256 timestamp; // For ZKsync OS not used, always set to 0
bytes32 commitment; // For ZKsync OS batches we'll store batch output hash here
}
/// @notice Legacy StoredBatchInfo struct
/// @dev dependencyRootsRollingHash is not included in the struct
// solhint-disable-next-line gas-struct-packing
struct LegacyStoredBatchInfo {
uint64 batchNumber;
bytes32 batchHash;
uint64 indexRepeatedStorageChanges;
uint256 numberOfLayer1Txs;
bytes32 priorityOperationsHash;
bytes32 l2LogsTreeRoot;
uint256 timestamp;
bytes32 commitment;
}
/// @notice Batches commitment verification.
/// @dev Only verifies batch commitments without any other processing.
/// @param _chainAddress 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.
/// @param _processBatchFrom The batch number from which the verification starts.
/// @param _processBatchTo The batch number at which the verification ends.
/// @param _proofData The encoded data of the new batches to be verified.
function proveBatchesSharedBridge(
address _chainAddress,
uint256 _processBatchFrom,
uint256 _processBatchTo,
bytes calldata _proofData
) external;
/// @notice 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)
/// @param _chainAddress 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.
/// @param _processFrom The batch number from which the execution starts.
/// @param _processTo The batch number at which the execution ends.
/// @param _executeData The encoded data of the new batches to be executed. Contains settlement fee payer address.
function executeBatchesSharedBridge(
address _chainAddress,
uint256 _processFrom,
uint256 _processTo,
bytes calldata _executeData
) external;
/// @notice Reverts unexecuted batches
/// @param _chainAddress The address of the DiamondProxy of the chain.
/// @param _newLastBatch batch number after which batches should be reverted
/// @dev 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;
/// @notice Event emitted when batches are verified
/// @param previousLastVerifiedBatch Batch number of the previous last verified batch
/// @param currentLastVerifiedBatch Batch number of the current last verified batch
/// @dev It has the name "BlocksVerification" and not "BatchesVerification" due to backward compatibility considerations
event BlocksVerification(uint256 indexed previousLastVerifiedBatch, uint256 indexed currentLastVerifiedBatch);
/// @notice Event emitted when a batch is executed
/// @param batchNumber Number of the batch executed
/// @param batchHash Hash of the L2 batch
/// @param commitment Verified input for the ZKsync circuit
/// @dev It has the name "BlockExecution" and not "BatchExecution" due to backward compatibility considerations
event BlockExecution(uint256 indexed batchNumber, bytes32 indexed batchHash, bytes32 indexed commitment);
/// @notice Event emitted when batches are reverted
/// @param totalBatchesCommitted Total number of committed batches after the revert
/// @param totalBatchesVerified Total number of verified batches after the revert
/// @param totalBatchesExecuted Total number of executed batches
/// @dev It has the name "BlocksRevert" and not "BatchesRevert" due to backward compatibility considerations
event BlocksRevert(uint256 totalBatchesCommitted, uint256 totalBatchesVerified, uint256 totalBatchesExecuted);
}
contracts/state-transition/chain-interfaces/IZKChainBase.sol
// SPDX-License-Identifier: MIT
// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version.
pragma solidity ^0.8.21;
/// @title The interface of the ZKsync contract, responsible for the main ZKsync logic.
/// @author Matter Labs
/// @custom:security-contact [email protected]
interface IZKChainBase {
/// @return Returns facet name.
function getName() external view returns (string memory);
}
lib/openzeppelin-contracts-upgradeable-v4/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
lib/openzeppelin-contracts-upgradeable-v4/contracts/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Настройки компилятораПоказать
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 9999999,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"@ensdomains/=node_modules/@ensdomains/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"forge-std/=lib/forge-std/src/",
"hardhat/=node_modules/hardhat/",
"murky/=lib/murky/src/",
"foundry-test/=test/foundry/",
"l2-contracts/=../l2-contracts/contracts/",
"system-contracts/=../system-contracts/",
"@openzeppelin/contracts-v4/=lib/openzeppelin-contracts-v4/contracts/",
"@openzeppelin/contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/contracts/",
"test-utils/=test/foundry/l1/integration/utils/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable-v4/lib/erc4626-tests/",
"openzeppelin-contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/",
"openzeppelin-contracts-v4/=lib/openzeppelin-contracts-v4/",
"openzeppelin-contracts/=lib/murky/lib/openzeppelin-contracts/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.