Source Code
Overview
ETH Balance
0 ETH
More Info
ContractCreator
Multichain Info
N/A
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
Parent Transaction Hash | Method | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|---|
0x60a06040 | 7941049 | 34 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x23bA48a4...DdbAB33e3 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
ExecutorFacet
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ZKChainBase} from "./ZKChainBase.sol"; import {IBridgehub} from "../../../bridgehub/IBridgehub.sol"; import {IMessageRoot} from "../../../bridgehub/IMessageRoot.sol"; import {COMMIT_TIMESTAMP_NOT_OLDER, COMMIT_TIMESTAMP_APPROXIMATION_DELTA, EMPTY_STRING_KECCAK, L2_TO_L1_LOG_SERIALIZE_SIZE, MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES, PACKED_L2_BLOCK_TIMESTAMP_MASK, PUBLIC_INPUT_SHIFT} from "../../../common/Config.sol"; import {IExecutor, L2_LOG_ADDRESS_OFFSET, L2_LOG_KEY_OFFSET, L2_LOG_VALUE_OFFSET, SystemLogKey, LogProcessingOutput, TOTAL_BLOBS_IN_COMMITMENT} from "../../chain-interfaces/IExecutor.sol"; import {PriorityQueue, PriorityOperation} from "../../libraries/PriorityQueue.sol"; import {BatchDecoder} from "../../libraries/BatchDecoder.sol"; import {UncheckedMath} from "../../../common/libraries/UncheckedMath.sol"; import {UnsafeBytes} from "../../../common/libraries/UnsafeBytes.sol"; import {L2_BOOTLOADER_ADDRESS, L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR, L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR} from "../../../common/L2ContractAddresses.sol"; import {IChainTypeManager} from "../../IChainTypeManager.sol"; import {PriorityTree, PriorityOpsBatchInfo} from "../../libraries/PriorityTree.sol"; import {IL1DAValidator, L1DAValidatorOutput} from "../../chain-interfaces/IL1DAValidator.sol"; import {InvalidSystemLogsLength, MissingSystemLogs, BatchNumberMismatch, TimeNotReached, ValueMismatch, HashMismatch, NonIncreasingTimestamp, TimestampError, InvalidLogSender, TxHashMismatch, UnexpectedSystemLog, LogAlreadyProcessed, InvalidProtocolVersion, CanOnlyProcessOneBatch, BatchHashMismatch, UpgradeBatchNumberIsNotZero, NonSequentialBatch, CantExecuteUnprovenBatches, SystemLogsSizeTooBig, InvalidNumberOfBlobs, VerifiedBatchesExceedsCommittedBatches, InvalidProof, RevertedBatchNotAfterNewLastBatch, CantRevertExecutedBatch, L2TimestampTooBig, PriorityOperationsRollingHashMismatch} from "../../../common/L1ContractErrors.sol"; import {InvalidBatchesDataLength, MismatchL2DAValidator, MismatchNumberOfLayer1Txs, PriorityOpsDataLeftPathLengthIsNotZero, PriorityOpsDataRightPathLengthIsNotZero, PriorityOpsDataItemHashesLengthIsNotZero} from "../../L1StateTransitionErrors.sol"; // While formally the following import is not used, it is needed to inherit documentation from it import {IZKChainBase} from "../../chain-interfaces/IZKChainBase.sol"; /// @dev The version that is used for the `Executor` calldata used for relaying the /// stored batch info. uint8 constant RELAYED_EXECUTOR_VERSION = 0; /// @title ZK chain Executor contract capable of processing events emitted in the ZK chain protocol. /// @author Matter Labs /// @custom:security-contact [email protected] contract ExecutorFacet is ZKChainBase, IExecutor { using UncheckedMath for uint256; using PriorityQueue for PriorityQueue.Queue; using PriorityTree for PriorityTree.Tree; /// @inheritdoc IZKChainBase string public constant override getName = "ExecutorFacet"; /// @notice The chain id of L1. This contract can be deployed on multiple layers, but this value is still equal to the /// L1 that is at the most base layer. uint256 internal immutable L1_CHAIN_ID; constructor(uint256 _l1ChainId) { L1_CHAIN_ID = _l1ChainId; } /// @dev Process one batch commit using the previous batch StoredBatchInfo /// @dev returns new batch StoredBatchInfo /// @notice Does not change storage function _commitOneBatch( StoredBatchInfo memory _previousBatch, CommitBatchInfo memory _newBatch, bytes32 _expectedSystemContractUpgradeTxHash ) internal returns (StoredBatchInfo memory storedBatchInfo) { // only commit next batch if (_newBatch.batchNumber != _previousBatch.batchNumber + 1) { revert BatchNumberMismatch(_previousBatch.batchNumber + 1, _newBatch.batchNumber); } // Check that batch contains all meta information for L2 logs. // Get the chained hash of priority transaction hashes. LogProcessingOutput memory logOutput = _processL2Logs(_newBatch, _expectedSystemContractUpgradeTxHash); L1DAValidatorOutput memory daOutput = IL1DAValidator(s.l1DAValidator).checkDA({ _chainId: s.chainId, _batchNumber: uint256(_newBatch.batchNumber), _l2DAValidatorOutputHash: logOutput.l2DAValidatorOutputHash, _operatorDAInput: _newBatch.operatorDAInput, _maxBlobsSupported: TOTAL_BLOBS_IN_COMMITMENT }); if (_previousBatch.batchHash != logOutput.previousBatchHash) { revert HashMismatch(logOutput.previousBatchHash, _previousBatch.batchHash); } // Check that the priority operation hash in the L2 logs is as expected if (logOutput.chainedPriorityTxsHash != _newBatch.priorityOperationsHash) { revert HashMismatch(logOutput.chainedPriorityTxsHash, _newBatch.priorityOperationsHash); } // Check that the number of processed priority operations is as expected if (logOutput.numberOfLayer1Txs != _newBatch.numberOfLayer1Txs) { revert ValueMismatch(logOutput.numberOfLayer1Txs, _newBatch.numberOfLayer1Txs); } // Check the timestamp of the new batch _verifyBatchTimestamp(logOutput.packedBatchAndL2BlockTimestamp, _newBatch.timestamp, _previousBatch.timestamp); // Create batch commitment for the proof verification (bytes32 metadataHash, bytes32 auxiliaryOutputHash, bytes32 commitment) = _createBatchCommitment( _newBatch, daOutput.stateDiffHash, daOutput.blobsOpeningCommitments, daOutput.blobsLinearHashes ); storedBatchInfo = StoredBatchInfo({ batchNumber: _newBatch.batchNumber, batchHash: _newBatch.newStateRoot, indexRepeatedStorageChanges: _newBatch.indexRepeatedStorageChanges, numberOfLayer1Txs: _newBatch.numberOfLayer1Txs, priorityOperationsHash: _newBatch.priorityOperationsHash, l2LogsTreeRoot: logOutput.l2LogsTreeRoot, timestamp: _newBatch.timestamp, commitment: commitment }); if (L1_CHAIN_ID != block.chainid) { // If we are settling on top of Gateway, we always relay the data needed to construct // a proof for a new batch (and finalize it) even if the data for Gateway transactions has been fully lost. // This data includes: // - `StoredBatchInfo` that is needed to execute a block on top of the previous one. // But also, we need to ensure that the components of the commitment of the batch are available: // - passThroughDataHash (and its full preimage) // - metadataHash (only the hash) // - auxiliaryOutputHash (only the hash) // The source of the truth for the data from above can be found here: // https://github.com/matter-labs/zksync-protocol/blob/c80fa4ee94fd0f7f05f7aea364291abb8b4d7351/crates/zkevm_circuits/src/scheduler/mod.rs#L1356-L1369 // // The full preimage of `passThroughDataHash` consists of the state root as well as the `indexRepeatedStorageChanges`. All // these values are already included as part of the `storedBatchInfo`, so we do not need to republish those. // slither-disable-next-line unused-return L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR.sendToL1( abi.encode(RELAYED_EXECUTOR_VERSION, storedBatchInfo, metadataHash, auxiliaryOutputHash) ); } } /// @notice checks that the timestamps of both the new batch and the new L2 block are correct. /// @param _packedBatchAndL2BlockTimestamp - packed batch and L2 block timestamp in a format of batchTimestamp * 2**128 + l2BatchTimestamp /// @param _expectedBatchTimestamp - expected batch timestamp /// @param _previousBatchTimestamp - the timestamp of the previous batch function _verifyBatchTimestamp( uint256 _packedBatchAndL2BlockTimestamp, uint256 _expectedBatchTimestamp, uint256 _previousBatchTimestamp ) internal view { // Check that the timestamp that came from the system context is expected uint256 batchTimestamp = _packedBatchAndL2BlockTimestamp >> 128; if (batchTimestamp != _expectedBatchTimestamp) { revert TimestampError(); } // While the fact that _previousBatchTimestamp < batchTimestamp is already checked on L2, // we double check it here for clarity if (_previousBatchTimestamp >= batchTimestamp) { revert NonIncreasingTimestamp(); } uint256 lastL2BlockTimestamp = _packedBatchAndL2BlockTimestamp & PACKED_L2_BLOCK_TIMESTAMP_MASK; // All L2 blocks have timestamps within the range of [batchTimestamp, lastL2BlockTimestamp]. // So here we need to only double check that: // - The timestamp of the batch is not too small. // - The timestamp of the last L2 block is not too big. // New batch timestamp is too small if (block.timestamp - COMMIT_TIMESTAMP_NOT_OLDER > batchTimestamp) { revert TimeNotReached(batchTimestamp, block.timestamp - COMMIT_TIMESTAMP_NOT_OLDER); } // The last L2 block timestamp is too big if (lastL2BlockTimestamp > block.timestamp + COMMIT_TIMESTAMP_APPROXIMATION_DELTA) { revert L2TimestampTooBig(); } } /// @dev Check that L2 logs are proper and batch contain all meta information for them /// @dev The logs processed here should line up such that only one log for each key from the /// SystemLogKey enum in Constants.sol is processed per new batch. /// @dev Data returned from here will be used to form the batch commitment. function _processL2Logs( CommitBatchInfo memory _newBatch, bytes32 _expectedSystemContractUpgradeTxHash ) internal view returns (LogProcessingOutput memory logOutput) { // Copy L2 to L1 logs into memory. bytes memory emittedL2Logs = _newBatch.systemLogs; // Used as bitmap to set/check log processing happens exactly once. // See SystemLogKey enum in Constants.sol for ordering. uint256 processedLogs = 0; // linear traversal of the logs uint256 logsLength = emittedL2Logs.length; if (logsLength % L2_TO_L1_LOG_SERIALIZE_SIZE != 0) { revert InvalidSystemLogsLength(); } for (uint256 i = 0; i < logsLength; i = i.uncheckedAdd(L2_TO_L1_LOG_SERIALIZE_SIZE)) { // Extract the values to be compared to/used such as the log sender, key, and value // slither-disable-next-line unused-return (address logSender, ) = UnsafeBytes.readAddress(emittedL2Logs, i + L2_LOG_ADDRESS_OFFSET); // slither-disable-next-line unused-return (uint256 logKey, ) = UnsafeBytes.readUint256(emittedL2Logs, i + L2_LOG_KEY_OFFSET); // slither-disable-next-line unused-return (bytes32 logValue, ) = UnsafeBytes.readBytes32(emittedL2Logs, i + L2_LOG_VALUE_OFFSET); // Ensure that the log hasn't been processed already if (_checkBit(processedLogs, uint8(logKey))) { revert LogAlreadyProcessed(uint8(logKey)); } processedLogs = _setBit(processedLogs, uint8(logKey)); // Need to check that each log was sent by the correct address. if (logKey == uint256(SystemLogKey.L2_TO_L1_LOGS_TREE_ROOT_KEY)) { if (logSender != address(L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR)) { revert InvalidLogSender(logSender, logKey); } logOutput.l2LogsTreeRoot = logValue; } else if (logKey == uint256(SystemLogKey.PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY)) { if (logSender != L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR) { revert InvalidLogSender(logSender, logKey); } logOutput.packedBatchAndL2BlockTimestamp = uint256(logValue); } else if (logKey == uint256(SystemLogKey.PREV_BATCH_HASH_KEY)) { if (logSender != L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR) { revert InvalidLogSender(logSender, logKey); } logOutput.previousBatchHash = logValue; } else if (logKey == uint256(SystemLogKey.CHAINED_PRIORITY_TXN_HASH_KEY)) { if (logSender != L2_BOOTLOADER_ADDRESS) { revert InvalidLogSender(logSender, logKey); } logOutput.chainedPriorityTxsHash = logValue; } else if (logKey == uint256(SystemLogKey.NUMBER_OF_LAYER_1_TXS_KEY)) { if (logSender != L2_BOOTLOADER_ADDRESS) { revert InvalidLogSender(logSender, logKey); } logOutput.numberOfLayer1Txs = uint256(logValue); } else if (logKey == uint256(SystemLogKey.USED_L2_DA_VALIDATOR_ADDRESS_KEY)) { if (logSender != address(L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR)) { revert InvalidLogSender(logSender, logKey); } if (s.l2DAValidator != address(uint160(uint256(logValue)))) { revert MismatchL2DAValidator(); } } else if (logKey == uint256(SystemLogKey.L2_DA_VALIDATOR_OUTPUT_HASH_KEY)) { if (logSender != address(L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR)) { revert InvalidLogSender(logSender, logKey); } logOutput.l2DAValidatorOutputHash = logValue; } else if (logKey == uint256(SystemLogKey.EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY)) { if (logSender != L2_BOOTLOADER_ADDRESS) { revert InvalidLogSender(logSender, logKey); } if (_expectedSystemContractUpgradeTxHash != logValue) { revert TxHashMismatch(); } } else if (logKey > uint256(SystemLogKey.EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY)) { revert UnexpectedSystemLog(logKey); } } // We only require 7 logs to be checked, the 8th is if we are expecting a protocol upgrade // Without the protocol upgrade we expect 7 logs: 2^7 - 1 = 127 // With the protocol upgrade we expect 8 logs: 2^8 - 1 = 255 if (_expectedSystemContractUpgradeTxHash == bytes32(0)) { if (processedLogs != 127) { revert MissingSystemLogs(127, processedLogs); } } else if (processedLogs != 255) { revert MissingSystemLogs(255, processedLogs); } } /// @inheritdoc IExecutor function commitBatchesSharedBridge( uint256, // _chainId uint256 _processFrom, uint256 _processTo, bytes calldata _commitData ) external nonReentrant onlyValidator onlySettlementLayer { // check that we have the right protocol version // three comments: // 1. A chain has to keep their protocol version up to date, as processing a block requires the latest or previous protocol version // to solve this we will need to add the feature to create batches with only the protocol upgrade tx, without any other txs. // 2. A chain might become out of sync if it launches while we are in the middle of a protocol upgrade. This would mean they cannot process their genesis upgrade // as their protocolversion would be outdated, and they also cannot process the protocol upgrade tx as they have a pending upgrade. // 3. The protocol upgrade is increased in the BaseZkSyncUpgrade, in the executor only the systemContractsUpgradeTxHash is checked if (!IChainTypeManager(s.chainTypeManager).protocolVersionIsActive(s.protocolVersion)) { revert InvalidProtocolVersion(); } (StoredBatchInfo memory lastCommittedBatchData, CommitBatchInfo[] memory newBatchesData) = BatchDecoder .decodeAndCheckCommitData(_commitData, _processFrom, _processTo); // With the new changes for EIP-4844, namely the restriction on number of blobs per block, we only allow for a single batch to be committed at a time. // Note: Don't need to check that `_processFrom` == `_processTo` because there is only one batch, // and so the range checked in the `decodeAndCheckCommitData` is enough. if (newBatchesData.length != 1) { revert CanOnlyProcessOneBatch(); } // Check that we commit batches after last committed batch if (s.storedBatchHashes[s.totalBatchesCommitted] != _hashStoredBatchInfo(lastCommittedBatchData)) { // incorrect previous batch data revert BatchHashMismatch( s.storedBatchHashes[s.totalBatchesCommitted], _hashStoredBatchInfo(lastCommittedBatchData) ); } bytes32 systemContractsUpgradeTxHash = s.l2SystemContractsUpgradeTxHash; // Upgrades are rarely done so we optimize a case with no active system contracts upgrade. if (systemContractsUpgradeTxHash == bytes32(0) || s.l2SystemContractsUpgradeBatchNumber != 0) { _commitBatchesWithoutSystemContractsUpgrade(lastCommittedBatchData, newBatchesData); } else { _commitBatchesWithSystemContractsUpgrade( lastCommittedBatchData, newBatchesData, systemContractsUpgradeTxHash ); } s.totalBatchesCommitted = s.totalBatchesCommitted + newBatchesData.length; } /// @dev Commits new batches without any system contracts upgrade. /// @param _lastCommittedBatchData The data of the last committed batch. /// @param _newBatchesData An array of batch data that needs to be committed. function _commitBatchesWithoutSystemContractsUpgrade( StoredBatchInfo memory _lastCommittedBatchData, CommitBatchInfo[] memory _newBatchesData ) internal { // We disable this check because calldata array length is cheap. // solhint-disable-next-line gas-length-in-loops for (uint256 i = 0; i < _newBatchesData.length; i = i.uncheckedInc()) { _lastCommittedBatchData = _commitOneBatch(_lastCommittedBatchData, _newBatchesData[i], bytes32(0)); s.storedBatchHashes[_lastCommittedBatchData.batchNumber] = _hashStoredBatchInfo(_lastCommittedBatchData); emit BlockCommit( _lastCommittedBatchData.batchNumber, _lastCommittedBatchData.batchHash, _lastCommittedBatchData.commitment ); } } /// @dev Commits new batches with a system contracts upgrade transaction. /// @param _lastCommittedBatchData The data of the last committed batch. /// @param _newBatchesData An array of batch data that needs to be committed. /// @param _systemContractUpgradeTxHash The transaction hash of the system contract upgrade. function _commitBatchesWithSystemContractsUpgrade( StoredBatchInfo memory _lastCommittedBatchData, CommitBatchInfo[] memory _newBatchesData, bytes32 _systemContractUpgradeTxHash ) internal { // The system contract upgrade is designed to be executed atomically with the new bootloader, a default account, // ZKP verifier, and other system parameters. Hence, we ensure that the upgrade transaction is // carried out within the first batch committed after the upgrade. // While the logic of the contract ensures that the s.l2SystemContractsUpgradeBatchNumber is 0 when this function is called, // this check is added just in case. Since it is a hot read, it does not incur noticeable gas cost. if (s.l2SystemContractsUpgradeBatchNumber != 0) { revert UpgradeBatchNumberIsNotZero(); } // Save the batch number where the upgrade transaction was executed. s.l2SystemContractsUpgradeBatchNumber = _newBatchesData[0].batchNumber; // We disable this check because calldata array length is cheap. // solhint-disable-next-line gas-length-in-loops for (uint256 i = 0; i < _newBatchesData.length; i = i.uncheckedInc()) { // The upgrade transaction must only be included in the first batch. bytes32 expectedUpgradeTxHash = i == 0 ? _systemContractUpgradeTxHash : bytes32(0); _lastCommittedBatchData = _commitOneBatch( _lastCommittedBatchData, _newBatchesData[i], expectedUpgradeTxHash ); s.storedBatchHashes[_lastCommittedBatchData.batchNumber] = _hashStoredBatchInfo(_lastCommittedBatchData); emit BlockCommit( _lastCommittedBatchData.batchNumber, _lastCommittedBatchData.batchHash, _lastCommittedBatchData.commitment ); } } /// @dev Pops the priority operations from the priority queue and returns a rolling hash of operations function _collectOperationsFromPriorityQueue(uint256 _nPriorityOps) internal returns (bytes32 concatHash) { concatHash = EMPTY_STRING_KECCAK; for (uint256 i = 0; i < _nPriorityOps; i = i.uncheckedInc()) { PriorityOperation memory priorityOp = s.priorityQueue.popFront(); concatHash = keccak256(abi.encode(concatHash, priorityOp.canonicalTxHash)); } s.priorityTree.skipUntil(s.priorityQueue.getFirstUnprocessedPriorityTx()); } function _rollingHash(bytes32[] memory _hashes) internal pure returns (bytes32) { bytes32 hash = EMPTY_STRING_KECCAK; uint256 nHashes = _hashes.length; for (uint256 i = 0; i < nHashes; i = i.uncheckedInc()) { hash = keccak256(abi.encode(hash, _hashes[i])); } return hash; } /// @dev Checks that the data of the batch is correct and can be executed /// @dev Verifies that batch number, batch hash and priority operations hash are correct function _checkBatchData( StoredBatchInfo memory _storedBatch, uint256 _executedBatchIdx, bytes32 _priorityOperationsHash ) internal view { uint256 currentBatchNumber = _storedBatch.batchNumber; if (currentBatchNumber != s.totalBatchesExecuted + _executedBatchIdx + 1) { revert NonSequentialBatch(); } if (_hashStoredBatchInfo(_storedBatch) != s.storedBatchHashes[currentBatchNumber]) { revert BatchHashMismatch(s.storedBatchHashes[currentBatchNumber], _hashStoredBatchInfo(_storedBatch)); } if (_priorityOperationsHash != _storedBatch.priorityOperationsHash) { revert PriorityOperationsRollingHashMismatch(); } } /// @dev Executes one batch /// @dev 1. Processes all pending operations (Complete priority requests) /// @dev 2. Finalizes batch on Ethereum /// @dev _executedBatchIdx is an index in the array of the batches that we want to execute together function _executeOneBatch(StoredBatchInfo memory _storedBatch, uint256 _executedBatchIdx) internal { bytes32 priorityOperationsHash = _collectOperationsFromPriorityQueue(_storedBatch.numberOfLayer1Txs); _checkBatchData(_storedBatch, _executedBatchIdx, priorityOperationsHash); uint256 currentBatchNumber = _storedBatch.batchNumber; // Save root hash of L2 -> L1 logs tree s.l2LogsRootHashes[currentBatchNumber] = _storedBatch.l2LogsTreeRoot; _appendMessageRoot(currentBatchNumber, _storedBatch.l2LogsTreeRoot); } /// @notice Executes one batch /// @dev 1. Processes all pending operations (Complete priority requests) /// @dev 2. Finalizes batch /// @dev _executedBatchIdx is an index in the array of the batches that we want to execute together function _executeOneBatch( StoredBatchInfo memory _storedBatch, PriorityOpsBatchInfo memory _priorityOpsData, uint256 _executedBatchIdx ) internal { if (_priorityOpsData.itemHashes.length != _storedBatch.numberOfLayer1Txs) { revert MismatchNumberOfLayer1Txs(_priorityOpsData.itemHashes.length, _storedBatch.numberOfLayer1Txs); } bytes32 priorityOperationsHash = _rollingHash(_priorityOpsData.itemHashes); _checkBatchData(_storedBatch, _executedBatchIdx, priorityOperationsHash); s.priorityTree.processBatch(_priorityOpsData); uint256 currentBatchNumber = _storedBatch.batchNumber; // Save root hash of L2 -> L1 logs tree s.l2LogsRootHashes[currentBatchNumber] = _storedBatch.l2LogsTreeRoot; _appendMessageRoot(currentBatchNumber, _storedBatch.l2LogsTreeRoot); } /// @notice Appends the batch message root to the global message. /// @param _batchNumber The number of the batch /// @param _messageRoot The root of the merkle tree of the messages to L1. /// @dev The logic of this function depends on the settlement layer as we support /// message root aggregation only on non-L1 settlement layers for ease for migration. function _appendMessageRoot(uint256 _batchNumber, bytes32 _messageRoot) internal { // During migration to the new protocol version, there will be a period when // the bridgehub does not yet provide the `messageRoot` functionality. // To ease up the migration, we never append messages to message root on L1. if (block.chainid != L1_CHAIN_ID) { // Once the batch is executed, we include its message to the message root. IMessageRoot messageRootContract = IBridgehub(s.bridgehub).messageRoot(); messageRootContract.addChainBatchRoot(s.chainId, _batchNumber, _messageRoot); } } /// @inheritdoc IExecutor function executeBatchesSharedBridge( uint256, // _chainId uint256 _processFrom, uint256 _processTo, bytes calldata _executeData ) external nonReentrant onlyValidator onlySettlementLayer { (StoredBatchInfo[] memory batchesData, PriorityOpsBatchInfo[] memory priorityOpsData) = BatchDecoder .decodeAndCheckExecuteData(_executeData, _processFrom, _processTo); uint256 nBatches = batchesData.length; if (batchesData.length != priorityOpsData.length) { revert InvalidBatchesDataLength(batchesData.length, priorityOpsData.length); } for (uint256 i = 0; i < nBatches; i = i.uncheckedInc()) { if (_isPriorityQueueActive()) { if (priorityOpsData[i].leftPath.length != 0) { revert PriorityOpsDataLeftPathLengthIsNotZero(); } if (priorityOpsData[i].rightPath.length != 0) { revert PriorityOpsDataRightPathLengthIsNotZero(); } if (priorityOpsData[i].itemHashes.length != 0) { revert PriorityOpsDataItemHashesLengthIsNotZero(); } _executeOneBatch(batchesData[i], i); } else { _executeOneBatch(batchesData[i], priorityOpsData[i], i); } emit BlockExecution(batchesData[i].batchNumber, batchesData[i].batchHash, batchesData[i].commitment); } uint256 newTotalBatchesExecuted = s.totalBatchesExecuted + nBatches; s.totalBatchesExecuted = newTotalBatchesExecuted; if (newTotalBatchesExecuted > s.totalBatchesVerified) { revert CantExecuteUnprovenBatches(); } uint256 batchWhenUpgradeHappened = s.l2SystemContractsUpgradeBatchNumber; if (batchWhenUpgradeHappened != 0 && batchWhenUpgradeHappened <= newTotalBatchesExecuted) { delete s.l2SystemContractsUpgradeTxHash; delete s.l2SystemContractsUpgradeBatchNumber; } } /// @inheritdoc IExecutor function proveBatchesSharedBridge( uint256, // _chainId uint256 _processBatchFrom, uint256 _processBatchTo, bytes calldata _proofData ) external nonReentrant onlyValidator onlySettlementLayer { ( StoredBatchInfo memory prevBatch, StoredBatchInfo[] memory committedBatches, uint256[] memory proof ) = BatchDecoder.decodeAndCheckProofData(_proofData, _processBatchFrom, _processBatchTo); // Save the variables into the stack to save gas on reading them later uint256 currentTotalBatchesVerified = s.totalBatchesVerified; uint256 committedBatchesLength = committedBatches.length; // Initialize the array, that will be used as public input to the ZKP uint256[] memory proofPublicInput = new uint256[](committedBatchesLength); // Check that the batch passed by the validator is indeed the first unverified batch if (_hashStoredBatchInfo(prevBatch) != s.storedBatchHashes[currentTotalBatchesVerified]) { revert BatchHashMismatch(s.storedBatchHashes[currentTotalBatchesVerified], _hashStoredBatchInfo(prevBatch)); } bytes32 prevBatchCommitment = prevBatch.commitment; for (uint256 i = 0; i < committedBatchesLength; i = i.uncheckedInc()) { currentTotalBatchesVerified = currentTotalBatchesVerified.uncheckedInc(); if (_hashStoredBatchInfo(committedBatches[i]) != s.storedBatchHashes[currentTotalBatchesVerified]) { revert BatchHashMismatch( s.storedBatchHashes[currentTotalBatchesVerified], _hashStoredBatchInfo(committedBatches[i]) ); } bytes32 currentBatchCommitment = committedBatches[i].commitment; proofPublicInput[i] = _getBatchProofPublicInput(prevBatchCommitment, currentBatchCommitment); prevBatchCommitment = currentBatchCommitment; } if (currentTotalBatchesVerified > s.totalBatchesCommitted) { revert VerifiedBatchesExceedsCommittedBatches(); } _verifyProof(proofPublicInput, proof); emit BlocksVerification(s.totalBatchesVerified, currentTotalBatchesVerified); s.totalBatchesVerified = currentTotalBatchesVerified; } function _verifyProof(uint256[] memory proofPublicInput, uint256[] memory _proof) internal view { // We can only process 1 batch proof at a time. if (proofPublicInput.length != 1) { revert CanOnlyProcessOneBatch(); } bool successVerifyProof = s.verifier.verify(proofPublicInput, _proof); if (!successVerifyProof) { revert InvalidProof(); } } /// @dev Gets zk proof public input function _getBatchProofPublicInput( bytes32 _prevBatchCommitment, bytes32 _currentBatchCommitment ) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_prevBatchCommitment, _currentBatchCommitment))) >> PUBLIC_INPUT_SHIFT; } /// @inheritdoc IExecutor function revertBatchesSharedBridge( uint256, uint256 _newLastBatch ) external nonReentrant onlyValidatorOrChainTypeManager { _revertBatches(_newLastBatch); } function _revertBatches(uint256 _newLastBatch) internal onlySettlementLayer { if (s.totalBatchesCommitted <= _newLastBatch) { revert RevertedBatchNotAfterNewLastBatch(); } if (_newLastBatch < s.totalBatchesExecuted) { revert CantRevertExecutedBatch(); } if (_newLastBatch < s.totalBatchesVerified) { s.totalBatchesVerified = _newLastBatch; } s.totalBatchesCommitted = _newLastBatch; // Reset the batch number of the executed system contracts upgrade transaction if the batch // where the system contracts upgrade was committed is among the reverted batches. if (s.l2SystemContractsUpgradeBatchNumber > _newLastBatch) { delete s.l2SystemContractsUpgradeBatchNumber; } emit BlocksRevert(s.totalBatchesCommitted, s.totalBatchesVerified, s.totalBatchesExecuted); } /// @dev Creates batch commitment from its data function _createBatchCommitment( CommitBatchInfo memory _newBatchData, bytes32 _stateDiffHash, bytes32[] memory _blobCommitments, bytes32[] memory _blobHashes ) internal view returns (bytes32 metadataHash, bytes32 auxiliaryOutputHash, bytes32 commitment) { bytes32 passThroughDataHash = keccak256(_batchPassThroughData(_newBatchData)); metadataHash = keccak256(_batchMetaParameters()); auxiliaryOutputHash = keccak256( _batchAuxiliaryOutput(_newBatchData, _stateDiffHash, _blobCommitments, _blobHashes) ); commitment = keccak256(abi.encode(passThroughDataHash, metadataHash, auxiliaryOutputHash)); } function _batchPassThroughData(CommitBatchInfo memory _batch) internal pure returns (bytes memory) { return abi.encodePacked( // solhint-disable-next-line func-named-parameters _batch.indexRepeatedStorageChanges, _batch.newStateRoot, uint64(0), // index repeated storage changes in zkPorter bytes32(0) // zkPorter batch hash ); } function _batchMetaParameters() internal view returns (bytes memory) { return abi.encodePacked( s.zkPorterIsAvailable, s.l2BootloaderBytecodeHash, s.l2DefaultAccountBytecodeHash, s.l2EvmEmulatorBytecodeHash ); } function _batchAuxiliaryOutput( CommitBatchInfo memory _batch, bytes32 _stateDiffHash, bytes32[] memory _blobCommitments, bytes32[] memory _blobHashes ) internal pure returns (bytes memory) { if (_batch.systemLogs.length > MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES) { revert SystemLogsSizeTooBig(); } bytes32 l2ToL1LogsHash = keccak256(_batch.systemLogs); return // solhint-disable-next-line func-named-parameters abi.encodePacked( l2ToL1LogsHash, _stateDiffHash, _batch.bootloaderHeapInitialContentsHash, _batch.eventsQueueStateHash, _encodeBlobAuxiliaryOutput(_blobCommitments, _blobHashes) ); } /// @dev Encodes the commitment to blobs to be used in the auxiliary output of the batch commitment /// @param _blobCommitments - the commitments to the blobs /// @param _blobHashes - the hashes of the blobs /// @param blobAuxOutputWords - The circuit commitment to the blobs split into 32-byte words function _encodeBlobAuxiliaryOutput( bytes32[] memory _blobCommitments, bytes32[] memory _blobHashes ) internal pure returns (bytes32[] memory blobAuxOutputWords) { // These invariants should be checked by the caller of this function, but we double check // just in case. if (_blobCommitments.length != TOTAL_BLOBS_IN_COMMITMENT || _blobHashes.length != TOTAL_BLOBS_IN_COMMITMENT) { revert InvalidNumberOfBlobs(TOTAL_BLOBS_IN_COMMITMENT, _blobCommitments.length, _blobHashes.length); } // for each blob we have: // linear hash (hash of preimage from system logs) and // output hash of blob commitments: keccak(versioned hash || opening point || evaluation value) // These values will all be bytes32(0) when we submit pubdata via calldata instead of blobs. // // For now, only up to 6 blobs are supported by the contract, while 16 are required by the circuits. // All the unfilled blobs will have their commitment as 0, including the case when we use only 1 blob. blobAuxOutputWords = new bytes32[](2 * TOTAL_BLOBS_IN_COMMITMENT); for (uint256 i = 0; i < TOTAL_BLOBS_IN_COMMITMENT; ++i) { blobAuxOutputWords[i * 2] = _blobHashes[i]; blobAuxOutputWords[i * 2 + 1] = _blobCommitments[i]; } } /// @notice Returns the keccak hash of the ABI-encoded StoredBatchInfo function _hashStoredBatchInfo(StoredBatchInfo memory _storedBatchInfo) internal pure returns (bytes32) { return keccak256(abi.encode(_storedBatchInfo)); } /// @notice Returns true if the bit at index {_index} is 1 function _checkBit(uint256 _bitMap, uint8 _index) internal pure returns (bool) { return (_bitMap & (1 << _index)) > 0; } /// @notice Sets the given bit in {_num} at index {_index} to 1. function _setBit(uint256 _bitMap, uint8 _index) internal pure returns (uint256) { return _bitMap | (1 << _index); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ZKChainStorage} from "../ZKChainStorage.sol"; import {ReentrancyGuard} from "../../../common/ReentrancyGuard.sol"; import {PriorityQueue} from "../../libraries/PriorityQueue.sol"; import {PriorityTree} from "../../libraries/PriorityTree.sol"; import {NotSettlementLayer} from "../../L1StateTransitionErrors.sol"; import {Unauthorized} from "../../../common/L1ContractErrors.sol"; /// @title Base contract containing functions accessible to the other facets. /// @author Matter Labs /// @custom:security-contact [email protected] contract ZKChainBase is ReentrancyGuard { using PriorityQueue for PriorityQueue.Queue; using PriorityTree for PriorityTree.Tree; // slither-disable-next-line uninitialized-state ZKChainStorage internal s; /// @notice Checks that the message sender is an active admin modifier onlyAdmin() { if (msg.sender != s.admin) { revert Unauthorized(msg.sender); } _; } /// @notice Checks if validator is active modifier onlyValidator() { if (!s.validators[msg.sender]) { revert Unauthorized(msg.sender); } _; } modifier onlyChainTypeManager() { if (msg.sender != s.chainTypeManager) { revert Unauthorized(msg.sender); } _; } modifier onlyBridgehub() { if (msg.sender != s.bridgehub) { revert Unauthorized(msg.sender); } _; } modifier onlyAdminOrChainTypeManager() { if (msg.sender != s.admin && msg.sender != s.chainTypeManager) { revert Unauthorized(msg.sender); } _; } modifier onlyValidatorOrChainTypeManager() { if (!s.validators[msg.sender] && msg.sender != s.chainTypeManager) { revert Unauthorized(msg.sender); } _; } modifier onlySettlementLayer() { if (s.settlementLayer != address(0)) { revert NotSettlementLayer(); } _; } modifier onlySelf() { if (msg.sender != address(this)) { revert Unauthorized(msg.sender); } _; } /// @notice Returns whether the priority queue is still active, i.e. /// the chain has not processed all transactions from it function _isPriorityQueueActive() internal view returns (bool) { return s.priorityQueue.getFirstUnprocessedPriorityTx() < s.priorityTree.startIndex; } /// @notice Ensures that the queue is deactivated. Should be invoked /// whenever the chain migrates to another settlement layer. function _forceDeactivateQueue() internal { // We double check whether it is still active mainly to prevent // overriding `tail`/`head` on L1 deployment. if (_isPriorityQueueActive()) { uint256 startIndex = s.priorityTree.startIndex; s.priorityQueue.head = startIndex; s.priorityQueue.tail = startIndex; } } function _getTotalPriorityTxs() internal view returns (uint256) { if (_isPriorityQueueActive()) { return s.priorityQueue.getTotalPriorityTxs(); } else { return s.priorityTree.getTotalPriorityTxs(); } } }
// 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 {L2Message, L2Log, TxStatus} from "../common/Messaging.sol"; import {IL1AssetHandler} from "../bridge/interfaces/IL1AssetHandler.sol"; import {ICTMDeploymentTracker} from "./ICTMDeploymentTracker.sol"; import {IMessageRoot} from "./IMessageRoot.sol"; import {IAssetHandler} from "../bridge/interfaces/IAssetHandler.sol"; struct L2TransactionRequestDirect { uint256 chainId; uint256 mintValue; address l2Contract; uint256 l2Value; bytes l2Calldata; uint256 l2GasLimit; uint256 l2GasPerPubdataByteLimit; bytes[] factoryDeps; address refundRecipient; } struct L2TransactionRequestTwoBridgesOuter { uint256 chainId; uint256 mintValue; uint256 l2Value; uint256 l2GasLimit; uint256 l2GasPerPubdataByteLimit; address refundRecipient; address secondBridgeAddress; uint256 secondBridgeValue; bytes secondBridgeCalldata; } struct L2TransactionRequestTwoBridgesInner { bytes32 magicValue; address l2Contract; bytes l2Calldata; bytes[] factoryDeps; bytes32 txDataHash; } struct BridgehubMintCTMAssetData { uint256 chainId; bytes32 baseTokenAssetId; bytes ctmData; bytes chainData; } struct BridgehubBurnCTMAssetData { uint256 chainId; bytes ctmData; bytes chainData; } /// @author Matter Labs /// @custom:security-contact [email protected] interface IBridgehub is IAssetHandler, IL1AssetHandler { /// @notice pendingAdmin is changed /// @dev Also emitted when new admin is accepted and in this case, `newPendingAdmin` would be zero address event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); /// @notice Admin changed event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /// @notice CTM asset registered event AssetRegistered( bytes32 indexed assetInfo, address indexed _assetAddress, bytes32 indexed additionalData, address sender ); event SettlementLayerRegistered(uint256 indexed chainId, bool indexed isWhitelisted); /// @notice Emitted when the bridging to the chain is started. /// @param chainId Chain ID of the ZK chain /// @param assetId Asset ID of the token for the zkChain's CTM /// @param settlementLayerChainId The chain id of the settlement layer the chain migrates to. event MigrationStarted(uint256 indexed chainId, bytes32 indexed assetId, uint256 indexed settlementLayerChainId); /// @notice Emitted when the bridging to the chain is complete. /// @param chainId Chain ID of the ZK chain /// @param assetId Asset ID of the token for the zkChain's CTM /// @param zkChain The address of the ZK chain on the chain where it is migrated to. event MigrationFinalized(uint256 indexed chainId, bytes32 indexed assetId, address indexed zkChain); /// @notice Starts the transfer of admin rights. Only the current admin or owner can propose a new pending one. /// @notice New admin can accept admin rights by calling `acceptAdmin` function. /// @param _newPendingAdmin Address of the new admin function setPendingAdmin(address _newPendingAdmin) external; /// @notice Accepts transfer of admin rights. Only pending admin can accept the role. function acceptAdmin() external; /// Getters function chainTypeManagerIsRegistered(address _chainTypeManager) external view returns (bool); function chainTypeManager(uint256 _chainId) external view returns (address); function assetIdIsRegistered(bytes32 _baseTokenAssetId) external view returns (bool); function baseToken(uint256 _chainId) external view returns (address); function baseTokenAssetId(uint256 _chainId) external view returns (bytes32); function sharedBridge() external view returns (address); function messageRoot() external view returns (IMessageRoot); function getZKChain(uint256 _chainId) external view returns (address); function getAllZKChains() external view returns (address[] memory); function getAllZKChainChainIDs() external view returns (uint256[] memory); function migrationPaused() external view returns (bool); function admin() external view returns (address); function assetRouter() external view returns (address); /// Mailbox forwarder function proveL2MessageInclusion( uint256 _chainId, uint256 _batchNumber, uint256 _index, L2Message calldata _message, bytes32[] calldata _proof ) external view returns (bool); function proveL2LogInclusion( uint256 _chainId, uint256 _batchNumber, uint256 _index, L2Log memory _log, bytes32[] calldata _proof ) external view returns (bool); function proveL1ToL2TransactionStatus( uint256 _chainId, bytes32 _l2TxHash, uint256 _l2BatchNumber, uint256 _l2MessageIndex, uint16 _l2TxNumberInBatch, bytes32[] calldata _merkleProof, TxStatus _status ) external view returns (bool); function requestL2TransactionDirect( L2TransactionRequestDirect calldata _request ) external payable returns (bytes32 canonicalTxHash); function requestL2TransactionTwoBridges( L2TransactionRequestTwoBridgesOuter calldata _request ) external payable returns (bytes32 canonicalTxHash); function l2TransactionBaseCost( uint256 _chainId, uint256 _gasPrice, uint256 _l2GasLimit, uint256 _l2GasPerPubdataByteLimit ) external view returns (uint256); //// Registry function createNewChain( uint256 _chainId, address _chainTypeManager, bytes32 _baseTokenAssetId, uint256 _salt, address _admin, bytes calldata _initData, bytes[] calldata _factoryDeps ) external returns (uint256 chainId); function addChainTypeManager(address _chainTypeManager) external; function removeChainTypeManager(address _chainTypeManager) external; function addTokenAssetId(bytes32 _baseTokenAssetId) external; function setAddresses( address _sharedBridge, ICTMDeploymentTracker _l1CtmDeployer, IMessageRoot _messageRoot ) external; event NewChain(uint256 indexed chainId, address chainTypeManager, address indexed chainGovernance); event ChainTypeManagerAdded(address indexed chainTypeManager); event ChainTypeManagerRemoved(address indexed chainTypeManager); event BaseTokenAssetIdRegistered(bytes32 indexed assetId); function whitelistedSettlementLayers(uint256 _chainId) external view returns (bool); function registerSettlementLayer(uint256 _newSettlementLayerChainId, bool _isWhitelisted) external; function settlementLayer(uint256 _chainId) external view returns (uint256); // function finalizeMigrationToGateway( // uint256 _chainId, // address _baseToken, // address _sharedBridge, // address _admin, // uint256 _expectedProtocolVersion, // ZKChainCommitment calldata _commitment, // bytes calldata _diamondCut // ) external; function forwardTransactionOnGateway( uint256 _chainId, bytes32 _canonicalTxHash, uint64 _expirationTimestamp ) external; function ctmAssetIdFromChainId(uint256 _chainId) external view returns (bytes32); function ctmAssetIdFromAddress(address _ctmAddress) external view returns (bytes32); function l1CtmDeployer() external view returns (ICTMDeploymentTracker); function ctmAssetIdToAddress(bytes32 _assetInfo) external view returns (address); function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress) external; function L1_CHAIN_ID() external view returns (uint256); function registerAlreadyDeployedZKChain(uint256 _chainId, address _hyperchain) external; /// @notice return the ZK chain contract for a chainId /// @dev It is a legacy method. Do not use! function getHyperchain(uint256 _chainId) external view returns (address); function registerLegacyChain(uint256 _chainId) external; function pauseMigration() external; function unpauseMigration() external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridgehub} from "./IBridgehub.sol"; /** * @author Matter Labs * @notice MessageRoot contract is responsible for storing and aggregating the roots of the batches from different chains into the MessageRoot. * @custom:security-contact [email protected] */ interface IMessageRoot { function BRIDGE_HUB() external view returns (IBridgehub); function addNewChain(uint256 _chainId) external; function addChainBatchRoot(uint256 _chainId, uint256 _batchNumber, bytes32 _chainBatchRoot) external; }
// 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; /// @dev `keccak256("")` bytes32 constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /// @dev Bytes in raw L2 log /// @dev Equal to the bytes size of the tuple - (uint8 ShardId, bool isService, uint16 txNumberInBatch, address sender, /// bytes32 key, bytes32 value) uint256 constant L2_TO_L1_LOG_SERIALIZE_SIZE = 88; /// @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; /// @dev The value of default leaf hash for L2 -> 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; bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = bytes32(0); /// @dev Denotes the type of the ZKsync transaction that came from L1. uint256 constant PRIORITY_OPERATION_L2_TX_TYPE = 255; /// @dev Denotes the type of the ZKsync transaction that is used for system upgrades. uint256 constant SYSTEM_UPGRADE_L2_TX_TYPE = 254; /// @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 The amount of time in seconds the validator has to process the priority transaction /// NOTE: The constant is set to zero for the Alpha release period uint256 constant PRIORITY_EXPIRATION = 0 days; /// @dev Timestamp - seconds since unix epoch. uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 3 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 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 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 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; } /// @dev Used as the `msg.sender` for system service transactions. address constant SERVICE_TRANSACTION_SENDER = address(uint160(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF));
// 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"; /// @dev Enum used by L2 System Contracts to differentiate logs. 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_VALIDATOR_ADDRESS_KEY, EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY } struct LogProcessingOutput { uint256 numberOfLayer1Txs; bytes32 chainedPriorityTxsHash; bytes32 previousBatchHash; bytes32 pubdataHash; bytes32 stateDiffHash; bytes32 l2LogsTreeRoot; uint256 packedBatchAndL2BlockTimestamp; bytes32 l2DAValidatorOutputHash; } /// @dev Offset used to pull Address From Log. Equal to 4 (bytes for isService) uint256 constant L2_LOG_ADDRESS_OFFSET = 4; /// @dev Offset used to pull Key From Log. Equal to 4 (bytes for isService) + 20 (bytes for address) uint256 constant L2_LOG_KEY_OFFSET = 24; /// @dev Offset used to pull Value From Log. Equal to 4 (bytes for isService) + 20 (bytes for address) + 32 (bytes for key) uint256 constant L2_LOG_VALUE_OFFSET = 56; /// @dev Max number of blobs currently supported uint256 constant MAX_NUMBER_OF_BLOBS = 6; /// @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 /// @param batchNumber Rollup batch number /// @param batchHash Hash of L2 batch /// @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 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 /// @param commitment Verified input for the ZKsync circuit // solhint-disable-next-line gas-struct-packing struct StoredBatchInfo { uint64 batchNumber; bytes32 batchHash; uint64 indexRepeatedStorageChanges; uint256 numberOfLayer1Txs; bytes32 priorityOperationsHash; bytes32 l2LogsTreeRoot; uint256 timestamp; bytes32 commitment; } /// @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 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 _chainId Chain ID of the chain. /// @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( uint256 _chainId, uint256 _processFrom, uint256 _processTo, bytes calldata _commitData ) external; /// @notice Batches commitment verification. /// @dev Only verifies batch commitments without any other processing. /// @param _chainId Chain ID of the chain. /// @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( uint256 _chainId, 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 _chainId Chain ID of the chain. /// @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. function executeBatchesSharedBridge( uint256 _chainId, uint256 _processFrom, uint256 _processTo, bytes calldata _executeData ) external; /// @notice Reverts unexecuted batches /// @param _chainId Chain ID of the chain /// @param _newLastBatch batch number after which batches should be reverted /// NOTE: Doesn't delete the stored data about batches, but only decreases /// counters that are responsible for the number of batches function revertBatchesSharedBridge(uint256 _chainId, uint256 _newLastBatch) 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 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); }
// 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 {QueueIsEmpty} from "../../common/L1ContractErrors.sol"; /// @notice The structure that contains meta information of the L2 transaction that was requested from L1 /// @dev The weird size of fields was selected specifically to minimize the structure storage size /// @param canonicalTxHash Hashed L2 transaction data that is needed to process it /// @param expirationTimestamp Expiration timestamp for this request (must be satisfied before) /// @param layer2Tip Additional payment to the validator as an incentive to perform the operation struct PriorityOperation { bytes32 canonicalTxHash; uint64 expirationTimestamp; uint192 layer2Tip; } /// @author Matter Labs /// @custom:security-contact [email protected] /// @dev The library provides the API to interact with the priority queue container /// @dev Order of processing operations from queue - FIFO (Fist in - first out) library PriorityQueue { using PriorityQueue for Queue; /// @notice Container that stores priority operations /// @param data The inner mapping that saves priority operation by its index /// @param head The pointer to the first unprocessed priority operation, equal to the tail if the queue is empty /// @param tail The pointer to the free slot struct Queue { mapping(uint256 priorityOpId => PriorityOperation priorityOp) data; uint256 tail; uint256 head; } /// @notice Returns zero if and only if no operations were processed from the queue /// @return Index of the oldest priority operation that wasn't processed yet function getFirstUnprocessedPriorityTx(Queue storage _queue) internal view returns (uint256) { return _queue.head; } /// @return The total number of priority operations that were added to the priority queue, including all processed ones function getTotalPriorityTxs(Queue storage _queue) internal view returns (uint256) { return _queue.tail; } /// @return The total number of unprocessed priority operations in a priority queue function getSize(Queue storage _queue) internal view returns (uint256) { return uint256(_queue.tail - _queue.head); } /// @return Whether the priority queue contains no operations function isEmpty(Queue storage _queue) internal view returns (bool) { return _queue.tail == _queue.head; } /// @notice Add the priority operation to the end of the priority queue function pushBack(Queue storage _queue, PriorityOperation memory _operation) internal { // Save value into the stack to avoid double reading from the storage uint256 tail = _queue.tail; _queue.data[tail] = _operation; _queue.tail = tail + 1; } /// @return The first unprocessed priority operation from the queue function front(Queue storage _queue) internal view returns (PriorityOperation memory) { // priority queue is empty if (_queue.isEmpty()) { revert QueueIsEmpty(); } return _queue.data[_queue.head]; } /// @notice Remove the first unprocessed priority operation from the queue /// @return priorityOperation that was popped from the priority queue function popFront(Queue storage _queue) internal returns (PriorityOperation memory priorityOperation) { // priority queue is empty if (_queue.isEmpty()) { revert QueueIsEmpty(); } // Save value into the stack to avoid double reading from the storage uint256 head = _queue.head; priorityOperation = _queue.data[head]; delete _queue.data[head]; _queue.head = head + 1; } }
// 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 {IExecutor} from "../chain-interfaces/IExecutor.sol"; import {PriorityOpsBatchInfo} from "./PriorityTree.sol"; import {IncorrectBatchBounds, EmptyData, UnsupportedCommitBatchEncoding, UnsupportedProofBatchEncoding, UnsupportedExecuteBatchEncoding} from "../../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Utility library for decoding and validating batch data. /// @dev This library decodes commit, proof, and execution batch data and verifies batch number bounds. /// It reverts with custom errors when the data is invalid or unsupported encoding is used. library BatchDecoder { /// @notice The currently supported encoding version. uint8 internal constant SUPPORTED_ENCODING_VERSION = 0; /// @notice Decodes commit data from a calldata bytes into the last committed batch data and an array of new batch data. /// @param _commitData The calldata byte array containing the data for committing batches. /// @return lastCommittedBatchData The data for the batch before newly committed batches. /// @return newBatchesData An array containing the newly committed batches. function _decodeCommitData( bytes calldata _commitData ) private pure returns ( IExecutor.StoredBatchInfo memory lastCommittedBatchData, IExecutor.CommitBatchInfo[] memory newBatchesData ) { if (_commitData.length == 0) { revert EmptyData(); } uint8 encodingVersion = uint8(_commitData[0]); if (encodingVersion == SUPPORTED_ENCODING_VERSION) { (lastCommittedBatchData, newBatchesData) = abi.decode( _commitData[1:], (IExecutor.StoredBatchInfo, IExecutor.CommitBatchInfo[]) ); } else { revert UnsupportedCommitBatchEncoding(encodingVersion); } } /// @notice Decodes the commit data and checks that the provided batch bounds are correct. /// @dev Note that it only checks that the last and the first batches in the array correspond to the provided bounds. /// The fact that the batches inside the array are provided in the correct order should be checked by the caller. /// @param _commitData The calldata byte array containing the data for committing batches. /// @param _processBatchFrom The expected batch number of the first commit batch in the array. /// @param _processBatchTo The expected batch number of the last commit batch in the array. /// @return lastCommittedBatchData The data for the batch before newly committed batches. /// @return newBatchesData An array containing the newly committed batches. function decodeAndCheckCommitData( bytes calldata _commitData, uint256 _processBatchFrom, uint256 _processBatchTo ) internal pure returns ( IExecutor.StoredBatchInfo memory lastCommittedBatchData, IExecutor.CommitBatchInfo[] memory newBatchesData ) { (lastCommittedBatchData, newBatchesData) = _decodeCommitData(_commitData); if (newBatchesData.length == 0) { revert EmptyData(); } if ( newBatchesData[0].batchNumber != _processBatchFrom || newBatchesData[newBatchesData.length - 1].batchNumber != _processBatchTo ) { revert IncorrectBatchBounds( _processBatchFrom, _processBatchTo, newBatchesData[0].batchNumber, newBatchesData[newBatchesData.length - 1].batchNumber ); } } /// @notice Decodes proof data from a calldata byte array into the previous batch, an array of proved batches, and a proof array. /// @param _proofData The calldata byte array containing the data for proving batches. /// @return prevBatch The batch information before the batches to be verified. /// @return provedBatches An array containing the the batches to be verified. /// @return proof An array containing the proof for the verifier. function _decodeProofData( bytes calldata _proofData ) private pure returns ( IExecutor.StoredBatchInfo memory prevBatch, IExecutor.StoredBatchInfo[] memory provedBatches, uint256[] memory proof ) { uint8 encodingVersion = uint8(_proofData[0]); if (encodingVersion == SUPPORTED_ENCODING_VERSION) { (prevBatch, provedBatches, proof) = abi.decode( _proofData[1:], (IExecutor.StoredBatchInfo, IExecutor.StoredBatchInfo[], uint256[]) ); } else { revert UnsupportedProofBatchEncoding(encodingVersion); } } /// @notice Decodes the commit data and checks that the provided batch bounds are correct. /// @dev Note that it only checks that the last and the first batches in the array correspond to the provided bounds. /// The fact that the batches inside the array are provided in the correct order should be checked by the caller. /// @param _proofData The commit data to decode. /// @param _processBatchFrom The expected batch number of the first batch in the array. /// @param _processBatchTo The expected batch number of the last batch in the array. /// @return prevBatch The batch information before the batches to be verified. /// @return provedBatches An array containing the the batches to be verified. /// @return proof An array containing the proof for the verifier. function decodeAndCheckProofData( bytes calldata _proofData, uint256 _processBatchFrom, uint256 _processBatchTo ) internal pure returns ( IExecutor.StoredBatchInfo memory prevBatch, IExecutor.StoredBatchInfo[] memory provedBatches, uint256[] memory proof ) { (prevBatch, provedBatches, proof) = _decodeProofData(_proofData); if (provedBatches.length == 0) { revert EmptyData(); } if ( provedBatches[0].batchNumber != _processBatchFrom || provedBatches[provedBatches.length - 1].batchNumber != _processBatchTo ) { revert IncorrectBatchBounds( _processBatchFrom, _processBatchTo, provedBatches[0].batchNumber, provedBatches[provedBatches.length - 1].batchNumber ); } } /// @notice Decodes execution data from a calldata byte array into an array of stored batch information. /// @param _executeData The calldata byte array containing the execution data to decode. /// @return executeData An array containing the stored batch information for execution. /// @return priorityOpsData Merkle proofs of the priority operations for each batch. function _decodeExecuteData( bytes calldata _executeData ) private pure returns (IExecutor.StoredBatchInfo[] memory executeData, PriorityOpsBatchInfo[] memory priorityOpsData) { if (_executeData.length == 0) { revert EmptyData(); } uint8 encodingVersion = uint8(_executeData[0]); if (encodingVersion == SUPPORTED_ENCODING_VERSION) { (executeData, priorityOpsData) = abi.decode( _executeData[1:], (IExecutor.StoredBatchInfo[], PriorityOpsBatchInfo[]) ); } else { revert UnsupportedExecuteBatchEncoding(encodingVersion); } } /// @notice Decodes the execute data and checks that the provided batch bounds are correct. /// @dev Note that it only checks that the last and the first batches in the array correspond to the provided bounds. /// The fact that the batches inside the array are provided in the correct order should be checked by the caller. /// @param _executeData The calldata byte array containing the execution data to decode. /// @param _processBatchFrom The expected batch number of the first batch in the array. /// @param _processBatchTo The expected batch number of the last batch in the array. /// @return executeData An array containing the stored batch information for execution. /// @return priorityOpsData Merkle proofs of the priority operations for each batch. function decodeAndCheckExecuteData( bytes calldata _executeData, uint256 _processBatchFrom, uint256 _processBatchTo ) internal pure returns (IExecutor.StoredBatchInfo[] memory executeData, PriorityOpsBatchInfo[] memory priorityOpsData) { (executeData, priorityOpsData) = _decodeExecuteData(_executeData); if (executeData.length == 0) { revert EmptyData(); } if ( executeData[0].batchNumber != _processBatchFrom || executeData[executeData.length - 1].batchNumber != _processBatchTo ) { revert IncorrectBatchBounds( _processBatchFrom, _processBatchTo, executeData[0].batchNumber, executeData[executeData.length - 1].batchNumber ); } } }
// 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; /** * @author Matter Labs * @custom:security-contact [email protected] * @notice The library for unchecked math. */ library UncheckedMath { function uncheckedInc(uint256 _number) internal pure returns (uint256) { unchecked { return _number + 1; } } function uncheckedAdd(uint256 _lhs, uint256 _rhs) internal pure returns (uint256) { unchecked { return _lhs + _rhs; } } }
// 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; /** * @author Matter Labs * @custom:security-contact [email protected] * @dev The library provides a set of functions that help read data from an "abi.encodePacked" byte array. * @dev Each of the functions accepts the `bytes memory` and the offset where data should be read and returns a value of a certain type. * * @dev WARNING! * 1) Functions don't check the length of the bytes array, so it can go out of bounds. * The user of the library must check for bytes length before using any functions from the library! * * 2) Read variables are not cleaned up - https://docs.soliditylang.org/en/v0.8.16/internals/variable_cleanup.html. * Using data in inline assembly can lead to unexpected behavior! */ library UnsafeBytes { function readUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 result, uint256 offset) { assembly { offset := add(_start, 4) result := mload(add(_bytes, offset)) } } function readAddress(bytes memory _bytes, uint256 _start) internal pure returns (address result, uint256 offset) { assembly { offset := add(_start, 20) result := mload(add(_bytes, offset)) } } function readUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256 result, uint256 offset) { assembly { offset := add(_start, 32) result := mload(add(_bytes, offset)) } } function readBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 result, uint256 offset) { assembly { offset := add(_start, 32) result := mload(add(_bytes, offset)) } } function readRemainingBytes(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory result) { uint256 arrayLen = _bytes.length - _start; result = new bytes(arrayLen); assembly { mcopy(add(result, 0x20), add(_bytes, add(0x20, _start)), arrayLen) } } }
// 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; /// @dev the offset for the system contracts uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000; // 2^15 /// @dev The offset from which the built-in, but user space contracts are located. uint160 constant USER_CONTRACTS_OFFSET = 0x10000; // 2^16 /// @dev The formal address of the initial program of the system: the bootloader address constant L2_BOOTLOADER_ADDRESS = address(SYSTEM_CONTRACTS_OFFSET + 0x01); /// @dev The address of the known code storage system contract address constant L2_KNOWN_CODE_STORAGE_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x04); /// @dev The address of the L2 deployer system contract. address constant L2_DEPLOYER_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x06); /// @dev The special reserved L2 address. It is located in the system contracts space but doesn't have deployed /// bytecode. /// @dev The L2 deployer system contract allows changing bytecodes on any address if the `msg.sender` is this address. /// @dev So, whenever the governor wants to redeploy system contracts, it just initiates the L1 upgrade call deployer /// system contract /// via the L1 -> L2 transaction with `sender == L2_FORCE_DEPLOYER_ADDR`. For more details see the /// `diamond-initializers` contracts. address constant L2_FORCE_DEPLOYER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x07); /// @dev The address of the special smart contract that can send arbitrary length message as an L2 log IL2ToL1Messenger constant L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR = IL2ToL1Messenger( address(SYSTEM_CONTRACTS_OFFSET + 0x08) ); /// @dev The address of the eth token system contract address constant L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0a); /// @dev The address of the context system contract address constant L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0b); /// @dev The address of the pubdata chunk publisher contract address constant L2_PUBDATA_CHUNK_PUBLISHER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x11); /// @dev The address used to execute complex upgragedes, also used for the genesis upgrade address constant L2_COMPLEX_UPGRADER_ADDR = address(SYSTEM_CONTRACTS_OFFSET + 0x0f); /// @dev the address of the msg value system contract address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09); /// @dev The address used to execute the genesis upgrade address constant L2_GENESIS_UPGRADE_ADDR = address(USER_CONTRACTS_OFFSET + 0x01); /// @dev The address of the L2 bridge hub system contract, used to start L1->L2 transactions address constant L2_BRIDGEHUB_ADDR = address(USER_CONTRACTS_OFFSET + 0x02); /// @dev the address of the l2 asset router. address constant L2_ASSET_ROUTER_ADDR = address(USER_CONTRACTS_OFFSET + 0x03); /// @dev An l2 system contract address, used in the assetId calculation for native assets. /// This is needed for automatic bridging, i.e. without deploying the AssetHandler contract, /// if the assetId can be calculated with this address then it is in fact an NTV asset address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(USER_CONTRACTS_OFFSET + 0x04); /// @dev the address of the l2 asset router. address constant L2_MESSAGE_ROOT_ADDR = address(USER_CONTRACTS_OFFSET + 0x05); /** * @author Matter Labs * @custom:security-contact [email protected] * @notice Smart contract for sending arbitrary length messages to L1 * @dev by default ZkSync can send fixed-length messages on L1. * A fixed length message has 4 parameters `senderAddress`, `isService`, `key`, `value`, * the first one is taken from the context, the other three are chosen by the sender. * @dev To send a variable-length message we use this trick: * - This system contract accepts an arbitrary length message and sends a fixed length message with * parameters `senderAddress == this`, `isService == true`, `key == msg.sender`, `value == keccak256(message)`. * - The contract on L1 accepts all sent messages and if the message came from this system contract * it requires that the preimage of `value` be provided. */ interface IL2ToL1Messenger { /// @notice Sends an arbitrary length message to L1. /// @param _message The variable length message to be sent to L1. /// @return Returns the keccak256 hashed value of the message. function sendToL1(bytes calldata _message) external returns (bytes32); }
// 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 {Diamond} from "./libraries/Diamond.sol"; import {L2CanonicalTransaction} from "../common/Messaging.sol"; import {FeeParams} from "./chain-deps/ZKChainStorage.sol"; // import {IBridgehub} from "../bridgehub/IBridgehub.sol"; /// @notice Struct that holds all data needed for initializing CTM Proxy. /// @dev We use struct instead of raw parameters in `initialize` function to prevent "Stack too deep" error /// @param owner The address who can manage non-critical updates in the contract /// @param validatorTimelock The address that serves as consensus, i.e. can submit blocks to be processed /// @param chainCreationParams The struct that contains the fields that define how a new chain should be created /// @param protocolVersion The initial protocol version on the newly deployed chain /// @param serverNotifier The address that serves as server notifier // solhint-disable-next-line gas-struct-packing struct ChainTypeManagerInitializeData { address owner; address validatorTimelock; ChainCreationParams chainCreationParams; uint256 protocolVersion; address serverNotifier; } /// @notice The struct that contains the fields that define how a new chain should be created /// within this CTM. /// @param genesisUpgrade The address that is used in the diamond cut initialize address on chain creation /// @param genesisBatchHash Batch hash of the genesis (initial) batch /// @param genesisIndexRepeatedStorageChanges The serial number of the shortcut storage key for the genesis batch /// @param genesisBatchCommitment The zk-proof commitment for the genesis batch /// @param diamondCut The diamond cut for the first upgrade transaction on the newly deployed chain // solhint-disable-next-line gas-struct-packing struct ChainCreationParams { address genesisUpgrade; bytes32 genesisBatchHash; uint64 genesisIndexRepeatedStorageChanges; bytes32 genesisBatchCommitment; Diamond.DiamondCutData diamondCut; bytes forceDeploymentsData; } interface IChainTypeManager { /// @dev Emitted when a new ZKChain is added event NewZKChain(uint256 indexed _chainId, address indexed _zkChainContract); /// @dev emitted when an chain registers and a GenesisUpgrade happens event GenesisUpgrade( address indexed _zkChain, L2CanonicalTransaction _l2Transaction, uint256 indexed _protocolVersion ); /// @notice pendingAdmin is changed /// @dev Also emitted when new admin is accepted and in this case, `newPendingAdmin` would be zero address event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); /// @notice Admin changed event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /// @notice ValidatorTimelock changed event NewValidatorTimelock(address indexed oldValidatorTimelock, address indexed newValidatorTimelock); /// @notice ServerNotifier changed event NewServerNotifier(address indexed oldServerNotifier, address indexed newServerNotifier); /// @notice chain creation parameters changed event NewChainCreationParams( address genesisUpgrade, bytes32 genesisBatchHash, uint64 genesisIndexRepeatedStorageChanges, bytes32 genesisBatchCommitment, bytes32 newInitialCutHash, bytes32 forceDeploymentHash ); /// @notice New UpgradeCutHash event NewUpgradeCutHash(uint256 indexed protocolVersion, bytes32 indexed upgradeCutHash); /// @notice New UpgradeCutData event NewUpgradeCutData(uint256 indexed protocolVersion, Diamond.DiamondCutData diamondCutData); /// @notice New ProtocolVersion event NewProtocolVersion(uint256 indexed oldProtocolVersion, uint256 indexed newProtocolVersion); /// @notice Updated ProtocolVersion deadline event UpdateProtocolVersionDeadline(uint256 indexed protocolVersion, uint256 deadline); function BRIDGE_HUB() external view returns (address); function setPendingAdmin(address _newPendingAdmin) external; function acceptAdmin() external; function getZKChain(uint256 _chainId) external view returns (address); function getHyperchain(uint256 _chainId) external view returns (address); function getZKChainLegacy(uint256 _chainId) external view returns (address); function storedBatchZero() external view returns (bytes32); function initialCutHash() external view returns (bytes32); function l1GenesisUpgrade() external view returns (address); function upgradeCutHash(uint256 _protocolVersion) external view returns (bytes32); function protocolVersion() external view returns (uint256); function protocolVersionDeadline(uint256 _protocolVersion) external view returns (uint256); function protocolVersionIsActive(uint256 _protocolVersion) external view returns (bool); function getProtocolVersion(uint256 _chainId) external view returns (uint256); function initialize(ChainTypeManagerInitializeData calldata _initializeData) external; function setValidatorTimelock(address _validatorTimelock) external; function setChainCreationParams(ChainCreationParams calldata _chainCreationParams) external; function getChainAdmin(uint256 _chainId) external view returns (address); function createNewChain( uint256 _chainId, bytes32 _baseTokenAssetId, address _admin, bytes calldata _initData, bytes[] calldata _factoryDeps ) external returns (address); function setNewVersionUpgrade( Diamond.DiamondCutData calldata _cutData, uint256 _oldProtocolVersion, uint256 _oldProtocolVersionDeadline, uint256 _newProtocolVersion ) external; function setUpgradeDiamondCut(Diamond.DiamondCutData calldata _cutData, uint256 _oldProtocolVersion) external; function executeUpgrade(uint256 _chainId, Diamond.DiamondCutData calldata _diamondCut) external; function setPriorityTxMaxGasLimit(uint256 _chainId, uint256 _maxGasLimit) external; function freezeChain(uint256 _chainId) external; function unfreezeChain(uint256 _chainId) external; function setTokenMultiplier(uint256 _chainId, uint128 _nominator, uint128 _denominator) external; function changeFeeParams(uint256 _chainId, FeeParams calldata _newFeeParams) external; function setValidator(uint256 _chainId, address _validator, bool _active) external; function setPorterAvailability(uint256 _chainId, bool _zkPorterIsAvailable) external; function upgradeChainFromVersion( uint256 _chainId, uint256 _oldProtocolVersion, Diamond.DiamondCutData calldata _diamondCut ) external; function getSemverProtocolVersion() external view returns (uint32, uint32, uint32); function forwardedBridgeBurn( uint256 _chainId, bytes calldata _data ) external returns (bytes memory _bridgeMintData); function forwardedBridgeMint(uint256 _chainId, bytes calldata _data) external returns (address); function forwardedBridgeRecoverFailedTransfer( uint256 _chainId, bytes32 _assetInfo, address _depositSender, bytes calldata _ctmData ) external; }
// 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 {DynamicIncrementalMerkle} from "../../common/libraries/DynamicIncrementalMerkle.sol"; import {Merkle} from "../../common/libraries/Merkle.sol"; import {PriorityTreeCommitment} from "../../common/Config.sol"; import {NotHistoricalRoot, InvalidCommitment, InvalidStartIndex, InvalidUnprocessedIndex, InvalidNextLeafIndex} from "../L1StateTransitionErrors.sol"; struct PriorityOpsBatchInfo { bytes32[] leftPath; bytes32[] rightPath; bytes32[] itemHashes; } bytes32 constant ZERO_LEAF_HASH = keccak256(""); library PriorityTree { using PriorityTree for Tree; using DynamicIncrementalMerkle for DynamicIncrementalMerkle.Bytes32PushTree; struct Tree { uint256 startIndex; // priority tree started accepting priority ops from this index uint256 unprocessedIndex; // relative to `startIndex` mapping(bytes32 => bool) historicalRoots; DynamicIncrementalMerkle.Bytes32PushTree tree; } /// @notice Returns zero if and only if no operations were processed from the tree /// @return Index of the oldest priority operation that wasn't processed yet function getFirstUnprocessedPriorityTx(Tree storage _tree) internal view returns (uint256) { return _tree.startIndex + _tree.unprocessedIndex; } /// @return The total number of priority operations that were added to the priority queue, including all processed ones function getTotalPriorityTxs(Tree storage _tree) internal view returns (uint256) { return _tree.startIndex + _tree.tree._nextLeafIndex; } /// @return The total number of unprocessed priority operations in a priority queue function getSize(Tree storage _tree) internal view returns (uint256) { return _tree.tree._nextLeafIndex - _tree.unprocessedIndex; } /// @notice Add the priority operation to the end of the priority queue function push(Tree storage _tree, bytes32 _hash) internal { (, bytes32 newRoot) = _tree.tree.push(_hash); _tree.historicalRoots[newRoot] = true; } /// @notice Set up the tree function setup(Tree storage _tree, uint256 _startIndex) internal { bytes32 initialRoot = _tree.tree.setup(ZERO_LEAF_HASH); _tree.historicalRoots[initialRoot] = true; _tree.startIndex = _startIndex; } /// @return Returns the tree root. function getRoot(Tree storage _tree) internal view returns (bytes32) { return _tree.tree.root(); } /// @param _root The root to check. /// @return Returns true if the root is a historical root. function isHistoricalRoot(Tree storage _tree, bytes32 _root) internal view returns (bool) { return _tree.historicalRoots[_root]; } /// @notice Process the priority operations of a batch. /// @dev Note, that the function below only checks that a certain segment of items is present in the tree. /// It does not check that e.g. there are no zero items inside the provided `itemHashes`, so in theory proofs /// that include non-existing priority operations could be created. This function relies on the fact /// that the `itemHashes` of `_priorityOpsData` are hashes of valid priority transactions. /// This fact is ensured by the fact the rolling hash of those is sent to the Executor by the bootloader /// and so assuming that zero knowledge proofs are correct, so is the structure of the `itemHashes`. function processBatch(Tree storage _tree, PriorityOpsBatchInfo memory _priorityOpsData) internal { if (_priorityOpsData.itemHashes.length > 0) { bytes32 expectedRoot = Merkle.calculateRootPaths( _priorityOpsData.leftPath, _priorityOpsData.rightPath, _tree.unprocessedIndex, _priorityOpsData.itemHashes ); if (!_tree.historicalRoots[expectedRoot]) { revert NotHistoricalRoot(); } _tree.unprocessedIndex += _priorityOpsData.itemHashes.length; } } /// @notice Allows to skip a certain number of operations. /// @param _lastUnprocessed The new expected id of the unprocessed transaction. /// @dev It is used when the corresponding transactions have been processed by priority queue. function skipUntil(Tree storage _tree, uint256 _lastUnprocessed) internal { if (_tree.startIndex > _lastUnprocessed) { // Nothing to do, return return; } uint256 newUnprocessedIndex = _lastUnprocessed - _tree.startIndex; if (newUnprocessedIndex <= _tree.unprocessedIndex) { // These transactions were already processed, skip. return; } _tree.unprocessedIndex = newUnprocessedIndex; } /// @notice Initialize a chain from a commitment. function initFromCommitment(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal { uint256 height = _commitment.sides.length; // Height, including the root node. if (height == 0) { revert InvalidCommitment(); } _tree.startIndex = _commitment.startIndex; _tree.unprocessedIndex = _commitment.unprocessedIndex; _tree.tree._nextLeafIndex = _commitment.nextLeafIndex; _tree.tree._sides = _commitment.sides; bytes32 zero = ZERO_LEAF_HASH; _tree.tree._zeros = new bytes32[](height); for (uint256 i; i < height; ++i) { _tree.tree._zeros[i] = zero; zero = Merkle.efficientHash(zero, zero); } _tree.historicalRoots[_tree.tree.root()] = true; } /// @notice Reinitialize the tree from a commitment on L1. function l1Reinit(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal { if (_tree.startIndex != _commitment.startIndex) { revert InvalidStartIndex(_tree.startIndex, _commitment.startIndex); } if (_tree.unprocessedIndex > _commitment.unprocessedIndex) { revert InvalidUnprocessedIndex(_tree.unprocessedIndex, _commitment.unprocessedIndex); } if (_tree.tree._nextLeafIndex < _commitment.nextLeafIndex) { revert InvalidNextLeafIndex(_tree.tree._nextLeafIndex, _commitment.nextLeafIndex); } _tree.unprocessedIndex = _commitment.unprocessedIndex; } /// @notice Reinitialize the tree from a commitment on GW. function checkGWReinit(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal view { if (_tree.startIndex != _commitment.startIndex) { revert InvalidStartIndex(_tree.startIndex, _commitment.startIndex); } if (_tree.unprocessedIndex > _commitment.unprocessedIndex) { revert InvalidUnprocessedIndex(_tree.unprocessedIndex, _commitment.unprocessedIndex); } if (_tree.tree._nextLeafIndex > _commitment.nextLeafIndex) { revert InvalidNextLeafIndex(_tree.tree._nextLeafIndex, _commitment.nextLeafIndex); } } /// @notice Returns the commitment to the priority tree. function getCommitment(Tree storage _tree) internal view returns (PriorityTreeCommitment memory commitment) { commitment.nextLeafIndex = _tree.tree._nextLeafIndex; commitment.startIndex = _tree.startIndex; commitment.unprocessedIndex = _tree.unprocessedIndex; commitment.sides = _tree.tree._sides; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @dev Enum used to determine the source of pubdata. At first we will support calldata and blobs but this can be extended. enum PubdataSource { Calldata, Blob } struct L1DAValidatorOutput { /// @dev The hash of the uncompressed state diff. bytes32 stateDiffHash; /// @dev The hashes of the blobs on L1. The array is dynamic to account for forward compatibility. /// The length of it must be equal to `maxBlobsSupported`. bytes32[] blobsLinearHashes; /// @dev The commitments to the blobs on L1. The array is dynamic to account for forward compatibility. /// Its length must be equal to the length of blobsLinearHashes. /// @dev If the system supports more blobs than returned, the rest of the array should be filled with zeros. bytes32[] blobsOpeningCommitments; } interface IL1DAValidator { /// @notice The function that checks the data availability for the given batch input. /// @param _chainId The chain id of the chain that is being committed. /// @param _batchNumber The batch number for which the data availability is being checked. /// @param _l2DAValidatorOutputHash The hash of that was returned by the l2DAValidator. /// @param _operatorDAInput The DA input by the operator provided on L1. /// @param _maxBlobsSupported The maximal number of blobs supported by the chain. /// We provide this value for future compatibility. /// This is needed because the corresponding `blobsLinearHashes`/`blobsOpeningCommitments` /// in the `L1DAValidatorOutput` struct will have to have this length as it is required /// to be static by the circuits. function checkDA( uint256 _chainId, uint256 _batchNumber, bytes32 _l2DAValidatorOutputHash, bytes calldata _operatorDAInput, uint256 _maxBlobsSupported ) external returns (L1DAValidatorOutput memory output); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; // 0x5ecf2d7a error AccessToFallbackDenied(address target, address invoker); // 0x3995f750 error AccessToFunctionDenied(address target, bytes4 selector, address invoker); // 0x6c167909 error OnlySelfAllowed(); // 0x52e22c98 error RestrictionWasNotPresent(address restriction); // 0xf126e113 error RestrictionWasAlreadyPresent(address restriction); // 0x3331e9c0 error CallNotAllowed(bytes call); // 0xf6fd7071 error RemovingPermanentRestriction(); // 0xfcb9b2e1 error UnallowedImplementation(bytes32 implementationHash); // 0x0dfb42bf error AddressAlreadySet(address addr); // 0x86bb51b8 error AddressHasNoCode(address); // 0x1f73225f error AddressMismatch(address expected, address supplied); // 0x5e85ae73 error AmountMustBeGreaterThanZero(); // 0xfde974f4 error AssetHandlerDoesNotExist(bytes32 assetId); // 0x1294e9e1 error AssetIdMismatch(bytes32 expected, bytes32 supplied); // 0xfe919e28 error AssetIdAlreadyRegistered(); // 0x0bfcef28 error AlreadyWhitelisted(address); // 0x04a0b7e9 error AssetIdNotSupported(bytes32 assetId); // 0x6ef9a972 error BaseTokenGasPriceDenominatorNotSet(); // 0x55ad3fd3 error BatchHashMismatch(bytes32 expected, bytes32 actual); // 0x2078a6a0 error BatchNotExecuted(uint256 batchNumber); // 0xbd4455ff error BatchNumberMismatch(uint256 expectedBatchNumber, uint256 providedBatchNumber); // 0x6cf12312 error BridgeHubAlreadyRegistered(); // 0xdb538614 error BridgeMintNotImplemented(); // 0xe85392f9 error CanOnlyProcessOneBatch(); // 0x00c6ead2 error CantExecuteUnprovenBatches(); // 0xe18cb383 error CantRevertExecutedBatch(); // 0x24591d89 error ChainIdAlreadyExists(); // 0x717a1656 error ChainIdCantBeCurrentChain(); // 0xa179f8c9 error ChainIdMismatch(); // 0x23f3c357 error ChainIdNotRegistered(uint256 chainId); // 0x8f620a06 error ChainIdTooBig(); // 0xf7a01e4d error DelegateCallFailed(bytes returnData); // 0x0a8ed92c error DenominatorIsZero(); // 0xb4f54111 error DeployFailed(); // 0x138ee1a3 error DeployingBridgedTokenForNativeToken(); // 0xc7c9660f error DepositDoesNotExist(); // 0xad2fa98e error DepositExists(); // 0x0e7ee319 error DiamondAlreadyFrozen(); // 0xa7151b9a error DiamondNotFrozen(); // 0x7138356f error EmptyAddress(); // 0x2d4d012f error EmptyAssetId(); // 0x1c25715b error EmptyBytes32(); // 0x95b66fe9 error EmptyDeposit(); // 0x627e0872 error ETHDepositNotSupported(); // 0xac4a3f98 error FacetExists(bytes4 selector, address); // 0xc91cf3b1 error GasPerPubdataMismatch(); // 0x6d4a7df8 error GenesisBatchCommitmentZero(); // 0x7940c83f error GenesisBatchHashZero(); // 0xb4fc6835 error GenesisIndexStorageZero(); // 0x3a1a8589 error GenesisUpgradeZero(); // 0xd356e6ba error HashedLogIsDefault(); // 0x0b08d5be error HashMismatch(bytes32 expected, bytes32 actual); // 0x601b6882 error ZKChainLimitReached(); // 0xdd381a4c error IncorrectBridgeHubAddress(address bridgehub); // 0x826fb11e error InsufficientChainBalance(); // 0xcbd9d2e0 error InvalidCaller(address); // 0x4fbe5dba error InvalidDelay(); // 0xc1780bd6 error InvalidLogSender(address sender, uint256 logKey); // 0xd8e9405c error InvalidNumberOfBlobs(uint256 expected, uint256 numCommitments, uint256 numHashes); // 0x09bde339 error InvalidProof(); // 0x5428eae7 error InvalidProtocolVersion(); // 0x6f1cf752 error InvalidPubdataPricingMode(); // 0x12ba286f error InvalidSelector(bytes4 func); // 0x0214acb6 error InvalidUpgradeTxn(UpgradeTxVerifyParam); // 0xfb5c22e6 error L2TimestampTooBig(); // 0x97e1359e error L2WithdrawalMessageWrongLength(uint256 messageLen); // 0xe37d2c02 error LengthIsNotDivisibleBy32(uint256 length); // 0x1b6825bb error LogAlreadyProcessed(uint8); // 0xcea34703 error MalformedBytecode(BytecodeError); // 0x9bb54c35 error MerkleIndexOutOfBounds(); // 0x8e23ac1a error MerklePathEmpty(); // 0x1c500385 error MerklePathOutOfBounds(); // 0x3312a450 error MigrationPaused(); // 0xfa44b527 error MissingSystemLogs(uint256 expected, uint256 actual); // 0x4a094431 error MsgValueMismatch(uint256 expectedMsgValue, uint256 providedMsgValue); // 0xb385a3da error MsgValueTooLow(uint256 required, uint256 provided); // 0x79cc2d22 error NoCallsProvided(); // 0xa6fef710 error NoFunctionsForDiamondCut(); // 0xcab098d8 error NoFundsTransferred(); // 0xc21b1ab7 error NonEmptyCalldata(); // 0x536ec84b error NonEmptyMsgValue(); // 0xd018e08e error NonIncreasingTimestamp(); // 0x0105f9c0 error NonSequentialBatch(); // 0x0ac76f01 error NonSequentialVersion(); // 0xdd7e3621 error NotInitializedReentrancyGuard(); // 0xdf17e316 error NotWhitelisted(address); // 0xf3ed9dfa error OnlyEraSupported(); // 0x1a21feed error OperationExists(); // 0xeda2fbb1 error OperationMustBePending(); // 0xe1c1ff37 error OperationMustBeReady(); // 0xb926450e error OriginChainIdNotFound(); // 0x9b48e060 error PreviousOperationNotExecuted(); // 0xd5a99014 error PriorityOperationsRollingHashMismatch(); // 0x1a4d284a error PriorityTxPubdataExceedsMaxPubDataPerBatch(); // 0xa461f651 error ProtocolIdMismatch(uint256 expectedProtocolVersion, uint256 providedProtocolId); // 0x64f94ec2 error ProtocolIdNotGreater(); // 0x959f26fb error PubdataGreaterThanLimit(uint256 limit, uint256 length); // 0x63c36549 error QueueIsEmpty(); // 0xab143c06 error Reentrancy(); // 0x667d17de error RemoveFunctionFacetAddressNotZero(address facet); // 0xa2d4b16c error RemoveFunctionFacetAddressZero(); // 0x3580370c error ReplaceFunctionFacetAddressZero(); // 0x9a67c1cb error RevertedBatchNotAfterNewLastBatch(); // 0xd3b6535b error SelectorsMustAllHaveSameFreezability(); // 0xd7a6b5e6 error SharedBridgeValueNotSet(SharedBridgeKey); // 0x856d5b77 error SharedBridgeNotSet(); // 0xdf3a8fdd error SlotOccupied(); // 0xec273439 error CTMAlreadyRegistered(); // 0xc630ef3c error CTMNotRegistered(); // 0xae43b424 error SystemLogsSizeTooBig(); // 0x08753982 error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp); // 0x2d50c33b error TimestampError(); // 0x06439c6b error TokenNotSupported(address token); // 0x23830e28 error TokensWithFeesNotSupported(); // 0x76da24b9 error TooManyFactoryDeps(); // 0xf0b4e88f error TooMuchGas(); // 0x00c5a6a9 error TransactionNotAllowed(); // 0x4c991078 error TxHashMismatch(); // 0x2e311df8 error TxnBodyGasLimitNotEnoughGas(); // 0x8e4a23d6 error Unauthorized(address caller); // 0xe52478c7 error UndefinedDiamondCutAction(); // 0x6aa39880 error UnexpectedSystemLog(uint256 logKey); // 0xf093c2e5 error UpgradeBatchNumberIsNotZero(); // 0x084a1449 error UnsupportedEncodingVersion(); // 0x47b3b145 error ValidateTxnNotEnoughGas(); // 0x626ade30 error ValueMismatch(uint256 expected, uint256 actual); // 0xe1022469 error VerifiedBatchesExceedsCommittedBatches(); // 0xae899454 error WithdrawalAlreadyFinalized(); // 0x750b219c error WithdrawFailed(); // 0x15e8e429 error WrongMagicValue(uint256 expectedMagicValue, uint256 providedMagicValue); // 0xd92e233d error ZeroAddress(); // 0xc84885d4 error ZeroChainId(); // 0x99d8fec9 error EmptyData(); // 0xf3dd1b9c error UnsupportedCommitBatchEncoding(uint8 version); // 0xf338f830 error UnsupportedProofBatchEncoding(uint8 version); // 0x14d2ed8a error UnsupportedExecuteBatchEncoding(uint8 version); // 0xd7d93e1f error IncorrectBatchBounds( uint256 processFromExpected, uint256 processToExpected, uint256 processFromProvided, uint256 processToProvided ); // 0x64107968 error AssetHandlerNotRegistered(bytes32 assetId); // 0x64846fe4 error NotARestriction(address addr); // 0xfa5cd00f error NotAllowed(address addr); // 0xccdd18d2 error BytecodeAlreadyPublished(bytes32 bytecodeHash); // 0x25d8333c error CallerNotTimerAdmin(); // 0x907f8e51 error DeadlineNotYetPassed(); // 0x6eef58d1 error NewDeadlineNotGreaterThanCurrent(); // 0x8b7e144a error NewDeadlineExceedsMaxDeadline(); // 0x2a5989a0 error AlreadyPermanentRollup(); // 0x92daded2 error InvalidDAForPermanentRollup(); // 0x7a4902ad error TimerAlreadyStarted(); // 0x09aa9830 error MerklePathLengthMismatch(uint256 pathLength, uint256 expectedLength); // 0xc33e6128 error MerkleNothingToProve(); // 0xafbb7a4e error MerkleIndexOrHeightMismatch(); // 0x1b582fcf error MerkleWrongIndex(uint256 index, uint256 maxNodeNumber); // 0x485cfcaa error MerkleWrongLength(uint256 newLeavesLength, uint256 leafNumber); // 0xce63ce17 error NoCTMForAssetId(bytes32 assetId); // 0x02181a13 error SettlementLayersMustSettleOnL1(); // 0x1850b46b error TokenNotLegacy(); // 0x1929b7de error IncorrectTokenAddressFromNTV(bytes32 assetId, address tokenAddress); // 0x48c5fa28 error InvalidProofLengthForFinalNode(); // 0xfade089a error LegacyEncodingUsedForNonL1Token(); // 0xa51fa558 error TokenIsLegacy(); // 0x29963361 error LegacyBridgeUsesNonNativeToken(); // 0x11832de8 error AssetRouterAllowanceNotZero(); // 0xaa5f6180 error BurningNativeWETHNotSupported(); // 0xb20b58ce error NoLegacySharedBridge(); // 0x8e3ce3cb error TooHighDeploymentNonce(); // 0x78d2ed02 error ChainAlreadyLive(); // 0x4e98b356 error MigrationsNotPaused(); // 0xf20c5c2a error WrappedBaseTokenAlreadyRegistered(); // 0xde4c0b96 error InvalidNTVBurnData(); // 0xbe7193d4 error InvalidSystemLogsLength(); // 0x8efef97a error LegacyBridgeNotSet(); // 0x767eed08 error LegacyMethodForNonL1Token(); // 0xc352bb73 error UnknownVerifierType(); // 0x456f8f7a error EmptyProofLength(); 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 }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.21; // 0x2e89f517 error L1DAValidatorAddressIsZero(); // 0x944bc075 error L2DAValidatorAddressIsZero(); // 0xca1c3cbc error AlreadyMigrated(); // 0xf05c64c6 error NotChainAdmin(address prevMsgSender, address admin); // 0xc59d372c error ProtocolVersionNotUpToDate(uint256 currentProtocolVersion, uint256 protocolVersion); // 0xedae13f3 error ExecutedIsNotConsistentWithVerified(uint256 batchesExecuted, uint256 batchesVerified); // 0x712d02d2 error VerifiedIsNotConsistentWithCommitted(uint256 batchesVerified, uint256 batchesCommitted); // 0xfb1a3b59 error InvalidNumberOfBatchHashes(uint256 batchHashesLength, uint256 expected); // 0xa840274f error PriorityQueueNotReady(); // 0x79274f04 error UnsupportedProofMetadataVersion(uint256 metadataVersion); // 0xa969e486 error LocalRootIsZero(); // 0xbdaf7d42 error LocalRootMustBeZero(); // 0xd0266e26 error NotSettlementLayer(); // 0x32ddf9a2 error NotHyperchain(); // 0x2237c426 error MismatchL2DAValidator(); // 0x2c01a4af error MismatchNumberOfLayer1Txs(uint256 numberOfLayer1Txs, uint256 expectedLength); // 0xfbd630b8 error InvalidBatchesDataLength(uint256 batchesDataLength, uint256 priorityOpsDataLength); // 0x55008233 error PriorityOpsDataLeftPathLengthIsNotZero(); // 0x8be936a9 error PriorityOpsDataRightPathLengthIsNotZero(); // 0x99d44739 error PriorityOpsDataItemHashesLengthIsNotZero(); // 0x885ae069 error OperatorDAInputTooSmall(uint256 operatorDAInputLength, uint256 minAllowedLength); // 0xbeb96791 error InvalidNumberOfBlobs(uint256 blobsProvided, uint256 maxBlobsSupported); // 0xd2531c15 error InvalidL2DAOutputHash(bytes32 l2DAValidatorOutputHash); // 0x04e05fd1 error OnlyOneBlobWithCalldataAllowed(); // 0x2dc9747d error PubdataInputTooSmall(uint256 pubdataInputLength, uint256 totalBlobsCommitmentSize); // 0x9044dff9 error PubdataLengthTooBig(uint256 pubdataLength, uint256 totalBlobSizeBytes); // 0x5513177c error InvalidPubdataHash(bytes32 fullPubdataHash, bytes32 providedPubdataHash); // 0x5717f940 error InvalidPubdataSource(uint8 pubdataSource); // 0x125d99b0 error BlobHashBlobCommitmentMismatchValue(); // 0x7fbff2dd error L1DAValidatorInvalidSender(address msgSender); // 0xc06789fa error InvalidCommitment(); // 0xc866ff2c error InitialForceDeploymentMismatch(bytes32 forceDeploymentHash, bytes32 initialForceDeploymentHash); // 0xb325f767 error AdminZero(); // 0x681150be error OutdatedProtocolVersion(uint256 protocolVersion, uint256 currentProtocolVersion); // 0x87470e36 error NotL1(uint256 blockChainId); // 0x90f67ecf error InvalidStartIndex(uint256 treeStartIndex, uint256 commitmentStartIndex); // 0x0f67bc0a error InvalidUnprocessedIndex(uint256 treeUnprocessedIndex, uint256 commitmentUnprocessedIndex); // 0x30043900 error InvalidNextLeafIndex(uint256 treeNextLeafIndex, uint256 commitmentNextLeafIndex); // 0xf9ba09d6 error NotAllBatchesExecuted(); // 0x9b53b101 error NotHistoricalRoot(); // 0xc02d3ee3 error ContractNotDeployed(); // 0xd7b2559b error NotMigrated(); // 0x52595598 error ValL1DAWrongInputLength(uint256 inputLength, uint256 expectedLength);
// 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); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IVerifier, VerifierParams} from "../chain-interfaces/IVerifier.sol"; // import {IChainTypeManager} from "../IChainTypeManager.sol"; import {PriorityQueue} from "../../state-transition/libraries/PriorityQueue.sol"; import {PriorityTree} from "../../state-transition/libraries/PriorityTree.sol"; /// @notice Indicates whether an upgrade is initiated and if yes what type /// @param None Upgrade is NOT initiated /// @param Transparent Fully transparent upgrade is initiated, upgrade data is publicly known /// @param Shadow Shadow upgrade is initiated, upgrade data is hidden enum UpgradeState { None, Transparent, Shadow } /// @dev Logically separated part of the storage structure, which is responsible for everything related to proxy /// upgrades and diamond cuts /// @param proposedUpgradeHash The hash of the current upgrade proposal, zero if there is no active proposal /// @param state Indicates whether an upgrade is initiated and if yes what type /// @param securityCouncil Address which has the permission to approve instant upgrades (expected to be a Gnosis /// multisig) /// @param approvedBySecurityCouncil Indicates whether the security council has approved the upgrade /// @param proposedUpgradeTimestamp The timestamp when the upgrade was proposed, zero if there are no active proposals /// @param currentProposalId The serial number of proposed upgrades, increments when proposing a new one struct UpgradeStorage { bytes32 proposedUpgradeHash; UpgradeState state; address securityCouncil; bool approvedBySecurityCouncil; uint40 proposedUpgradeTimestamp; uint40 currentProposalId; } /// @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 } /// @notice The fee params for L1->L2 transactions for the network. /// @param pubdataPricingMode How the users will charged for pubdata in L1->L2 transactions. /// @param batchOverheadL1Gas The amount of L1 gas required to process the batch (except for the calldata). /// @param maxPubdataPerBatch The maximal number of pubdata that can be emitted per batch. /// @param priorityTxMaxPubdata The maximal amount of pubdata a priority transaction is allowed to publish. /// It can be slightly less than maxPubdataPerBatch in order to have some margin for the bootloader execution. /// @param minimalL2GasPrice The minimal L2 gas price to be used by L1->L2 transactions. It should represent /// the price that a single unit of compute costs. struct FeeParams { PubdataPricingMode pubdataPricingMode; uint32 batchOverheadL1Gas; uint32 maxPubdataPerBatch; uint32 maxL2GasPerBatch; uint32 priorityTxMaxPubdata; uint64 minimalL2GasPrice; } /// @dev storing all storage variables for ZK chain diamond facets /// NOTE: It is used in a proxy, so it is possible to add new variables to the end /// but NOT to modify already existing variables or change their order. /// NOTE: variables prefixed with '__DEPRECATED_' are deprecated and shouldn't be used. /// Their presence is maintained for compatibility and to prevent storage collision. // solhint-disable-next-line gas-struct-packing struct ZKChainStorage { /// @dev Storage of variables needed for deprecated diamond cut facet uint256[7] __DEPRECATED_diamondCutStorage; /// @notice Address which will exercise critical changes to the Diamond Proxy (upgrades, freezing & unfreezing). Replaced by CTM address __DEPRECATED_governor; /// @notice Address that the governor proposed as one that will replace it address __DEPRECATED_pendingGovernor; /// @notice List of permitted validators mapping(address validatorAddress => bool isValidator) validators; /// @dev Verifier contract. Used to verify aggregated proof for batches IVerifier verifier; /// @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; /// @dev Stored hashed StoredBatch for batch number mapping(uint256 batchNumber => bytes32 batchHash) storedBatchHashes; /// @dev Stored root hashes of L2 -> L1 logs mapping(uint256 batchNumber => bytes32 l2LogsRootHash) l2LogsRootHashes; /// @dev Container that stores transactions requested from L1 PriorityQueue.Queue priorityQueue; /// @dev The smart contract that manages the list with permission to call contract functions address __DEPRECATED_allowList; VerifierParams __DEPRECATED_verifierParams; /// @notice Bytecode hash of bootloader program. /// @dev Used as an input to zkp-circuit. bytes32 l2BootloaderBytecodeHash; /// @notice Bytecode hash of default account (bytecode for EOA). /// @dev Used as an input to zkp-circuit. bytes32 l2DefaultAccountBytecodeHash; /// @dev Indicates that the porter may be touched on L2 transactions. /// @dev Used as an input to zkp-circuit. bool zkPorterIsAvailable; /// @dev The maximum number of the L2 gas that a user can request for L1 -> L2 transactions /// @dev This is the maximum number of L2 gas that is available for the "body" of the transaction, i.e. /// without overhead for proving the batch. uint256 priorityTxMaxGasLimit; /// @dev Storage of variables needed for upgrade facet UpgradeStorage __DEPRECATED_upgrades; /// @dev A mapping L2 batch number => message number => flag. /// @dev The L2 -> L1 log is sent for every withdrawal, so this mapping is serving as /// a flag to indicate that the message was already processed. /// @dev Used to indicate that eth withdrawal was already processed mapping(uint256 l2BatchNumber => mapping(uint256 l2ToL1MessageNumber => bool isFinalized)) isEthWithdrawalFinalized; /// @dev The most recent withdrawal time and amount reset uint256 __DEPRECATED_lastWithdrawalLimitReset; /// @dev The accumulated withdrawn amount during the withdrawal limit window uint256 __DEPRECATED_withdrawnAmountInWindow; /// @dev A mapping user address => the total deposited amount by the user mapping(address => uint256) __DEPRECATED_totalDepositedAmountPerUser; /// @dev Stores the protocol version. Note, that the protocol version may not only encompass changes to the /// smart contracts, but also to the node behavior. uint256 protocolVersion; /// @dev Hash of the system contract upgrade transaction. If 0, then no upgrade transaction needs to be done. bytes32 l2SystemContractsUpgradeTxHash; /// @dev Batch number where the upgrade transaction has happened. If 0, then no upgrade transaction has happened /// yet. uint256 l2SystemContractsUpgradeBatchNumber; /// @dev Address which will exercise non-critical changes to the Diamond Proxy (changing validator set & unfreezing) address admin; /// @notice Address that the admin proposed as one that will replace admin role address pendingAdmin; /// @dev Fee params used to derive gasPrice for the L1->L2 transactions. For L2 transactions, /// the bootloader gives enough freedom to the operator. /// @dev The value is only for the L1 deployment of the ZK Chain, since payment for all the priority transactions is /// charged at that level. FeeParams feeParams; /// @dev Address of the blob versioned hash getter smart contract used for EIP-4844 versioned hashes. /// @dev Used only for testing. address blobVersionedHashRetriever; /// @dev The chainId of the chain uint256 chainId; /// @dev The address of the bridgehub address bridgehub; /// @dev The address of the ChainTypeManager address chainTypeManager; /// @dev The address of the baseToken contract. Eth is address(1) address __DEPRECATED_baseToken; /// @dev The address of the baseTokenbridge. Eth also uses the shared bridge address __DEPRECATED_baseTokenBridge; /// @notice gasPriceMultiplier for each baseToken, so that each L1->L2 transaction pays for its transaction on the destination /// we multiply by the nominator, and divide by the denominator uint128 baseTokenGasPriceMultiplierNominator; uint128 baseTokenGasPriceMultiplierDenominator; /// @dev The optional address of the contract that has to be used for transaction filtering/whitelisting address transactionFilterer; /// @dev The address of the l1DAValidator contract. /// This contract is responsible for the verification of the correctness of the DA on L1. address l1DAValidator; /// @dev The address of the contract on L2 that is responsible for the data availability verification. /// This contract sends `l2DAValidatorOutputHash` to L1 via L2->L1 system log and it will routed to the `l1DAValidator` contract. address l2DAValidator; /// @dev the Asset Id of the baseToken bytes32 baseTokenAssetId; /// @dev If this ZKchain settles on this chain, then this is zero. Otherwise it is the address of the ZKchain that is a /// settlement layer for this ZKchain. (think about it as a 'forwarding' address for the chain that migrated away). address settlementLayer; /// @dev Priority tree, the new data structure for priority queue PriorityTree.Tree priorityTree; /// @dev Whether the chain is a permanent rollup. Note, that it only enforces the DA validator pair, but /// it does not enforce any other parameters, e.g. `pubdataPricingMode` bool isPermanentRollup; /// @notice Bytecode hash of evm emulator. /// @dev Used as an input to zkp-circuit. bytes32 l2EvmEmulatorBytecodeHash; }
// 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 {SlotOccupied, NotInitializedReentrancyGuard, Reentrancy} 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) } } }
// 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; /// @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 expirationTimestamp The timestamp by which the priority operation must be processed by the operator. /// @param request The external calldata request for the priority operation. struct WritePriorityOpParams { uint256 txId; uint256 l2GasPrice; uint64 expirationTimestamp; 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 contractAddressL2 The address of the contract on L2 to call. /// @param valueToMint 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; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @title L1 Asset Handler contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Used for any asset handler and called by the L1AssetRouter interface IL1AssetHandler { /// @param _chainId the chainId that the message will be sent to /// @param _assetId the assetId of the asset being bridged /// @param _depositSender the address of the entity that initiated the deposit. /// @param _data the actual data specified for the function function bridgeRecoverFailedTransfer( uint256 _chainId, bytes32 _assetId, address _depositSender, bytes calldata _data ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {L2TransactionRequestTwoBridgesInner, IBridgehub} from "./IBridgehub.sol"; import {IAssetRouterBase} from "../bridge/asset-router/IAssetRouterBase.sol"; import {IL1AssetDeploymentTracker} from "../bridge/interfaces/IL1AssetDeploymentTracker.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] interface ICTMDeploymentTracker is IL1AssetDeploymentTracker { function bridgehubDeposit( uint256 _chainId, address _originalCaller, uint256 _l2Value, bytes calldata _data ) external payable returns (L2TransactionRequestTwoBridgesInner memory request); function BRIDGE_HUB() external view returns (IBridgehub); function L1_ASSET_ROUTER() external view returns (IAssetRouterBase); function registerCTMAssetOnL1(address _ctmAddress) external; function calculateAssetId(address _l1CTM) external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @title Asset Handler contract interface /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice Used for any asset handler and called by the AssetRouter interface IAssetHandler { /// @dev Emitted when a token is minted event BridgeMint(uint256 indexed chainId, bytes32 indexed assetId, address receiver, uint256 amount); /// @dev Emitted when a token is burned event BridgeBurn( uint256 indexed chainId, bytes32 indexed assetId, address indexed sender, address receiver, uint256 amount ); /// @param _chainId the chainId that the message is from /// @param _assetId the assetId of the asset being bridged /// @param _data the actual data specified for the function /// @dev Note, that while payable, this function will only receive base token on L2 chains, /// while L1 the provided msg.value is always 0. However, this may change in the future, /// so if your AssetHandler implementation relies on it, it is better to explicitly check it. function bridgeMint(uint256 _chainId, bytes32 _assetId, bytes calldata _data) external payable; /// @notice Burns bridged tokens and returns the calldata for L2 <-> L1 message. /// @dev In case of native token vault _data is the tuple of _depositAmount and _l2Receiver. /// @param _chainId the chainId that the message will be sent to /// @param _msgValue the msg.value of the L2 transaction. For now it is always 0. /// @param _assetId the assetId of the asset being bridged /// @param _originalCaller the original caller of the /// @param _data the actual data specified for the function /// @return _bridgeMintData The calldata used by counterpart asset handler to unlock tokens for recipient. function bridgeBurn( uint256 _chainId, uint256 _msgValue, bytes32 _assetId, address _originalCaller, bytes calldata _data ) external payable returns (bytes memory _bridgeMintData); }
// 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 {SafeCast} from "@openzeppelin/contracts-v4/utils/math/SafeCast.sol"; import {UncheckedMath} from "../../common/libraries/UncheckedMath.sol"; import {NoFunctionsForDiamondCut, UndefinedDiamondCutAction, AddressHasNoCode, FacetExists, RemoveFunctionFacetAddressZero, SelectorsMustAllHaveSameFreezability, NonEmptyCalldata, ReplaceFunctionFacetAddressZero, RemoveFunctionFacetAddressNotZero, DelegateCallFailed} from "../../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] /// @notice The helper library for managing the EIP-2535 diamond proxy. library Diamond { using UncheckedMath for uint256; using SafeCast for uint256; /// @dev Magic value that should be returned by diamond cut initialize contracts. /// @dev Used to distinguish calls to contracts that were supposed to be used as diamond initializer from other contracts. bytes32 internal constant DIAMOND_INIT_SUCCESS_RETURN_VALUE = 0x33774e659306e47509050e97cb651e731180a42d458212294d30751925c551a2; // keccak256("diamond.zksync.init") - 1 /// @dev Storage position of `DiamondStorage` structure. bytes32 private constant DIAMOND_STORAGE_POSITION = 0xc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131b; // keccak256("diamond.standard.diamond.storage") - 1; event DiamondCut(FacetCut[] facetCuts, address initAddress, bytes initCalldata); /// @dev Utility struct that contains associated facet & meta information of selector /// @param facetAddress address of the facet which is connected with selector /// @param selectorPosition index in `FacetToSelectors.selectors` array, where is selector stored /// @param isFreezable denotes whether the selector can be frozen. struct SelectorToFacet { address facetAddress; uint16 selectorPosition; bool isFreezable; } /// @dev Utility struct that contains associated selectors & meta information of facet /// @param selectors list of all selectors that belong to the facet /// @param facetPosition index in `DiamondStorage.facets` array, where is facet stored struct FacetToSelectors { bytes4[] selectors; uint16 facetPosition; } /// @notice The structure that holds all diamond proxy associated parameters /// @dev According to the EIP-2535 should be stored on a special storage key - `DIAMOND_STORAGE_POSITION` /// @param selectorToFacet A mapping from the selector to the facet address and its meta information /// @param facetToSelectors A mapping from facet address to its selectors with meta information /// @param facets The array of all unique facet addresses that belong to the diamond proxy /// @param isFrozen Denotes whether the diamond proxy is frozen and all freezable facets are not accessible struct DiamondStorage { mapping(bytes4 selector => SelectorToFacet selectorInfo) selectorToFacet; mapping(address facetAddress => FacetToSelectors facetInfo) facetToSelectors; address[] facets; bool isFrozen; } /// @dev Parameters for diamond changes that touch one of the facets /// @param facet The address of facet that's affected by the cut /// @param action The action that is made on the facet /// @param isFreezable Denotes whether the facet & all their selectors can be frozen /// @param selectors An array of unique selectors that belongs to the facet address // solhint-disable-next-line gas-struct-packing struct FacetCut { address facet; Action action; bool isFreezable; bytes4[] selectors; } /// @dev Structure of the diamond proxy changes /// @param facetCuts The set of changes (adding/removing/replacement) of implementation contracts /// @param initAddress The address that's delegate called after setting up new facet changes /// @param initCalldata Calldata for the delegate call to `initAddress` struct DiamondCutData { FacetCut[] facetCuts; address initAddress; bytes initCalldata; } /// @dev Type of change over diamond: add/replace/remove facets enum Action { Add, Replace, Remove } /// @return diamondStorage The pointer to the storage where all specific diamond proxy parameters stored function getDiamondStorage() internal pure returns (DiamondStorage storage diamondStorage) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { diamondStorage.slot := position } } /// @dev Add/replace/remove any number of selectors and optionally execute a function with delegatecall /// @param _diamondCut Diamond's facet changes and the parameters to optional initialization delegatecall function diamondCut(DiamondCutData memory _diamondCut) internal { FacetCut[] memory facetCuts = _diamondCut.facetCuts; address initAddress = _diamondCut.initAddress; bytes memory initCalldata = _diamondCut.initCalldata; uint256 facetCutsLength = facetCuts.length; for (uint256 i = 0; i < facetCutsLength; i = i.uncheckedInc()) { Action action = facetCuts[i].action; address facet = facetCuts[i].facet; bool isFacetFreezable = facetCuts[i].isFreezable; bytes4[] memory selectors = facetCuts[i].selectors; if (selectors.length == 0) { revert NoFunctionsForDiamondCut(); } if (action == Action.Add) { _addFunctions(facet, selectors, isFacetFreezable); } else if (action == Action.Replace) { _replaceFunctions(facet, selectors, isFacetFreezable); } else if (action == Action.Remove) { _removeFunctions(facet, selectors); } else { revert UndefinedDiamondCutAction(); } } _initializeDiamondCut(initAddress, initCalldata); emit DiamondCut(facetCuts, initAddress, initCalldata); } /// @dev Add new functions to the diamond proxy /// NOTE: expect but NOT enforce that `_selectors` is NON-EMPTY array function _addFunctions(address _facet, bytes4[] memory _selectors, bool _isFacetFreezable) private { DiamondStorage storage ds = getDiamondStorage(); // Facet with no code cannot be added. // This check also verifies that the facet does not have zero address, since it is the // address with which 0x00000000 selector is associated. if (_facet.code.length == 0) { revert AddressHasNoCode(_facet); } // Add facet to the list of facets if the facet address is new one _saveFacetIfNew(_facet); uint256 selectorsLength = _selectors.length; for (uint256 i = 0; i < selectorsLength; i = i.uncheckedInc()) { bytes4 selector = _selectors[i]; SelectorToFacet memory oldFacet = ds.selectorToFacet[selector]; if (oldFacet.facetAddress != address(0)) { revert FacetExists(selector, oldFacet.facetAddress); } _addOneFunction(_facet, selector, _isFacetFreezable); } } /// @dev Change associated facets to already known function selectors /// NOTE: expect but NOT enforce that `_selectors` is NON-EMPTY array function _replaceFunctions(address _facet, bytes4[] memory _selectors, bool _isFacetFreezable) private { DiamondStorage storage ds = getDiamondStorage(); // Facet with no code cannot be added. // This check also verifies that the facet does not have zero address, since it is the // address with which 0x00000000 selector is associated. if (_facet.code.length == 0) { revert AddressHasNoCode(_facet); } uint256 selectorsLength = _selectors.length; for (uint256 i = 0; i < selectorsLength; i = i.uncheckedInc()) { bytes4 selector = _selectors[i]; SelectorToFacet memory oldFacet = ds.selectorToFacet[selector]; // it is impossible to replace the facet with zero address if (oldFacet.facetAddress == address(0)) { revert ReplaceFunctionFacetAddressZero(); } _removeOneFunction(oldFacet.facetAddress, selector); // Add facet to the list of facets if the facet address is a new one _saveFacetIfNew(_facet); _addOneFunction(_facet, selector, _isFacetFreezable); } } /// @dev Remove association with function and facet /// NOTE: expect but NOT enforce that `_selectors` is NON-EMPTY array function _removeFunctions(address _facet, bytes4[] memory _selectors) private { DiamondStorage storage ds = getDiamondStorage(); // facet address must be zero if (_facet != address(0)) { revert RemoveFunctionFacetAddressNotZero(_facet); } uint256 selectorsLength = _selectors.length; for (uint256 i = 0; i < selectorsLength; i = i.uncheckedInc()) { bytes4 selector = _selectors[i]; SelectorToFacet memory oldFacet = ds.selectorToFacet[selector]; // Can't delete a non-existent facet if (oldFacet.facetAddress == address(0)) { revert RemoveFunctionFacetAddressZero(); } _removeOneFunction(oldFacet.facetAddress, selector); } } /// @dev Add address to the list of known facets if it is not on the list yet /// NOTE: should be called ONLY before adding a new selector associated with the address function _saveFacetIfNew(address _facet) private { DiamondStorage storage ds = getDiamondStorage(); uint256 selectorsLength = ds.facetToSelectors[_facet].selectors.length; // If there are no selectors associated with facet then save facet as new one if (selectorsLength == 0) { ds.facetToSelectors[_facet].facetPosition = ds.facets.length.toUint16(); ds.facets.push(_facet); } } /// @dev Add one function to the already known facet /// NOTE: It is expected but NOT enforced that: /// - `_facet` is NON-ZERO address /// - `_facet` is already stored address in `DiamondStorage.facets` /// - `_selector` is NOT associated by another facet function _addOneFunction(address _facet, bytes4 _selector, bool _isSelectorFreezable) private { DiamondStorage storage ds = getDiamondStorage(); uint16 selectorPosition = (ds.facetToSelectors[_facet].selectors.length).toUint16(); // if selectorPosition is nonzero, it means it is not a new facet // so the freezability of the first selector must be matched to _isSelectorFreezable // so all the selectors in a facet will have the same freezability if (selectorPosition != 0) { bytes4 selector0 = ds.facetToSelectors[_facet].selectors[0]; if (_isSelectorFreezable != ds.selectorToFacet[selector0].isFreezable) { revert SelectorsMustAllHaveSameFreezability(); } } ds.selectorToFacet[_selector] = SelectorToFacet({ facetAddress: _facet, selectorPosition: selectorPosition, isFreezable: _isSelectorFreezable }); ds.facetToSelectors[_facet].selectors.push(_selector); } /// @dev Remove one associated function with facet /// NOTE: It is expected but NOT enforced that `_facet` is NON-ZERO address function _removeOneFunction(address _facet, bytes4 _selector) private { DiamondStorage storage ds = getDiamondStorage(); // Get index of `FacetToSelectors.selectors` of the selector and last element of array uint256 selectorPosition = ds.selectorToFacet[_selector].selectorPosition; uint256 lastSelectorPosition = ds.facetToSelectors[_facet].selectors.length - 1; // If the selector is not at the end of the array then move the last element to the selector position if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetToSelectors[_facet].selectors[lastSelectorPosition]; ds.facetToSelectors[_facet].selectors[selectorPosition] = lastSelector; ds.selectorToFacet[lastSelector].selectorPosition = selectorPosition.toUint16(); } // Remove last element from the selectors array ds.facetToSelectors[_facet].selectors.pop(); // Finally, clean up the association with facet delete ds.selectorToFacet[_selector]; // If there are no selectors for facet then remove the facet from the list of known facets if (lastSelectorPosition == 0) { _removeFacet(_facet); } } /// @dev remove facet from the list of known facets /// NOTE: It is expected but NOT enforced that there are no selectors associated with `_facet` function _removeFacet(address _facet) private { DiamondStorage storage ds = getDiamondStorage(); // Get index of `DiamondStorage.facets` of the facet and last element of array uint256 facetPosition = ds.facetToSelectors[_facet].facetPosition; uint256 lastFacetPosition = ds.facets.length - 1; // If the facet is not at the end of the array then move the last element to the facet position if (facetPosition != lastFacetPosition) { address lastFacet = ds.facets[lastFacetPosition]; ds.facets[facetPosition] = lastFacet; ds.facetToSelectors[lastFacet].facetPosition = facetPosition.toUint16(); } // Remove last element from the facets array ds.facets.pop(); } /// @dev Delegates call to the initialization address with provided calldata /// @dev Used as a final step of diamond cut to execute the logic of the initialization for changed facets function _initializeDiamondCut(address _init, bytes memory _calldata) private { if (_init == address(0)) { // Non-empty calldata for zero address if (_calldata.length != 0) { revert NonEmptyCalldata(); } } else { // Do not check whether `_init` is a contract since later we check that it returns data. (bool success, bytes memory data) = _init.delegatecall(_calldata); if (!success) { // If the returndata is too small, we still want to produce some meaningful error if (data.length < 4) { revert DelegateCallFailed(data); } assembly { revert(add(data, 0x20), mload(data)) } } // Check that called contract returns magic value to make sure that contract logic // supposed to be used as diamond cut initializer. if (data.length != 32) { revert DelegateCallFailed(data); } if (abi.decode(data, (bytes32)) != DIAMOND_INIT_SUCCESS_RETURN_VALUE) { revert DelegateCallFailed(data); } } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Merkle} from "./Merkle.sol"; import {Arrays} from "@openzeppelin/contracts-v4/utils/Arrays.sol"; /** * @dev Library for managing https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures. * * Each tree is a complete binary tree with the ability to sequentially insert leaves, changing them from a zero to a * non-zero value and updating its root. This structure allows inserting commitments (or other entries) that are not * stored, but can be proven to be part of the tree at a later time if the root is kept. See {MerkleProof}. * * A tree is defined by the following parameters: * * * Depth: The number of levels in the tree, it also defines the maximum number of leaves as 2**depth. * * Zero value: The value that represents an empty leaf. Used to avoid regular zero values to be part of the tree. * * Hashing function: A cryptographic hash function used to produce internal nodes. * * This is a fork of OpenZeppelin's [`MerkleTree`](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/9af280dc4b45ee5bda96ba47ff829b407eaab67e/contracts/utils/structs/MerkleTree.sol) * library, with the changes to support dynamic tree growth (doubling the size when full). */ library DynamicIncrementalMerkle { /** * @dev A complete `bytes32` Merkle tree. * * The `sides` and `zero` arrays are set to have a length equal to the depth of the tree during setup. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * NOTE: The `root` and the updates history is not stored within the tree. Consider using a secondary structure to * store a list of historical roots from the values returned from {setup} and {push} (e.g. a mapping, {BitMaps} or * {Checkpoints}). * * WARNING: Updating any of the tree's parameters after the first insertion will result in a corrupted tree. */ struct Bytes32PushTree { uint256 _nextLeafIndex; bytes32[] _sides; bytes32[] _zeros; } /** * @dev Initialize a {Bytes32PushTree} using {Hashes-Keccak256} to hash internal nodes. * The capacity of the tree (i.e. number of leaves) is set to `2**levels`. * * IMPORTANT: The zero value should be carefully chosen since it will be stored in the tree representing * empty leaves. It should be a value that is not expected to be part of the tree. */ function setup(Bytes32PushTree storage self, bytes32 zero) internal returns (bytes32 initialRoot) { self._nextLeafIndex = 0; self._zeros.push(zero); self._sides.push(bytes32(0)); return bytes32(0); } /** * @dev Resets the tree to a blank state. * Calling this function on MerkleTree that was already setup and used will reset it to a blank state. * @param zero The value that represents an empty leaf. * @return initialRoot The initial root of the tree. */ function reset(Bytes32PushTree storage self, bytes32 zero) internal returns (bytes32 initialRoot) { self._nextLeafIndex = 0; uint256 length = self._zeros.length; for (uint256 i = length; 0 < i; --i) { self._zeros.pop(); } length = self._sides.length; for (uint256 i = length; 0 < i; --i) { self._sides.pop(); } self._zeros.push(zero); self._sides.push(bytes32(0)); return bytes32(0); } /** * @dev Insert a new leaf in the tree, and compute the new root. Returns the position of the inserted leaf in the * tree, and the resulting root. * * Hashing the leaf before calling this function is recommended as a protection against * second pre-image attacks. */ function push(Bytes32PushTree storage self, bytes32 leaf) internal returns (uint256 index, bytes32 newRoot) { // Cache read uint256 levels = self._zeros.length - 1; // Get leaf index // solhint-disable-next-line gas-increment-by-one index = self._nextLeafIndex++; // Check if tree is full. if (index == 1 << levels) { bytes32 zero = self._zeros[levels]; bytes32 newZero = Merkle.efficientHash(zero, zero); self._zeros.push(newZero); self._sides.push(bytes32(0)); ++levels; } // Rebuild branch from leaf to root uint256 currentIndex = index; bytes32 currentLevelHash = leaf; bool updatedSides = false; for (uint32 i = 0; i < levels; ++i) { // Reaching the parent node, is currentLevelHash the left child? bool isLeft = currentIndex % 2 == 0; // If so, next time we will come from the right, so we need to save it if (isLeft && !updatedSides) { Arrays.unsafeAccess(self._sides, i).value = currentLevelHash; updatedSides = true; } // Compute the current node hash by using the hash function // with either its sibling (side) or the zero value for that level. currentLevelHash = Merkle.efficientHash( isLeft ? currentLevelHash : Arrays.unsafeAccess(self._sides, i).value, isLeft ? Arrays.unsafeAccess(self._zeros, i).value : currentLevelHash ); // Update node index currentIndex >>= 1; } Arrays.unsafeAccess(self._sides, levels).value = currentLevelHash; return (index, currentLevelHash); } /** * @dev Tree's root. */ function root(Bytes32PushTree storage self) internal view returns (bytes32) { return Arrays.unsafeAccess(self._sides, self._sides.length - 1).value; } /** * @dev Tree's height (does not include the root node). */ function height(Bytes32PushTree storage self) internal view returns (uint256) { return self._sides.length - 1; } }
// 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 {UncheckedMath} from "../../common/libraries/UncheckedMath.sol"; import {MerklePathEmpty, MerklePathOutOfBounds, MerkleIndexOutOfBounds, MerklePathLengthMismatch, MerkleNothingToProve, MerkleIndexOrHeightMismatch} from "../../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact [email protected] library Merkle { using UncheckedMath for uint256; /// @dev Calculate Merkle root by the provided Merkle proof. /// NOTE: When using this function, check that the _path length is equal to the tree height to prevent shorter/longer paths attack /// however, for chains settling on GW the proof includes the GW proof, so the path increases. See Mailbox for more details. /// @param _path Merkle path from the leaf to the root /// @param _index Leaf index in the tree /// @param _itemHash Hash of leaf content /// @return The Merkle root function calculateRoot( bytes32[] calldata _path, uint256 _index, bytes32 _itemHash ) internal pure returns (bytes32) { uint256 pathLength = _path.length; _validatePathLengthForSingleProof(_index, pathLength); bytes32 currentHash = _itemHash; for (uint256 i; i < pathLength; i = i.uncheckedInc()) { currentHash = (_index % 2 == 0) ? efficientHash(currentHash, _path[i]) : efficientHash(_path[i], currentHash); _index /= 2; } return currentHash; } /// @dev Calculate Merkle root by the provided Merkle proof. /// @dev NOTE: When using this function, check that the _path length is appropriate to prevent shorter/longer paths attack /// @param _path Merkle path from the leaf to the root /// @param _index Leaf index in the tree. /// @dev NOTE the tree can be joined. In this case the second tree's leaves indexes increase by the number of leaves in the first tree. /// @param _itemHash Hash of leaf content /// @return The Merkle root function calculateRootMemory( bytes32[] memory _path, uint256 _index, bytes32 _itemHash ) internal pure returns (bytes32) { uint256 pathLength = _path.length; _validatePathLengthForSingleProof(_index, pathLength); bytes32 currentHash = _itemHash; for (uint256 i; i < pathLength; i = i.uncheckedInc()) { currentHash = (_index % 2 == 0) ? efficientHash(currentHash, _path[i]) : efficientHash(_path[i], currentHash); _index /= 2; } return currentHash; } /// @dev Calculate Merkle root by the provided Merkle proof for a range of elements /// NOTE: When using this function, check that the _startPath and _endPath lengths are equal to the tree height to prevent shorter/longer paths attack /// @param _startPath Merkle path from the first element of the range to the root /// @param _endPath Merkle path from the last element of the range to the root /// @param _startIndex Index of the first element of the range in the tree /// @param _itemHashes Hashes of the elements in the range /// @return The Merkle root function calculateRootPaths( bytes32[] memory _startPath, bytes32[] memory _endPath, uint256 _startIndex, bytes32[] memory _itemHashes ) internal pure returns (bytes32) { uint256 pathLength = _startPath.length; if (pathLength != _endPath.length) { revert MerklePathLengthMismatch(pathLength, _endPath.length); } if (pathLength >= 256) { revert MerklePathOutOfBounds(); } uint256 levelLen = _itemHashes.length; // Edge case: we want to be able to prove an element in a single-node tree. if (pathLength == 0 && (_startIndex != 0 || levelLen != 1)) { revert MerklePathEmpty(); } if (levelLen == 0) { revert MerkleNothingToProve(); } if (_startIndex + levelLen > (1 << pathLength)) { revert MerkleIndexOrHeightMismatch(); } bytes32[] memory itemHashes = _itemHashes; for (uint256 level; level < pathLength; level = level.uncheckedInc()) { uint256 parity = _startIndex % 2; // We get an extra element on the next level if on the current level elements either // start on an odd index (`parity == 1`) or end on an even index (`levelLen % 2 == 1`) uint256 nextLevelLen = levelLen / 2 + (parity | (levelLen % 2)); for (uint256 i; i < nextLevelLen; i = i.uncheckedInc()) { bytes32 lhs = (i == 0 && parity == 1) ? _startPath[level] : itemHashes[2 * i - parity]; bytes32 rhs = (i == nextLevelLen - 1 && (levelLen - parity) % 2 == 1) ? _endPath[level] : itemHashes[2 * i + 1 - parity]; itemHashes[i] = efficientHash(lhs, rhs); } levelLen = nextLevelLen; _startIndex /= 2; } return itemHashes[0]; } /// @dev Keccak hash of the concatenation of two 32-byte words function efficientHash(bytes32 _lhs, bytes32 _rhs) internal pure returns (bytes32 result) { assembly { mstore(0x00, _lhs) mstore(0x20, _rhs) result := keccak256(0x00, 0x40) } } function _validatePathLengthForSingleProof(uint256 _index, uint256 _pathLength) private pure { if (_pathLength >= 256) { revert MerklePathOutOfBounds(); } if (_index >= (1 << _pathLength)) { revert MerkleIndexOutOfBounds(); } } }
// 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; /// @notice Part of the configuration parameters of ZKP circuits struct VerifierParams { bytes32 recursionNodeLevelVkHash; bytes32 recursionLeafLevelVkHash; bytes32 recursionCircuitsSetVksHash; } /// @title The interface of the Verifier contract, responsible for the zero knowledge proof verification. /// @author Matter Labs /// @custom:security-contact [email protected] interface IVerifier { /// @dev Verifies a zk-SNARK proof. /// @return A boolean value indicating whether the zk-SNARK proof is valid. /// Note: The function may revert execution instead of returning false in some cases. function verify(uint256[] calldata _publicInputs, uint256[] calldata _proof) external view returns (bool); /// @notice Calculates a keccak256 hash of the runtime loaded verification keys. /// @return vkHash The keccak256 hash of the loaded verification keys. function verificationKeyHash() external view returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridgehub} from "../../bridgehub/IBridgehub.sol"; /// @dev The encoding version used for legacy txs. bytes1 constant LEGACY_ENCODING_VERSION = 0x00; /// @dev The encoding version used for new txs. bytes1 constant NEW_ENCODING_VERSION = 0x01; /// @dev The encoding version used for txs that set the asset handler on the counterpart contract. bytes1 constant SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION = 0x02; /// @title L1 Bridge contract interface /// @author Matter Labs /// @custom:security-contact [email protected] interface IAssetRouterBase { event BridgehubDepositBaseTokenInitiated( uint256 indexed chainId, address indexed from, bytes32 assetId, uint256 amount ); event BridgehubDepositInitiated( uint256 indexed chainId, bytes32 indexed txDataHash, address indexed from, bytes32 assetId, bytes bridgeMintCalldata ); event BridgehubWithdrawalInitiated( uint256 chainId, address indexed sender, bytes32 indexed assetId, bytes32 assetDataHash // Todo: What's the point of emitting hash? ); event AssetDeploymentTrackerRegistered( bytes32 indexed assetId, bytes32 indexed additionalData, address assetDeploymentTracker ); event AssetHandlerRegistered(bytes32 indexed assetId, address indexed _assetHandlerAddress); event DepositFinalizedAssetRouter(uint256 indexed chainId, bytes32 indexed assetId, bytes assetData); function BRIDGE_HUB() external view returns (IBridgehub); /// @notice Sets the asset handler address for a specified asset ID on the chain of the asset deployment tracker. /// @dev The caller of this function is encoded within the `assetId`, therefore, it should be invoked by the asset deployment tracker contract. /// @dev No access control on the caller, as msg.sender is encoded in the assetId. /// @dev Typically, for most tokens, ADT is the native token vault. However, custom tokens may have their own specific asset deployment trackers. /// @dev `setAssetHandlerAddressOnCounterpart` should be called on L1 to set asset handlers on L2 chains for a specific asset ID. /// @param _assetRegistrationData The asset data which may include the asset address and any additional required data or encodings. /// @param _assetHandlerAddress The address of the asset handler to be set for the provided asset. function setAssetHandlerAddressThisChain(bytes32 _assetRegistrationData, address _assetHandlerAddress) external; function assetHandlerAddress(bytes32 _assetId) external view returns (address); /// @notice Finalize the withdrawal and release funds. /// @param _chainId The chain ID of the transaction to check. /// @param _assetId The bridged asset ID. /// @param _transferData The position in the L2 logs Merkle tree of the l2Log that was sent with the message. /// @dev We have both the legacy finalizeWithdrawal and the new finalizeDeposit functions, /// finalizeDeposit uses the new format. On the L2 we have finalizeDeposit with new and old formats both. function finalizeDeposit(uint256 _chainId, bytes32 _assetId, bytes memory _transferData) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /// @author Matter Labs /// @custom:security-contact [email protected] interface IL1AssetDeploymentTracker { function bridgeCheckCounterpartAddress( uint256 _chainId, bytes32 _assetId, address _originalCaller, address _assetHandlerAddressOnCounterpart ) external view; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits"); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits"); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits"); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits"); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits"); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits"); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits"); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits"); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits"); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits"); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits"); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits"); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits"); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits"); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits"); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits"); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits"); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits"); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits"); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits"); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits"); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits"); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Arrays.sol) pragma solidity ^0.8.0; import "./StorageSlot.sol"; import "./math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { using StorageSlot for bytes32; /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (unsafeAccess(array, mid).value > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && unsafeAccess(array, low - 1).value == element) { return low - 1; } else { return low; } } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) { bytes32 slot; // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) slot := add(keccak256(0, 0x20), pos) } return slot.getAddressSlot(); } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) { bytes32 slot; // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) slot := add(keccak256(0, 0x20), pos) } return slot.getBytes32Slot(); } /** * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check. * * WARNING: Only use if you are certain `pos` is lower than the array length. */ function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) { bytes32 slot; // We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr` // following https://docs.soliditylang.org/en/v0.8.17/internals/layout_in_storage.html#mappings-and-dynamic-arrays. /// @solidity memory-safe-assembly assembly { mstore(0, arr.slot) slot := add(keccak256(0, 0x20), pos) } return slot.getUint256Slot(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._ * _Available since v4.9 for `string`, `bytes`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
{ "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/", "@openzeppelin/contracts-v4/=lib/openzeppelin-contracts-v4/contracts/", "@openzeppelin/contracts-upgradeable-v4/=lib/openzeppelin-contracts-upgradeable-v4/contracts/", "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/" ], "optimizer": { "enabled": true, "runs": 200 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "cancun", "viaIR": false, "libraries": {} }
Contract ABI
API[{"inputs":[{"internalType":"uint256","name":"_l1ChainId","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bytes32","name":"expected","type":"bytes32"},{"internalType":"bytes32","name":"actual","type":"bytes32"}],"name":"BatchHashMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedBatchNumber","type":"uint256"},{"internalType":"uint256","name":"providedBatchNumber","type":"uint256"}],"name":"BatchNumberMismatch","type":"error"},{"inputs":[],"name":"CanOnlyProcessOneBatch","type":"error"},{"inputs":[],"name":"CantExecuteUnprovenBatches","type":"error"},{"inputs":[],"name":"CantRevertExecutedBatch","type":"error"},{"inputs":[],"name":"EmptyData","type":"error"},{"inputs":[{"internalType":"bytes32","name":"expected","type":"bytes32"},{"internalType":"bytes32","name":"actual","type":"bytes32"}],"name":"HashMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"processFromExpected","type":"uint256"},{"internalType":"uint256","name":"processToExpected","type":"uint256"},{"internalType":"uint256","name":"processFromProvided","type":"uint256"},{"internalType":"uint256","name":"processToProvided","type":"uint256"}],"name":"IncorrectBatchBounds","type":"error"},{"inputs":[{"internalType":"uint256","name":"batchesDataLength","type":"uint256"},{"internalType":"uint256","name":"priorityOpsDataLength","type":"uint256"}],"name":"InvalidBatchesDataLength","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"logKey","type":"uint256"}],"name":"InvalidLogSender","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"numCommitments","type":"uint256"},{"internalType":"uint256","name":"numHashes","type":"uint256"}],"name":"InvalidNumberOfBlobs","type":"error"},{"inputs":[],"name":"InvalidProof","type":"error"},{"inputs":[],"name":"InvalidProtocolVersion","type":"error"},{"inputs":[],"name":"InvalidSystemLogsLength","type":"error"},{"inputs":[],"name":"L2TimestampTooBig","type":"error"},{"inputs":[{"internalType":"uint8","name":"","type":"uint8"}],"name":"LogAlreadyProcessed","type":"error"},{"inputs":[],"name":"MerkleIndexOrHeightMismatch","type":"error"},{"inputs":[],"name":"MerkleNothingToProve","type":"error"},{"inputs":[],"name":"MerklePathEmpty","type":"error"},{"inputs":[{"internalType":"uint256","name":"pathLength","type":"uint256"},{"internalType":"uint256","name":"expectedLength","type":"uint256"}],"name":"MerklePathLengthMismatch","type":"error"},{"inputs":[],"name":"MerklePathOutOfBounds","type":"error"},{"inputs":[],"name":"MismatchL2DAValidator","type":"error"},{"inputs":[{"internalType":"uint256","name":"numberOfLayer1Txs","type":"uint256"},{"internalType":"uint256","name":"expectedLength","type":"uint256"}],"name":"MismatchNumberOfLayer1Txs","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"MissingSystemLogs","type":"error"},{"inputs":[],"name":"NonIncreasingTimestamp","type":"error"},{"inputs":[],"name":"NonSequentialBatch","type":"error"},{"inputs":[],"name":"NotHistoricalRoot","type":"error"},{"inputs":[],"name":"NotInitializedReentrancyGuard","type":"error"},{"inputs":[],"name":"NotSettlementLayer","type":"error"},{"inputs":[],"name":"PriorityOperationsRollingHashMismatch","type":"error"},{"inputs":[],"name":"PriorityOpsDataItemHashesLengthIsNotZero","type":"error"},{"inputs":[],"name":"PriorityOpsDataLeftPathLengthIsNotZero","type":"error"},{"inputs":[],"name":"PriorityOpsDataRightPathLengthIsNotZero","type":"error"},{"inputs":[],"name":"QueueIsEmpty","type":"error"},{"inputs":[],"name":"Reentrancy","type":"error"},{"inputs":[],"name":"RevertedBatchNotAfterNewLastBatch","type":"error"},{"inputs":[],"name":"SystemLogsSizeTooBig","type":"error"},{"inputs":[{"internalType":"uint256","name":"expectedTimestamp","type":"uint256"},{"internalType":"uint256","name":"actualTimestamp","type":"uint256"}],"name":"TimeNotReached","type":"error"},{"inputs":[],"name":"TimestampError","type":"error"},{"inputs":[],"name":"TxHashMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"}],"name":"Unauthorized","type":"error"},{"inputs":[{"internalType":"uint256","name":"logKey","type":"uint256"}],"name":"UnexpectedSystemLog","type":"error"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"}],"name":"UnsupportedCommitBatchEncoding","type":"error"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"}],"name":"UnsupportedExecuteBatchEncoding","type":"error"},{"inputs":[{"internalType":"uint8","name":"version","type":"uint8"}],"name":"UnsupportedProofBatchEncoding","type":"error"},{"inputs":[],"name":"UpgradeBatchNumberIsNotZero","type":"error"},{"inputs":[{"internalType":"uint256","name":"expected","type":"uint256"},{"internalType":"uint256","name":"actual","type":"uint256"}],"name":"ValueMismatch","type":"error"},{"inputs":[],"name":"VerifiedBatchesExceedsCommittedBatches","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"batchNumber","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"batchHash","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"commitment","type":"bytes32"}],"name":"BlockCommit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"batchNumber","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"batchHash","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"commitment","type":"bytes32"}],"name":"BlockExecution","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"totalBatchesCommitted","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBatchesVerified","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBatchesExecuted","type":"uint256"}],"name":"BlocksRevert","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"previousLastVerifiedBatch","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"currentLastVerifiedBatch","type":"uint256"}],"name":"BlocksVerification","type":"event"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"_processFrom","type":"uint256"},{"internalType":"uint256","name":"_processTo","type":"uint256"},{"internalType":"bytes","name":"_commitData","type":"bytes"}],"name":"commitBatchesSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"_processFrom","type":"uint256"},{"internalType":"uint256","name":"_processTo","type":"uint256"},{"internalType":"bytes","name":"_executeData","type":"bytes"}],"name":"executeBatchesSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getName","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"_processBatchFrom","type":"uint256"},{"internalType":"uint256","name":"_processBatchTo","type":"uint256"},{"internalType":"bytes","name":"_proofData","type":"bytes"}],"name":"proveBatchesSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"_newLastBatch","type":"uint256"}],"name":"revertBatchesSharedBridge","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Deployed Bytecode
0x608060405234801561000f575f80fd5b5060043610610055575f3560e01c80630f23da431461005957806317d7de7c1461006e57806398f81962146100b0578063cf02827d146100c3578063e12a6137146100d6575b5f80fd5b61006c6100673660046125aa565b6100e9565b005b61009a6040518060400160405280600d81526020016c115e1958dd5d1bdc919858d95d609a1b81525081565b6040516100a7919061260d565b60405180910390f35b61006c6100be366004612626565b6101b9565b61006c6100d1366004612626565b6103f4565b61006c6100e4366004612626565b61073a565b5f805160206130ae833981519152545f8190036101195760405163dd7e362160e01b815260040160405180910390fd5b6001811461013a5760405163558a1e0360e11b815260040160405180910390fd5b60025f805160206130ae83398151915255335f9081526009602052604090205460ff161580156101755750602a546001600160a01b03163314155b1561019a5760405163472511eb60e11b81523360048201526024015b60405180910390fd5b6101a3826109d2565b60015f805160206130ae83398151915255505050565b5f805160206130ae833981519152545f8190036101e95760405163dd7e362160e01b815260040160405180910390fd5b6001811461020a5760405163558a1e0360e11b815260040160405180910390fd5b60025f805160206130ae83398151915255335f9081526009602052604090205460ff1661024c5760405163472511eb60e11b8152336004820152602401610191565b6032546001600160a01b03161561027657604051636813371360e11b815260040160405180910390fd5b602a5460215460405163def9d6af60e01b81526001600160a01b039092169163def9d6af916102ab9160040190815260200190565b602060405180830381865afa1580156102c6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102ea91906126aa565b61030757604051635428eae760e01b815260040160405180910390fd5b5f8061031585858989610aaf565b91509150805160011461033b5760405163e85392f960e01b815260040160405180910390fd5b61034482610be2565b600d545f908152600e60205260409020541461039657600d545f908152600e602052604090205461037483610be2565b6040516355ad3fd360e01b815260048101929092526024820152604401610191565b6022548015806103a7575060235415155b156103bb576103b68383610c11565b6103c6565b6103c6838383610cb1565b8151600d546103d591906126dd565b600d55505060015f805160206130ae8339815191525550505050505050565b5f805160206130ae833981519152545f8190036104245760405163dd7e362160e01b815260040160405180910390fd5b600181146104455760405163558a1e0360e11b815260040160405180910390fd5b60025f805160206130ae83398151915255335f9081526009602052604090205460ff166104875760405163472511eb60e11b8152336004820152602401610191565b6032546001600160a01b0316156104b157604051636813371360e11b815260040160405180910390fd5b5f806104bf85858989610dad565b815181519294509092509081146104f65782518251604051631f7ac61760e31b815260048101929092526024820152604401610191565b5f5b818110156106c05760335460125410156105ed5782818151811061051e5761051e6126f0565b60200260200101515f0151515f1461054957604051635500823360e01b815260040160405180910390fd5b82818151811061055b5761055b6126f0565b602002602001015160200151515f1461058757604051638be936a960e01b815260040160405180910390fd5b828181518110610599576105996126f0565b602002602001015160400151515f146105c5576040516399d4473960e01b815260040160405180910390fd5b6105e88482815181106105da576105da6126f0565b602002602001015182610e79565b61062a565b61062a848281518110610602576106026126f0565b602002602001015184838151811061061c5761061c6126f0565b602002602001015183610ec4565b83818151811061063c5761063c6126f0565b602002602001015160e0015184828151811061065a5761065a6126f0565b602002602001015160200151858381518110610678576106786126f0565b60200260200101515f01516001600160401b03167f2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d316560405160405180910390a46001016104f8565b50600b545f906106d19083906126dd565b600b819055600c549091508111156106fb576040516263756960e11b815260040160405180910390fd5b602354801580159061070d5750818111155b1561071c575f60228190556023555b505050505060015f805160206130ae83398151915255505050505050565b5f805160206130ae833981519152545f81900361076a5760405163dd7e362160e01b815260040160405180910390fd5b6001811461078b5760405163558a1e0360e11b815260040160405180910390fd5b60025f805160206130ae83398151915255335f9081526009602052604090205460ff166107cd5760405163472511eb60e11b8152336004820152602401610191565b6032546001600160a01b0316156107f757604051636813371360e11b815260040160405180910390fd5b5f805f61080686868a8a610f60565b600c5482519396509194509250905f816001600160401b0381111561082d5761082d612704565b604051908082528060200260200182016040528015610856578160200160208202803683370190505b505f848152600e602052604090205490915061087187610be2565b1461088d575f838152600e602052604090205461037487610be2565b60e08601515f5b8381101561095457600185015f818152600e60205260409020548851919650906108d7908990849081106108ca576108ca6126f0565b6020026020010151610be2565b14610902575f858152600e60205260409020548751610374908990849081106108ca576108ca6126f0565b5f878281518110610915576109156126f0565b602002602001015160e00151905061092d8382611027565b84838151811061093f5761093f6126f0565b60209081029190910101529150600101610894565b50600d548411156109785760405163e102246960e01b815260040160405180910390fd5b6109828286611069565b600c546040518591907f22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81905f90a3505050600c55505060015f805160206130ae8339815191525550505050505050565b6032546001600160a01b0316156109fc57604051636813371360e11b815260040160405180910390fd5b600d548110610a1e57604051639a67c1cb60e01b815260040160405180910390fd5b600b54811015610a415760405163e18cb38360e01b815260040160405180910390fd5b600c54811015610a5157600c8190555b600d819055602354811015610a65575f6023555b600d54600c54600b5460408051938452602084019290925282820152517f8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee59181900360600190a150565b610ab7612567565b6060610ac3868661111c565b805191935091505f03610ae9576040516399d8fec960e01b815260040160405180910390fd5b83815f81518110610afc57610afc6126f0565b60200260200101515f01516001600160401b0316141580610b4f5750828160018351610b289190612718565b81518110610b3857610b386126f0565b60200260200101515f01516001600160401b031614155b15610bd9578383825f81518110610b6857610b686126f0565b60200260200101515f01518360018551610b829190612718565b81518110610b9257610b926126f0565b60209081029190910101515160405163d7d93e1f60e01b8152600481019490945260248401929092526001600160401b039081166044840152166064820152608401610191565b94509492505050565b5f81604051602001610bf49190612786565b604051602081830303815290604052805190602001209050919050565b5f5b8151811015610cac57610c4283838381518110610c3257610c326126f0565b60200260200101515f801b6111b5565b9250610c4d83610be2565b83516001600160401b039081165f908152600e602090815260408083209490945560e087015190870151875194519194909316917f8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb76391a4600101610c13565b505050565b60235415610cd25760405163f093c2e560e01b815260040160405180910390fd5b815f81518110610ce457610ce46126f0565b6020908102919091010151516001600160401b03166023555f5b8251811015610da7575f8115610d14575f610d16565b825b9050610d3c85858481518110610d2e57610d2e6126f0565b6020026020010151836111b5565b9450610d4785610be2565b85516001600160401b039081165f908152600e602090815260408083209490945560e089015190890151895194519194909316917f8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb76391a450600101610cfe565b50505050565b606080610dba86866114f6565b815191935091505f03610de0576040516399d8fec960e01b815260040160405180910390fd5b83825f81518110610df357610df36126f0565b60200260200101515f01516001600160401b0316141580610e465750828260018451610e1f9190612718565b81518110610e2f57610e2f6126f0565b60200260200101515f01516001600160401b031614155b15610bd9578383835f81518110610e5f57610e5f6126f0565b60200260200101515f01518460018651610b829190612718565b5f610e878360600151611576565b9050610e9483838361160b565b825160a0840180516001600160401b039092165f818152600f602052604090209290925551610da79082906116a7565b826060015182604001515114610f03578160400151518360600151604051632c01a4af60e01b8152600401610191929190918252602082015260400190565b5f610f1183604001516117a9565b9050610f1e84838361160b565b610f29603384611840565b835160a0850180516001600160401b039092165f818152600f602052604090209290925551610f599082906116a7565b5050505050565b610f68612567565b606080610f7587876118bc565b815192955090935091505f03610f9e576040516399d8fec960e01b815260040160405180910390fd5b84825f81518110610fb157610fb16126f0565b60200260200101515f01516001600160401b03161415806110045750838260018451610fdd9190612718565b81518110610fed57610fed6126f0565b60200260200101515f01516001600160401b031614155b1561101d578484835f81518110610e5f57610e5f6126f0565b9450945094915050565b5f60208383604051602001611046929190918252602082015260400190565b604051602081830303815290604052805190602001205f1c901c90505b92915050565b815160011461108b5760405163e85392f960e01b815260040160405180910390fd5b600a5460405163b864f5a960e01b81525f916001600160a01b03169063b864f5a9906110bd90869086906004016127cf565b602060405180830381865afa1580156110d8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110fc91906126aa565b905080610cac576040516309bde33960e01b815260040160405180910390fd5b611124612567565b60605f839003611147576040516399d8fec960e01b815260040160405180910390fd5b5f84845f81811061115a5761115a6126f0565b919091013560f81c915081905061118f5761117884600181886127fc565b81019061118591906129dc565b90935091506111ad565b604051633cf746e760e21b815260ff82166004820152602401610191565b509250929050565b6111bd612567565b83516111ca906001612b5e565b6001600160401b0316835f01516001600160401b0316146112205783516111f2906001612b5e565b835160405163bd4455ff60e01b81526001600160401b03928316600482015291166024820152604401610191565b5f61122b8484611937565b602f54602854865160e084015161012089015160405163381c3f1360e01b81529596505f956001600160a01b039095169463381c3f13946112819490936001600160401b03909116929091601090600401612b7e565b5f604051808303815f875af115801561129c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526112c39190810190612c1b565b9050816040015186602001511461130257816040015186602001516040516305846adf60e11b8152600401610191929190918252602082015260400190565b8460a0015182602001511461133d57602082015160a08601516040516305846adf60e11b815260048101929092526024820152604401610191565b60808501518251146113725781516080860151604051630626ade360e41b815260048101929092526024820152604401610191565b6113928260c0015186602001516001600160401b03168860c00151611e2d565b5f805f6113ac88855f015186604001518760200151611ef5565b925092509250604051806101000160405280895f01516001600160401b031681526020018960600151815260200189604001516001600160401b03168152602001896080015181526020018960a0015181526020018660a00151815260200189602001516001600160401b03168152602001828152509550467f0000000000000000000000000000000000000000000000000000000000aa36a7146114ea576114586180006008612caf565b6001600160a01b03166362f84b245f88868660405160200161147d9493929190612ccf565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016114a8919061260d565b6020604051808303815f875af11580156114c4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114e89190612cfb565b505b50505050509392505050565b6060805f83900361151a576040516399d8fec960e01b815260040160405180910390fd5b5f84845f81811061152d5761152d6126f0565b919091013560f81c91508190506115585761154b84600181886127fc565b8101906111859190612dd4565b604051630a6976c560e11b815260ff82166004820152602401610191565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4705f5b828110156115f6575f6115ac6010611fff565b80516040519192506115cc91859190602001918252602082015260400190565b604051602081830303815290604052805190602001209250506115ef8160010190565b9050611599565b50601254611606906033906120be565b919050565b8251600b546001600160401b03909116906116279084906126dd565b6116329060016126dd565b811461165057604051620417e760e61b815260040160405180910390fd5b5f818152600e602052604090205461166785610be2565b14611683575f818152600e602052604090205461037485610be2565b83608001518214610da75760405163356a640560e21b815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000000000000aa36a746146117a55760295460408051636a5cfa7d60e11b815290515f926001600160a01b03169163d4b9f4fa9160048083019260209291908290030181865afa158015611715573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117399190612f1a565b60285460405163fb644fc560e01b8152600481019190915260248101859052604481018490529091506001600160a01b0382169063fb644fc5906064015f604051808303815f87803b15801561178d575f80fd5b505af115801561179f573d5f803e3d5ffd5b50505050505b5050565b80515f907fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090825b8181101561183757828582815181106117ec576117ec6126f0565b602002602001015160405160200161180e929190918252602082015260400190565b6040516020818303038152906040528051906020012092506118308160010190565b90506117d1565b50909392505050565b604081015151156117a5575f611867825f01518360200151856001015485604001516120f7565b5f81815260028501602052604090205490915060ff1661189a57604051639b53b10160e01b815260040160405180910390fd5b816040015151836001015f8282546118b291906126dd565b9091555050505050565b6118c4612567565b6060805f85855f8181106118da576118da6126f0565b919091013560f81c9150819050611911576118f885600181896127fc565b8101906119059190612f40565b9195509350915061192f565b604051630f338f8360e41b815260ff82166004820152602401610191565b509250925092565b60408051610100810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915261010083015180515f9061198c605882613020565b156119aa57604051632f9c64f560e21b815260040160405180910390fd5b5f5b81811015611dc3575f6119d2856119c46004856126dd565b601491810182015192910190565b5090505f6119f3866119e56018866126dd565b602091810182015192910190565b5090505f611a06876119e56038876126dd565b509050600160ff83161b861615611a3557604051631b6825bb60e01b815260ff83166004820152602401610191565b600160ff83161b8617955081611aa157611a526180006008612caf565b6001600160a01b0316836001600160a01b031614611a95576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b60a08801819052611db8565b60018203611b0557611ab6618000600b612caf565b6001600160a01b0316836001600160a01b031614611af9576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b60c08801819052611db8565b60048203611b6957611b1a618000600b612caf565b6001600160a01b0316836001600160a01b031614611b5d576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b60408801819052611db8565b60028203611bcd57611b7e6180006001612caf565b6001600160a01b0316836001600160a01b031614611bc1576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b60208801819052611db8565b60038203611c2d57611be26180006001612caf565b6001600160a01b0316836001600160a01b031614611c25576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b808852611db8565b60068203611cb857611c426180006008612caf565b6001600160a01b0316836001600160a01b031614611c85576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b6030546001600160a01b03828116911614611cb35760405163111be21360e11b815260040160405180910390fd5b611db8565b60058203611d1c57611ccd6180006008612caf565b6001600160a01b0316836001600160a01b031614611d10576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b60e08801819052611db8565b60078203611d9457611d316180006001612caf565b6001600160a01b0316836001600160a01b031614611d74576040516360bc05eb60e11b81526001600160a01b038416600482015260248101839052604401610191565b808914611cb357604051630993220f60e31b815260040160405180910390fd5b6007821115611db85760405162d5473160e71b815260048101839052602401610191565b5050506058016119ac565b5084611df95781607f14611df45760405163fa44b52760e01b8152607f600482015260248101839052604401610191565b611e24565b8160ff14611e245760405163fa44b52760e01b815260ff600482015260248101839052604401610191565b50505092915050565b608083901c828114611e5257604051632d50c33b60e01b815260040160405180910390fd5b808210611e725760405163680c704760e11b815260040160405180910390fd5b6fffffffffffffffffffffffffffffffff841681611e936203f48042612718565b1115611ec95781611ea76203f48042612718565b60405163043a9cc160e11b815260048101929092526024820152604401610191565b611ed5610e10426126dd565b811115610f5957604051637dae117360e11b815260040160405180910390fd5b5f805f80611f4e88604081810151606080840151925160c09290921b6001600160c01b031916602083015260288201929092525f6048820181905260508201526070016040516020818303038152906040529050919050565b805190602001209050611fa4601954601754601854603a5460405160ff909416151560f81b6020850152602184019290925260418301526061820152606090608101604051602081830303815290604052905090565b805190602001209350611fb988888888612391565b8051602091820120604080519283018490528201869052606082018190529350608001604051602081830303815290604052805190602001209150509450945094915050565b604080516060810182525f80825260208201819052918101919091526002820154600183015403612043576040516363c3654960e01b815260040160405180910390fd5b5060028101545f81815260208381526040808320815160608101835281548152600180830180546001600160401b038116848801526801000000000000000090046001600160c01b03169483019490945286865293879052908490559290559091906120b09082906126dd565b836002018190555050919050565b81548110156120cb575050565b81545f906120d99083612718565b9050826001015481116120eb57505050565b60019092019190915550565b835183515f91908114612129578451604051629aa98360e41b8152610191918391600401918252602082015260400190565b610100811061214b57604051631c50038560e01b815260040160405180910390fd5b825181158015612165575084151580612165575080600114155b1561218357604051634711d60d60e11b815260040160405180910390fd5b805f036121a357604051631867cc2560e31b815260040160405180910390fd5b6001821b6121b182876126dd565b11156121d0576040516357ddbd2760e11b815260040160405180910390fd5b835f5b83811015612369575f6121e7600289613020565b90505f6121f5600286613020565b8217612202600287613033565b61220c91906126dd565b90505f5b81811015612345575f811580156122275750836001145b61225f578584612238846002613046565b6122429190612718565b81518110612252576122526126f0565b602002602001015161227a565b8c8581518110612271576122716126f0565b60200260200101515b90505f612288600185612718565b831480156122ab5750600261229d868a612718565b6122a79190613020565b6001145b6122ee5786856122bc856002613046565b6122c79060016126dd565b6122d19190612718565b815181106122e1576122e16126f0565b6020026020010151612309565b8c8681518110612300576123006126f0565b60200260200101515b905061231e82825f9182526020526040902090565b878481518110612330576123306126f0565b60209081029190910101525050600101612210565b5093508361235460028a613033565b985050506123628160010190565b90506121d3565b50805f8151811061237c5761237c6126f0565b60200260200101519350505050949350505050565b60606123a06058610200613046565b6123ab9060046126dd565b8561010001515111156123d157604051632b90ed0960e21b815260040160405180910390fd5b5f85610100015180519060200120905080858760c001518860e001516123f78888612425565b60405160200161240b95949392919061305d565b604051602081830303815290604052915050949350505050565b60606010835114158061243a57506010825114155b1561246c578251825160405163363a501760e21b81526010600482015260248101929092526044820152606401610191565b61247860106002613046565b6001600160401b0381111561248f5761248f612704565b6040519080825280602002602001820160405280156124b8578160200160208202803683370190505b5090505f5b6010811015612560578281815181106124d8576124d86126f0565b6020026020010151828260026124ee9190613046565b815181106124fe576124fe6126f0565b60200260200101818152505083818151811061251c5761251c6126f0565b6020026020010151828260026125329190613046565b61253d9060016126dd565b8151811061254d5761254d6126f0565b60209081029190910101526001016124bd565b5092915050565b60408051610100810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b5f80604083850312156125bb575f80fd5b50508035926020909101359150565b5f81518084525f5b818110156125ee576020818501810151868301820152016125d2565b505f602082860101526020601f19601f83011685010191505092915050565b602081525f61261f60208301846125ca565b9392505050565b5f805f805f6080868803121561263a575f80fd5b85359450602086013593506040860135925060608601356001600160401b0380821115612665575f80fd5b818801915088601f830112612678575f80fd5b813581811115612686575f80fd5b896020828501011115612697575f80fd5b9699959850939650602001949392505050565b5f602082840312156126ba575f80fd5b8151801515811461261f575f80fd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115611063576110636126c9565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b81810381811115611063576110636126c9565b6001600160401b038082511683526020820151602084015280604083015116604084015250606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e08301525050565b6101008101611063828461272b565b5f815180845260208085019450602084015f5b838110156127c4578151875295820195908201906001016127a8565b509495945050505050565b604081525f6127e16040830185612795565b82810360208401526127f38185612795565b95945050505050565b5f808585111561280a575f80fd5b83861115612816575f80fd5b5050820193919092039150565b60405161014081016001600160401b038111828210171561284657612846612704565b60405290565b604051606081016001600160401b038111828210171561284657612846612704565b604051601f8201601f191681016001600160401b038111828210171561289657612896612704565b604052919050565b80356001600160401b0381168114611606575f80fd5b5f6101008083850312156128c6575f80fd5b604051908101906001600160401b03821181831017156128e8576128e8612704565b816040528092506128f88461289e565b8152602084013560208201526129106040850161289e565b6040820152606084013560608201526080840135608082015260a084013560a082015260c084013560c082015260e084013560e0820152505092915050565b5f6001600160401b0382111561296757612967612704565b5060051b60200190565b5f82601f830112612980575f80fd5b81356001600160401b0381111561299957612999612704565b6129ac601f8201601f191660200161286e565b8181528460208386010111156129c0575f80fd5b816020850160208301375f918101602001919091529392505050565b5f8061012083850312156129ee575f80fd5b6129f884846128b4565b9150610100808401356001600160401b0380821115612a15575f80fd5b818601915086601f830112612a28575f80fd5b81356020612a3d612a388361294f565b61286e565b82815260059290921b8401810191818101908a841115612a5b575f80fd5b8286015b84811015612b4c57803586811115612a75575f80fd5b8701610140818e03601f19011215612a8b575f80fd5b612a93612823565b612a9e86830161289e565b8152612aac6040830161289e565b86820152612abc6060830161289e565b60408201526080820135606082015260a0820135608082015260c082013560a082015260e082013560c08201528982013560e082015261012082013588811115612b04575f80fd5b612b128f8883860101612971565b8b8301525061014082013588811115612b29575f80fd5b612b378f8883860101612971565b61012083015250845250918301918301612a5f565b50809750505050505050509250929050565b6001600160401b03818116838216019080821115612560576125606126c9565b85815284602082015283604082015260a060608201525f612ba260a08301856125ca565b90508260808301529695505050505050565b5f82601f830112612bc3575f80fd5b81516020612bd3612a388361294f565b8083825260208201915060208460051b870101935086841115612bf4575f80fd5b602086015b84811015612c105780518352918301918301612bf9565b509695505050505050565b5f60208284031215612c2b575f80fd5b81516001600160401b0380821115612c41575f80fd5b9083019060608286031215612c54575f80fd5b612c5c61284c565b82518152602083015182811115612c71575f80fd5b612c7d87828601612bb4565b602083015250604083015182811115612c94575f80fd5b612ca087828601612bb4565b60408301525095945050505050565b6001600160a01b03818116838216019080821115612560576125606126c9565b60ff851681526101608101612ce7602083018661272b565b610120820193909352610140015292915050565b5f60208284031215612d0b575f80fd5b5051919050565b5f82601f830112612d21575f80fd5b81356020612d31612a388361294f565b8083825260208201915060208460081b870101935086841115612d52575f80fd5b602086015b84811015612c1057612d6988826128b4565b83529183019161010001612d57565b5f82601f830112612d87575f80fd5b81356020612d97612a388361294f565b8083825260208201915060208460051b870101935086841115612db8575f80fd5b602086015b84811015612c105780358352918301918301612dbd565b5f8060408385031215612de5575f80fd5b82356001600160401b0380821115612dfb575f80fd5b612e0786838701612d12565b9350602091508185013581811115612e1d575f80fd5b8501601f81018713612e2d575f80fd5b8035612e3b612a388261294f565b81815260059190911b82018401908481019089831115612e59575f80fd5b8584015b83811015612f0957803586811115612e73575f80fd5b85016060818d03601f1901811315612e89575f80fd5b612e9161284c565b8983013589811115612ea1575f80fd5b612eaf8f8c83870101612d78565b825250604083013589811115612ec3575f80fd5b612ed18f8c83870101612d78565b828c015250908201359088821115612ee7575f80fd5b612ef58e8b84860101612d78565b604082015285525050918601918601612e5d565b508096505050505050509250929050565b5f60208284031215612f2a575f80fd5b81516001600160a01b038116811461261f575f80fd5b5f805f6101408486031215612f53575f80fd5b612f5d85856128b4565b92506101008401356001600160401b0380821115612f79575f80fd5b612f8587838801612d12565b9350610120860135915080821115612f9b575f80fd5b508401601f81018613612fac575f80fd5b80356020612fbc612a388361294f565b8083825260208201915060208460051b860101935089841115612fdd575f80fd5b6020850194505b83851015612ffd57843582529382019390820190612fe4565b80955050505050509250925092565b634e487b7160e01b5f52601260045260245ffd5b5f8261302e5761302e61300c565b500690565b5f826130415761304161300c565b500490565b8082028115828204841417611063576110636126c9565b8581525f6020866020840152856040840152846060840152608083018451602086015f5b8281101561309d57815184529284019290840190600101613081565b50919a995050505050505050505056fe8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4a2646970667358221220d4e6f03225c336ccf0ae747e4c1433586616d30ef7a9a2f5350eef2f1fe85d1264736f6c63430008180033
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.