diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 2f2871cea..9b136eac8 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -5,7 +5,7 @@ We truly appreciate efforts to discover and disclose security issues responsibly ## Vulnerabilities If you'd like to report a security issue in the repositories of matter-labs organization, please proceed to our -[Bug Bounty Program on Immunefi](https://era.zksync.io/docs/reference/troubleshooting/audit-bug-bounty.html#bug-bounty-program). +[Bug Bounty Program on Immunefi](https://immunefi.com/bug-bounty/zksyncera/information/). ## Other Security Issues diff --git a/.github/workflows/codespell.yaml b/.github/workflows/codespell.yaml index 39c2a69d5..8a4b4cbf8 100644 --- a/.github/workflows/codespell.yaml +++ b/.github/workflows/codespell.yaml @@ -12,25 +12,26 @@ name: Codespell on: pull_request jobs: - codespell: - runs-on: ubuntu-latest - - steps: - - name: Checkout the repository - uses: actions/checkout@v4 - - - name: pip cache - uses: actions/cache@v4 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} - restore-keys: ${{ runner.os }}-pip- - - - name: Install prerequisites - run: sudo pip install -r ./.codespell/requirements.txt - - - name: Spell check - run: codespell --config=./.codespell/.codespellrc + # TODO: fix codespell CI + # codespell: + # runs-on: ubuntu-latest + + # steps: + # - name: Checkout the repository + # uses: actions/checkout@v4 + + # - name: pip cache + # uses: actions/cache@v4 + # with: + # path: ~/.cache/pip + # key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} + # restore-keys: ${{ runner.os }}-pip- + + # - name: Install prerequisites + # run: sudo pip install -r ./.codespell/requirements.txt + + # - name: Spell check + # run: codespell --config=./.codespell/.codespellrc typos: runs-on: ubuntu-latest diff --git a/.github/workflows/dead-links.yaml b/.github/workflows/dead-links.yaml new file mode 100644 index 000000000..0bf2e6f88 --- /dev/null +++ b/.github/workflows/dead-links.yaml @@ -0,0 +1,22 @@ +name: Check Dead Links in Markdown Files + +on: pull_request + +jobs: + check-dead-links: + name: Check Dead Links in Markdown Files + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install Rust and Lychee + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y + ~/.cargo/bin/cargo install lychee + + - name: Find and check markdown files + run: | + GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} + find . -type f -name "*.md" ! -path "*/node_modules/*" ! -path "*/openzeppelin*" ! -path "*/murky/*" -exec lychee --github-token $GITHUB_TOKEN {} + diff --git a/.github/workflows/l1-contracts-ci.yaml b/.github/workflows/l1-contracts-ci.yaml index 964efaea8..c54944a27 100644 --- a/.github/workflows/l1-contracts-ci.yaml +++ b/.github/workflows/l1-contracts-ci.yaml @@ -78,6 +78,9 @@ jobs: - name: Lint run: yarn lint:check + - name: Lint errors + run: yarn l1 errors-lint --check + test-foundry: needs: [build, lint] runs-on: ubuntu-latest @@ -276,37 +279,38 @@ jobs: - name: Run coverage run: FOUNDRY_PROFILE=default yarn test:foundry && FOUNDRY_PROFILE=default yarn coverage:foundry --report summary --report lcov - # To ignore coverage for certain directories modify the paths in this step as needed. The - # below default ignores coverage results for the test and script directories. Alternatively, - # to include coverage in all directories, comment out this step. Note that because this - # filtering applies to the lcov file, the summary table generated in the previous step will - # still include all files and directories. - # The `--rc lcov_branch_coverage=1` part keeps branch info in the filtered report, since lcov - # defaults to removing branch info. - - name: Filter directories - run: | - sudo apt update && sudo apt install -y lcov - lcov --remove lcov.info 'test/*' 'contracts/dev-contracts/*' '../lib/forge-std/*' '../lib/murky/*' 'lib/*' '../lib/*' 'lib/' 'deploy-scripts/*' --output-file lcov.info --rc lcov_branch_coverage=1 - - # This step posts a detailed coverage report as a comment and deletes previous comments on - # each push. The below step is used to fail coverage if the specified coverage threshold is - # not met. The below step can post a comment (when it's `github-token` is specified) but it's - # not as useful, and this action cannot fail CI based on a minimum coverage threshold, which - # is why we use both in this way. - - name: Post coverage report - if: github.event_name == 'pull_request' # This action fails when ran outside of a pull request. - uses: romeovs/lcov-reporter-action@v0.3.1 - with: - delete-old-comments: true - lcov-file: ./l1-contracts/lcov.info - github-token: ${{ secrets.GITHUB_TOKEN }} # Adds a coverage summary comment to the PR. - - - name: Verify minimum coverage - uses: zgosalvez/github-actions-report-lcov@v2 - with: - coverage-files: ./l1-contracts/lcov.info - working-directory: l1-contracts - minimum-coverage: 85 # Set coverage threshold. + # TODO: for some reason filtering directories stopped working. + # # To ignore coverage for certain directories modify the paths in this step as needed. The + # # below default ignores coverage results for the test and script directories. Alternatively, + # # to include coverage in all directories, comment out this step. Note that because this + # # filtering applies to the lcov file, the summary table generated in the previous step will + # # still include all files and directories. + # # The `--rc lcov_branch_coverage=1` part keeps branch info in the filtered report, since lcov + # # defaults to removing branch info. + # - name: Filter directories + # run: | + # sudo apt update && sudo apt install -y lcov + # lcov --remove lcov.info 'test/*' 'contracts/dev-contracts/*' '../lib/forge-std/*' '../lib/murky/*' 'lib/*' '../lib/*' 'lib/' 'deploy-scripts/*' --output-file lcov.info --rc lcov_branch_coverage=1 + + # # This step posts a detailed coverage report as a comment and deletes previous comments on + # # each push. The below step is used to fail coverage if the specified coverage threshold is + # # not met. The below step can post a comment (when it's `github-token` is specified) but it's + # # not as useful, and this action cannot fail CI based on a minimum coverage threshold, which + # # is why we use both in this way. + # - name: Post coverage report + # if: github.event_name == 'pull_request' # This action fails when ran outside of a pull request. + # uses: romeovs/lcov-reporter-action@v0.3.1 + # with: + # delete-old-comments: true + # lcov-file: ./l1-contracts/lcov.info + # github-token: ${{ secrets.GITHUB_TOKEN }} # Adds a coverage summary comment to the PR. + + # - name: Verify minimum coverage + # uses: zgosalvez/github-actions-report-lcov@v2 + # with: + # coverage-files: ./l1-contracts/lcov.info + # working-directory: l1-contracts + # minimum-coverage: 85 # Set coverage threshold. gas-report: needs: [build, lint] diff --git a/.github/workflows/slither.yaml b/.github/workflows/slither.yaml index fa253e159..48b28a405 100644 --- a/.github/workflows/slither.yaml +++ b/.github/workflows/slither.yaml @@ -39,6 +39,7 @@ jobs: rm -rf ./l1-contracts/contracts/state-transition/utils/ rm -rf ./l1-contracts/contracts/state-transition/Verifier.sol rm -rf ./l1-contracts/contracts/state-transition/TestnetVerifier.sol + rm -rf ./l1-contracts/contracts/state-transition/chain-deps/GatewayCTMDeployer.sol rm -rf ./l1-contracts/contracts/dev-contracts/test/VerifierTest.sol rm -rf ./l1-contracts/contracts/dev-contracts/test/VerifierRecursiveTest.sol diff --git a/.github/workflows/system-contracts-ci.yaml b/.github/workflows/system-contracts-ci.yaml index f842214d6..a5ff52e26 100644 --- a/.github/workflows/system-contracts-ci.yaml +++ b/.github/workflows/system-contracts-ci.yaml @@ -53,35 +53,36 @@ jobs: - name: Run lint run: yarn lint:check - test-bootloader: - needs: [build, lint] - runs-on: ubuntu-latest - - steps: - - name: Checkout the repository - uses: actions/checkout@v4 - - - name: Install rust - uses: actions-rust-lang/setup-rust-toolchain@v1 - with: - toolchain: nightly-2023-04-17 - - - name: Restore artifacts cache - uses: actions/cache/restore@v3 - with: - fail-on-cache-miss: true - key: artifacts-system-${{ github.sha }} - path: | - system-contracts/artifacts-zk - system-contracts/cache-zk - system-contracts/typechain - system-contracts/contracts-preprocessed - system-contracts/bootloader/build - - - name: Run bootloader tests - run: | - cd system-contracts/bootloader/test_infra - cargo run + # FIXME: recover when used multivm is updated + # test-bootloader: + # needs: [build, lint] + # runs-on: ubuntu-latest + + # steps: + # - name: Checkout the repository + # uses: actions/checkout@v4 + + # - name: Install rust + # uses: actions-rust-lang/setup-rust-toolchain@v1 + # with: + # toolchain: nightly-2023-04-17 + + # - name: Restore artifacts cache + # uses: actions/cache/restore@v3 + # with: + # fail-on-cache-miss: true + # key: artifacts-system-${{ github.sha }} + # path: | + # system-contracts/artifacts-zk + # system-contracts/cache-zk + # system-contracts/typechain + # system-contracts/contracts-preprocessed + # system-contracts/bootloader/build + + # - name: Run bootloader tests + # run: | + # cd system-contracts/bootloader/test_infra + # cargo run test-contracts: needs: [build, lint] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 46bdeebac..dbefde5c1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,7 +13,7 @@ There are many ways to contribute to the ZK Stack: issues. 3. Resolve issues: either by showing an issue isn't a problem and the current state is ok as is or by fixing the problem and opening a PR. -4. Report security issues, see [our security policy](./github/SECURITY.md). +4. Report security issues, see [our security policy](./.github/SECURITY.md). 5. [Join the team!](https://matterlabs.notion.site/Shape-the-future-of-Ethereum-at-Matter-Labs-dfb3b5a037044bb3a8006af2eb0575e0) ## Fixing issues @@ -34,7 +34,7 @@ We aim to make it as easy as possible to contribute to the mission. This is stil and suggestions here too. Some resources to help: 1. [In-repo docs aimed at developers](docs) -2. [ZKsync Era docs!](https://era.zksync.io/docs/) +2. [ZKsync Era docs!](https://docs.zksync.io/zk-stack) 3. Company links can be found in the [repo's readme](README.md) ## Code of Conduct diff --git a/README.md b/README.md index cc1425b5b..8c776af4c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ or re-auditing a single line of code. ZKsync Era also uses an LLVM-based compile write smart contracts in C++, Rust and other popular languages. This repository contains both L1 and L2 ZKsync smart contracts. For their description see the -[system overview](docs/Overview.md). +[system overview](docs/overview.md). ## Disclaimer diff --git a/SECURITY.md b/SECURITY.md index 2f2871cea..9b136eac8 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -5,7 +5,7 @@ We truly appreciate efforts to discover and disclose security issues responsibly ## Vulnerabilities If you'd like to report a security issue in the repositories of matter-labs organization, please proceed to our -[Bug Bounty Program on Immunefi](https://era.zksync.io/docs/reference/troubleshooting/audit-bug-bounty.html#bug-bounty-program). +[Bug Bounty Program on Immunefi](https://immunefi.com/bug-bounty/zksyncera/information/). ## Other Security Issues diff --git a/SystemConfig.json b/SystemConfig.json index 73d75b2b0..e66dd60ee 100644 --- a/SystemConfig.json +++ b/SystemConfig.json @@ -13,7 +13,7 @@ "L1_TX_DELTA_FACTORY_DEPS_PUBDATA": 64, "L2_TX_INTRINSIC_GAS": 14070, "L2_TX_INTRINSIC_PUBDATA": 0, - "MAX_NEW_FACTORY_DEPS": 32, + "MAX_NEW_FACTORY_DEPS": 64, "MAX_GAS_PER_TRANSACTION": 80000000, "KECCAK_ROUND_COST_GAS": 40, "SHA256_ROUND_COST_GAS": 7, diff --git a/da-contracts/contracts/CalldataDA.sol b/da-contracts/contracts/CalldataDA.sol index ffb666f5f..776cd912d 100644 --- a/da-contracts/contracts/CalldataDA.sol +++ b/da-contracts/contracts/CalldataDA.sol @@ -2,7 +2,7 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string +import {OperatorDAInputLengthTooSmall, InvalidNumberOfBlobs, InvalidBlobsHashes, InvalidL2DAOutputHash, OneBlobWithCalldata, PubdataInputTooSmall, PubdataLengthTooBig, InvalidPubdataHash} from "./DAContractsErrors.sol"; /// @dev Total number of bytes in a blob. Blob = 4096 field elements * 31 bytes per field element /// @dev EIP-4844 defines it as 131_072 but we use 4096 * 31 within our circuits to always fit within a field element @@ -44,26 +44,34 @@ abstract contract CalldataDA { // - Then, there are linear hashes of the published blobs, 32 bytes each. // Check that it accommodates enough pubdata for the state diff hash, hash of pubdata + the number of blobs. - require(_operatorDAInput.length >= BLOB_DATA_OFFSET, "too small"); + if (_operatorDAInput.length < BLOB_DATA_OFFSET) { + revert OperatorDAInputLengthTooSmall(_operatorDAInput.length, BLOB_DATA_OFFSET); + } stateDiffHash = bytes32(_operatorDAInput[:32]); fullPubdataHash = bytes32(_operatorDAInput[32:64]); blobsProvided = uint256(uint8(_operatorDAInput[64])); - require(blobsProvided <= _maxBlobsSupported, "invalid number of blobs"); + if (blobsProvided > _maxBlobsSupported) { + revert InvalidNumberOfBlobs(blobsProvided, _maxBlobsSupported); + } // Note that the API of the contract requires that the returned blobs linear hashes have length of // the `_maxBlobsSupported` blobsLinearHashes = new bytes32[](_maxBlobsSupported); - require(_operatorDAInput.length >= BLOB_DATA_OFFSET + 32 * blobsProvided, "invalid blobs hashes"); + if (_operatorDAInput.length < BLOB_DATA_OFFSET + 32 * blobsProvided) { + revert InvalidBlobsHashes(_operatorDAInput.length, BLOB_DATA_OFFSET + 32 * blobsProvided); + } _cloneCalldata(blobsLinearHashes, _operatorDAInput[BLOB_DATA_OFFSET:], blobsProvided); uint256 ptr = BLOB_DATA_OFFSET + 32 * blobsProvided; // Now, we need to double check that the provided input was indeed returned by the L2 DA validator. - require(keccak256(_operatorDAInput[:ptr]) == _l2DAValidatorOutputHash, "invalid l2 DA output hash"); + if (keccak256(_operatorDAInput[:ptr]) != _l2DAValidatorOutputHash) { + revert InvalidL2DAOutputHash(); + } // The rest of the output was provided specifically by the operator l1DaInput = _operatorDAInput[ptr:]; @@ -81,8 +89,12 @@ abstract contract CalldataDA { uint256 _maxBlobsSupported, bytes calldata _pubdataInput ) internal pure virtual returns (bytes32[] memory blobCommitments, bytes calldata _pubdata) { - require(_blobsProvided == 1, "one blob with calldata"); - require(_pubdataInput.length >= BLOB_COMMITMENT_SIZE, "pubdata too small"); + if (_blobsProvided != 1) { + revert OneBlobWithCalldata(); + } + if (_pubdataInput.length < BLOB_COMMITMENT_SIZE) { + revert PubdataInputTooSmall(_pubdataInput.length, BLOB_COMMITMENT_SIZE); + } // We typically do not know whether we'll use calldata or blobs at the time when // we start proving the batch. That's why the blob commitment for a single blob is still present in the case of calldata. @@ -91,8 +103,12 @@ abstract contract CalldataDA { _pubdata = _pubdataInput[:_pubdataInput.length - BLOB_COMMITMENT_SIZE]; - require(_pubdata.length <= BLOB_SIZE_BYTES, "cz"); - require(_fullPubdataHash == keccak256(_pubdata), "wp"); + if (_pubdata.length > BLOB_SIZE_BYTES) { + revert PubdataLengthTooBig(_pubdata.length, BLOB_SIZE_BYTES); + } + if (_fullPubdataHash != keccak256(_pubdata)) { + revert InvalidPubdataHash(_fullPubdataHash, keccak256(_pubdata)); + } blobCommitments[0] = bytes32(_pubdataInput[_pubdataInput.length - BLOB_COMMITMENT_SIZE:_pubdataInput.length]); } diff --git a/da-contracts/contracts/DAContractsErrors.sol b/da-contracts/contracts/DAContractsErrors.sol index 2116d582d..0923b3579 100644 --- a/da-contracts/contracts/DAContractsErrors.sol +++ b/da-contracts/contracts/DAContractsErrors.sol @@ -3,8 +3,6 @@ pragma solidity ^0.8.21; // 0x53dee67b error PubdataCommitmentsEmpty(); -// 0x7734c31a -error PubdataCommitmentsTooBig(); // 0x53e6d04d error InvalidPubdataCommitmentsSize(); // 0xafd53e2f @@ -17,3 +15,35 @@ error NonEmptyBlobVersionHash(uint256 index); error PointEvalCallFailed(bytes); // 0x4daa985d error PointEvalFailed(bytes); + +// 0xf4a3e629 +error OperatorDAInputLengthTooSmall(uint256 operatorDAInputLength, uint256 blobDataOffset); + +// 0xbeb96791 +error InvalidNumberOfBlobs(uint256 blobsProvided, uint256 maxBlobsSupported); + +// 0xcd384e46 +error InvalidBlobsHashes(uint256 operatorDAInputLength, uint256 blobsProvided); + +// 0xe9e79528 +error InvalidL2DAOutputHash(); + +// 0x3db6e664 +error OneBlobWithCalldata(); + +// 0x2dc9747d +error PubdataInputTooSmall(uint256 pubdataInputLength, uint256 blobCommitmentSize); + +// 0x9044dff9 +error PubdataLengthTooBig(uint256 pubdataLength, uint256 blobSizeBytes); + +// 0x5513177c +error InvalidPubdataHash(bytes32 fullPubdataHash, bytes32 pubdata); + +// 0xc771423e +error BlobCommitmentNotPublished(); + +// 0x5717f940 +error InvalidPubdataSource(uint8 pubdataSource); +// 0x52595598 +error ValL1DAWrongInputLength(uint256 inputLength, uint256 expectedLength); diff --git a/da-contracts/contracts/IL1DAValidator.sol b/da-contracts/contracts/IL1DAValidator.sol index c22e9c557..cb2b640e5 100644 --- a/da-contracts/contracts/IL1DAValidator.sol +++ b/da-contracts/contracts/IL1DAValidator.sol @@ -17,7 +17,7 @@ struct L1DAValidatorOutput { 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 _chainId The batch number for which the data availability is being checked. + /// @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. diff --git a/da-contracts/contracts/RollupL1DAValidator.sol b/da-contracts/contracts/RollupL1DAValidator.sol index 99a57a7c3..c0b2765d6 100644 --- a/da-contracts/contracts/RollupL1DAValidator.sol +++ b/da-contracts/contracts/RollupL1DAValidator.sol @@ -2,15 +2,13 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {IL1DAValidator, L1DAValidatorOutput} from "./IL1DAValidator.sol"; import {CalldataDA} from "./CalldataDA.sol"; import {PubdataSource, BLS_MODULUS, PUBDATA_COMMITMENT_SIZE, PUBDATA_COMMITMENT_CLAIMED_VALUE_OFFSET, PUBDATA_COMMITMENT_COMMITMENT_OFFSET, BLOB_DA_INPUT_SIZE, POINT_EVALUATION_PRECOMPILE_ADDR} from "./DAUtils.sol"; -import {PubdataCommitmentsEmpty, InvalidPubdataCommitmentsSize, BlobHashCommitmentError, EmptyBlobVersionHash, NonEmptyBlobVersionHash, PointEvalCallFailed, PointEvalFailed} from "./DAContractsErrors.sol"; +import {InvalidPubdataSource, PubdataCommitmentsEmpty, InvalidPubdataCommitmentsSize, BlobHashCommitmentError, EmptyBlobVersionHash, NonEmptyBlobVersionHash, PointEvalCallFailed, PointEvalFailed, BlobCommitmentNotPublished} from "./DAContractsErrors.sol"; uint256 constant BLOBS_SUPPORTED = 6; @@ -67,7 +65,7 @@ contract RollupL1DAValidator is IL1DAValidator, CalldataDA { } else if (pubdataSource == uint8(PubdataSource.Calldata)) { (blobCommitments, ) = _processCalldataDA(blobsProvided, fullPubdataHash, _maxBlobsSupported, l1DaInput[1:]); } else { - revert("l1-da-validator/invalid-pubdata-source"); + revert InvalidPubdataSource(pubdataSource); } // We verify that for each set of blobHash/blobCommitment are either both empty @@ -145,8 +143,9 @@ contract RollupL1DAValidator is IL1DAValidator, CalldataDA { if (prepublishedCommitment != bytes32(0)) { // We double check that this commitment has indeed been published. // If that is the case, we do not care about the actual underlying data. - require(publishedBlobCommitments[prepublishedCommitment], "not published"); - + if (!publishedBlobCommitments[prepublishedCommitment]) { + revert BlobCommitmentNotPublished(); + } blobsCommitments[i] = prepublishedCommitment; } else { blobsCommitments[i] = _getPublishedBlobCommitment(versionedHashIndex, commitmentData); diff --git a/docs/Overview.md b/docs/Overview.md deleted file mode 100644 index bcee716b2..000000000 --- a/docs/Overview.md +++ /dev/null @@ -1,304 +0,0 @@ -# Overview - -ZKsync Era is a permissionless general-purpose ZK rollup. Similar to many L1 blockchains and sidechains it enables -deployment and interaction with Turing-complete smart contracts. - -- L2 smart contracts are executed on a zkEVM. -- zkEVM bytecode is different from the L1 EVM. -- There is a Solidity and Vyper compilers for L2 smart contracts. -- There is a standard way to pass messages between L1 and L2. That is a part of the protocol. -- There is no escape hatch mechanism yet, but there will be one. - -All data that is needed to restore the L2 state are also pushed on-chain. There are two approaches, publishing inputs of -L2 transactions on-chain and publishing the state transition diff. ZKsync follows the second option. - -See the [documentation](https://era.zksync.io/docs/dev/fundamentals/rollups.html) to read more! - -## Glossary - -- **Governor** - a privileged address that controls the upgradability of the network and sets other privileged - addresses. -- **Security council** - an address of the Gnosis multisig with the trusted owners that can decrease upgrade timelock. -- **Validator/Operator** - a privileged address that can commit/verify/execute L2 batches. -- **L2 batch (or just batch)** - An aggregation of multiple L2 blocks. Note, that while the API operates on L2 blocks, - the prove system operates on batches, which represent a single proved VM execution, which typically contains multiple - L2 blocks. -- **Facet** - implementation contract. The word comes from the EIP-2535. -- **Gas** - a unit that measures the amount of computational effort required to execute specific operations on the - ZKsync Era network. - -### L1 Smart contracts - -#### Diamond - -Technically, this L1 smart contract acts as a connector between Ethereum (L1) and ZKsync (L2). This contract checks the -validity proof and data availability, handles L2 <-> L1 communication, finalizes L2 state transition, and more. - -There are also important contracts deployed on the L2 that can also execute logic called _system contracts_. Using L2 -<-> L1 communication can affect both the L1 and the L2. - -#### DiamondProxy - -The main contract uses [EIP-2535](https://eips.ethereum.org/EIPS/eip-2535) diamond proxy pattern. It is an in-house -implementation that is inspired by the [mudgen reference implementation](https://github.com/mudgen/Diamond). It has no -external functions, only the fallback that delegates a call to one of the facets (target/implementation contract). So -even an upgrade system is a separate facet that can be replaced. - -One of the differences from the reference implementation is access freezability. Each of the facets has an associated -parameter that indicates if it is possible to freeze access to the facet. Privileged actors can freeze the **diamond** -(not a specific facet!) and all facets with the marker `isFreezable` should be inaccessible until the admin or the state transition manager unfreezes the diamond. Note that it is a very dangerous thing since the diamond proxy can freeze the upgrade -system and then the diamond will be frozen forever. - -#### DiamondInit - -It is a one-function contract that implements the logic of initializing a diamond proxy. It is called only once on the -diamond constructor and is not saved in the diamond as a facet. - -Implementation detail - function returns a magic value just like it is designed in -[EIP-1271](https://eips.ethereum.org/EIPS/eip-1271), but the magic value is 32 bytes in size. - -#### GettersFacet - -Separate facet, whose only function is providing `view` and `pure` methods. It also implements -[diamond loupe](https://eips.ethereum.org/EIPS/eip-2535#diamond-loupe) which makes managing facets easier. This contract -must never be frozen. - -#### AdminFacet - -Controls changing the privileged addresses such as admin and validators or one of the system parameters (L2 -bootloader bytecode hash, verifier address, verifier parameters, etc), and it also manages the freezing/unfreezing and -execution of upgrades in the diamond proxy. - -#### Governance - -This contract manages operations (calls with preconditions) for governance tasks. The contract allows for operations to -be scheduled, executed, and canceled with appropriate permissions and delays. It is used for managing and coordinating -upgrades and changes in all ZKsync Era governed contracts. - -Each upgrade consists of two steps: - -- Upgrade Proposal - The governor can schedule upgrades in two different manners: - - Fully transparent data. All implementation contracts and migration contracts are known to the community. The governor must wait - for the timelock to execute the upgrade. - - Shadow upgrade. The governor only shows the commitment for the upgrade. The upgrade can be executed only with security council - approval without timelock. -- Upgrade execution - perform the upgrade that was proposed. - -#### MailboxFacet - -The facet that handles L2 <-> L1 communication, an overview for which can be found in -[docs](https://era.zksync.io/docs/dev/developer-guides/bridging/l1-l2-interop.html). - -The Mailbox performs three functions: - -- L1 <-> L2 communication. -- Bridging native Ether to the L2. -- Censorship resistance mechanism (not yet implemented). - -L1 -> L2 communication is implemented as requesting an L2 transaction on L1 and executing it on L2. This means a user -can call the function on the L1 contract to save the data about the transaction in some queue. Later on, a validator can -process it on L2 and mark them as processed on the L1 priority queue. Currently, it is used for sending information from -L1 to L2 or implementing multi-layer protocols. - -_NOTE_: While user requests the transaction from L1, the initiated transaction on L2 will have such a `msg.sender`: - -```solidity - address sender = msg.sender; - if (sender != tx.origin) { - sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender); - } -``` - -where - -```solidity -uint160 constant offset = uint160(0x1111000000000000000000000000000000001111); - -function applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) { - unchecked { - l2Address = address(uint160(l1Address) + offset); - } -} -``` - -For most of the rollups the address aliasing needs to prevent cross-chain exploits that would otherwise be possible if -we simply reused the same L1 addresses as the L2 sender. In ZKsync Era address derivation rule is different from the -Ethereum, so cross-chain exploits are already impossible. However, ZKsync Era may add full EVM support in the future, so -applying address aliasing leave room for future EVM compatibility. - -The L1 -> L2 communication is also used for bridging ether. The user should include a `msg.value` when initiating a -transaction request on the L1 contract. Before executing a transaction on L2, the specified address will be credited -with the funds. To withdraw funds user should call `withdraw` function on the `L2EtherToken` system contracts. This will -burn the funds on L2, allowing the user to reclaim them through the `finalizeEthWithdrawal` function on the -`MailboxFacet`. - -L2 -> L1 communication, in contrast to L1 -> L2 communication, is based only on transferring the information, and not on -the transaction execution on L1. - -From the L2 side, there is a special zkEVM opcode that saves `l2ToL1Log` in the L2 batch. A validator will send all -`l2ToL1Logs` when sending an L2 batch to the L1 (see `ExecutorFacet`). Later on, users will be able to both read their -`l2ToL1logs` on L1 and _prove_ that they sent it. - -From the L1 side, for each L2 batch, a Merkle root with such logs in leaves is calculated. Thus, a user can provide -Merkle proof for each `l2ToL1Logs`. - -_NOTE_: For each executed L1 -> L2 transaction, the system program necessarily sends an L2 -> L1 log. To verify the -execution status user may use the `proveL1ToL2TransactionStatus`. - -_NOTE_: The `l2ToL1Log` structure consists of fixed-size fields! Because of this, it is inconvenient to send a lot of -data from L2 and to prove that they were sent on L1 using only `l2ToL1log`. To send a variable-length message we use -this trick: - -- One of the system contracts 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. - -#### L1 -> L2 Transaction filtering - -There is a mechanism for applying custom filters to the L1 -> L2 communication. It is achieved by having an address of -the `TransactionFilterer` contract in the `ZkSyncZKChainStorage`. If the filterer exists, it is being called in -the `Mailbox` facet with the tx details and has to return whether the transaction can be executed or not. The filterer -has to implement the `ITransactionFilterer` interface. The ones intended to use this feature, have to deploy the -contract that implements `ITransactionFilterer` and use `setTransactionFilterer` function of `AdminFacet` to set the -address of the transaction filterer. The same function called with `0` address will disable the filtering. - -#### ExecutorFacet - -A contract that accepts L2 batches, enforces data availability and checks the validity of zk-proofs. - -The state transition is divided into three stages: - -- `commitBatches` - check L2 batch timestamp, process the L2 logs, save data for a batch, and prepare data for zk-proof. -- `proveBatches` - validate zk-proof. -- `executeBatches` - finalize the state, marking L1 -> L2 communication processing, and saving Merkle tree with L2 logs. - -Each L2 -> L1 system log will have a key that is part of the following: - -```solidity -enum SystemLogKey { - L2_TO_L1_LOGS_TREE_ROOT_KEY, - PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, - PREV_BATCH_HASH_KEY, - CHAINED_PRIORITY_TXN_HASH_KEY, - NUMBER_OF_LAYER_1_TXS_KEY, - L2_DA_VALIDATOR_OUTPUT_HASH_KEY, - USED_L2_DA_VALIDATOR_ADDRESS_KEY, - EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY -} -``` - -When a batch is committed, we process L2 -> L1 system logs. Here are the invariants that are expected there: - -- In a given batch there will be either 7 or 8 system logs. The 8th log is only required for a protocol upgrade. -- There will be a single log for each key that is contained within `SystemLogKey` -- Three logs from the `L2_TO_L1_MESSENGER` with keys: -- `L2_TO_L1_LOGS_TREE_ROOT_KEY` -- `TOTAL_L2_TO_L1_PUBDATA_KEY` -- `STATE_DIFF_HASH_KEY` -- Two logs from `L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR` with keys: - - `PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY` - - `PREV_BATCH_HASH_KEY` -- Two or three logs from `L2_BOOTLOADER_ADDRESS` with keys: - - `CHAINED_PRIORITY_TXN_HASH_KEY` - - `NUMBER_OF_LAYER_1_TXS_KEY` - - `EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY` -- None logs from other addresses (may be changed in the future). - -#### Bridges - -Bridges are completely separate contracts from the Diamond. They are a wrapper for L1 <-> L2 communication on contracts -on both L1 and L2. Upon locking assets on one layer, a request is sent to mint these bridged assets on the other layer. -Upon burning assets on one layer, a request is sent to unlock them on the other. - -Unlike the native Ether bridging, all other assets can be bridged by the custom implementation relying on the trustless -L1 <-> L2 communication. - -##### L1ERC20Bridge - -The legacy implementation of the ERC20 token bridge. Works only with regular ERC20 tokens, i.e. not with -fee-on-transfer tokens or other custom logic for handling user balances. Only works for Era. - -- `deposit` - lock funds inside the contract and send a request to mint bridged assets on L2. -- `claimFailedDeposit` - unlock funds if the deposit was initiated but then failed on L2. -- `finalizeWithdrawal` - unlock funds for the valid withdrawal request from L2. - -##### L1AssetRouter - -The "standard" implementation of the ERC20 and WETH token bridge. Works only with regular ERC20 tokens, i.e. not with -fee-on-transfer tokens or other custom logic for handling user balances. - -- `deposit` - lock funds inside the contract and send a request to mint bridged assets on L2. -- `claimFailedDeposit` - unlock funds if the deposit was initiated but then failed on L2. -- `finalizeWithdrawal` - unlock funds for the valid withdrawal request from L2. - -The bridge also handles WETH token deposits between the two domains. It is designed to streamline and -enhance the user experience for bridging WETH tokens by minimizing the number of transactions required and reducing -liquidity fragmentation thus improving efficiency and user experience. - -This contract accepts WETH deposits on L1, unwraps them to ETH, and sends the ETH to the L2 WETH bridge contract, where -it is wrapped back into WETH and delivered to the L2 recipient. - -Thus, the deposit is made in one transaction, and the user receives L2 WETH that can be unwrapped to ETH. - -##### L2SharedBridge - -The L2 counterpart of the L1 Shared bridge. - -- `withdraw` - initiate a withdrawal by burning funds on the contract and sending a corresponding message to L1. -- `finalizeDeposit` - finalize the deposit and mint funds on L2. - -For WETH withdrawals, the contract receives ETH from the L2 WETH bridge contract, wraps it into WETH, and sends the WETH to -the L1 recipient. - -#### ValidatorTimelock - -An intermediate smart contract between the validator EOA account and the ZKsync smart contract. Its primary purpose is -to provide a trustless means of delaying batch execution without modifying the main ZKsync contract. ZKsync actively -monitors the chain activity and reacts to any suspicious activity by freezing the chain. This allows time for -investigation and mitigation before resuming normal operations. - -It is a temporary solution to prevent any significant impact of the validator hot key leakage, while the network is in -the Alpha stage. - -This contract consists of four main functions `commitBatches`, `proveBatches`, `executeBatches`, and `revertBatches`, -that can be called only by the validator. - -When the validator calls `commitBatches`, the same calldata will be propagated to the ZKsync contract (`DiamondProxy` -through `call` where it invokes the `ExecutorFacet` through `delegatecall`), and also a timestamp is assigned to these -batches to track the time these batches are committed by the validator to enforce a delay between committing and -execution of batches. Then, the validator can prove the already committed batches regardless of the mentioned timestamp, -and again the same calldata (related to the `proveBatches` function) will be propagated to the ZKsync contract. After, -the `delay` is elapsed, the validator is allowed to call `executeBatches` to propagate the same calldata to ZKsync -contract. - -### L2 specifics - -#### Deployment - -The L2 deployment process is different from Ethereum. - -In L1, the deployment always goes through two opcodes `create` and `create2`, each of which provides its address -derivation. The parameter of these opcodes is the so-called "init bytecode" - a bytecode that returns the bytecode to be -deployed. This works well in L1 but is suboptimal for L2. - -In the case of L2, there are also two ways to deploy contracts - `create` and `create2`. However, the expected input -parameters for `create` and `create2` are different. It accepts the hash of the bytecode, rather than the full bytecode. -Therefore, users pay less for contract creation and don't need to send the full contract code by the network upon -deploys. - -A good question could be, _how does the validator know the preimage of the bytecode hashes to execute the code?_ Here -comes the concept of factory dependencies! Factory dependencies are a list of bytecode hashes whose preimages were shown -on L1 (data is always available). Such bytecode hashes can be deployed, others - no. Note that they can be added to the -system by either L2 transaction or L1 -> L2 communication, where you can specify the full bytecode and the system will -mark it as known and allow you to deploy it. - -Besides that, due to the bytecode differences for L1 and L2 contracts, address derivation is different. This applies to -both `create` and `create2` and means that contracts deployed on the L1 cannot have a collision with contracts deployed -on the L2. Please note that EOA address derivation is the same as on Ethereum. - -Thus: - -- L2 contracts are deployed by bytecode hash, not by full bytecode -- Factory dependencies - list of bytecode hashes that can be deployed on L2 -- Address derivation for `create`/`create2` on L1 and L2 is different diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..bda9695ce --- /dev/null +++ b/docs/README.md @@ -0,0 +1,64 @@ +# ZK Stack contracts specs + +The order of the files here only roughly represents the order of reading. A lot of topics are intertwined, so it is recommended to read everything first to have a complete picture and then refer to specific documents for more details. + +- [Glossary](./glossary.md) +- [Overview](./overview.md) +- Contracts of an individual chain + - [ZK Chain basics](./settlement_contracts/zkchain_basics.md) + - Data availability + - [Custom DA support](./settlement_contracts/data_availability/custom_da.md) + - [Rollup DA support](./settlement_contracts/data_availability/rollup_da.md) + - [Standard pubdata format](./settlement_contracts/data_availability/standard_pubdata_format.md) + - [State diff compression v1 spec](./settlement_contracts/data_availability/state_diff_compression_v1_spec.md) + - L1->L2 transaction handling + - [Processing of L1->L2 transactions](./settlement_contracts/priority_queue/processing_of_l1->l2_txs.md) + - [Priority queue](./settlement_contracts/priority_queue/priority-queue.md) + - Consensus + - [Consensus Registry](./consensus/consensus-registry.md) +- Chain Management + - [Chain type manager](./chain_management/chain_type_manager.md) + - [Admin role](./chain_management/admin_role.md) + - [Chain genesis](./chain_management/chain_genesis.md) + - [Standard Upgrade process](./chain_management/upgrade_process.md) +- Bridging + - Bridgehub + - [Overview of the bridgehub functionality](./bridging/bridgehub/overview.md) + - [Asset Router](./bridging/asset_router/overview.md) +- L2 System Contracts + - [System contracts bootloader description](./l2_system_contracts/system_contracts_bootloader_description.md) + - [Batches and blocks on ZKsync](./l2_system_contracts/batches_and_blocks_on_zksync.md) + - [Elliptic curve precompiles](./l2_system_contracts/elliptic_curve_precompiles.md) + - [ZKsync fee model](./l2_system_contracts/zksync_fee_model.md) +- Gateway + - [General overview](./gateway/overview.md) + - [Chain migration](./gateway/chain_migration.md) + - [L1->L3 messaging via gateway](./gateway/messaging_via_gateway.md) + - [L3->L1 messaging via gateway](./gateway/nested_l3_l1_messaging.md) + - [Gateway protocol versioning](./gateway/gateway_protocol_upgrades.md) + - [DA handling on Gateway](./gateway/gateway_da.md) +- Upgrade history + - [Gateway upgrade diff](./upgrade_history/gateway_upgrade/gateway_diff_review.md) + - [Gateway upgrade process](./upgrade_history/gateway_upgrade/upgrade_process.md) + +![Reading order](./img/reading_order.png) + +## Repo structure + +The repository contains the following sections: + +- [gas-bound-caller](../gas-bound-caller) that contains `GasBoundCaller` utility contract implementation. You can read more about it in its README. +- [da-contracts](../da-contracts/). There are implementations for [DA validation](./settlement_contracts/data_availability/custom_da.md) contracts that should be deployed on L1 only. +- [l1-contracts](../l1-contracts/). Despite the legacy name, it contains contracts that are deployed both on L1 and on L2. This folder encompasses bridging, ZK chain contracts, the contracts for chain admin, etc. The name is historical due to the fact that these contracts were usually deployed on L1 only. However with Gateway, settlement and bridging-related contracts will be deployed on both EVM and eraVM environment. Also, bridging has been unified between L1 and L2 in many places and so keeping everything in one project allows to avoid code duplication. +- [l2-contracts](../l2-contracts/). Contains contracts that are deployed only on L2. +- [system-contracts](../system-contracts/). Contains system contracts or predeployed L2 contracts. + +## For auditors: Invariants/tricky places to look out for + +This section is for auditors of the codebase. It includes some of the important invariants that the system relies on and which if broken could have bad consequences. + +- Assuming that the accepting CTM is correct & efficient, the L1→GW part of the L1→GW→L3 transaction never fails. It is assumed that the provided max amount for gas is always enough for any transaction that can realistically come from L1. +- GW → L1 migration never fails. If it is possible to get into a state where the migration is not possible to finish, then the chain is basically lost. There are some exceptions where for now it is the expected behavior. (check out the “Migration invariants & protocol upgradability” section) +- The general consistency of chains when migration between different settlement layers is done. Including the feasibility of emergency upgrades, etc. I.e. whether the whole system is thought-through. +- Preimage attacks in the L3→L1 tree, we apply special prefixes to ensure that the tree structure is fixed, i.e. all logs are 88 bytes long (this is for backwards compatibility reasons). For batch leaves and chain id leaves we use special prefixes. +- Data availability guarantees. Whether rollup users can always restore all their storage slots, etc. An example of a potential tricky issue can be found in “Security notes for Gateway-based rollups” [in this document](./gateway/gateway_da.md). diff --git a/docs/bridging/asset_router/asset_router.md b/docs/bridging/asset_router/asset_router.md new file mode 100644 index 000000000..99f678f58 --- /dev/null +++ b/docs/bridging/asset_router/asset_router.md @@ -0,0 +1,47 @@ +# AssetRouters (L1/L2) and NativeTokenVault + +[back to readme](../../README.md) + +The main job of the asset router is to be the central point of coordination for bridging. All crosschain token bridging is done between asset routers only and once the message reaches asset router, it then routes it to the corresponding asset handler. + +In order to make this easier, all L2 chains have the asset router located on the same address on every chain. It is `0x10003` and it is pre-deployed contract. More on how it is deployed can be seen in the [Chain Genesis](../../chain_management/chain_genesis.md) section. + +The endgame is to have L1 asset router have the same functionality as the L2 one. This is not the case yet, but some progress has been made: L2AssetRouter can now bridge L2-native assets to L1, from which it could be bridged to other chains in the ecosystem. + +The specifics of the L2AssetRouter is the need to interact with the previously deployed L2SharedBridgeLegacy if it was already present. It has less “rights” than the L1AssetRouter: at the moment it is assumed that all asset deployment trackers are from L1, the only way to register an asset handler on L2 is to make an L1→L2 transaction. + +> Note, that today registering new asset deployment trackers will be permissioned, but the plan is to make it permissionless in the future + +The specifics of the L1AssetRouter come from the need to be backwards compatible with the old L1SharedBridge. Yes, it will not share the same storage, but it will inherit the need to be backwards compatible with the current SDK. Also, L1AssetRouter needs to facilitate L1-only operations, such as recovering from failed deposits. + +Also, L1AssetRouter is the only base token bridge contract that can participate in initiation of cross chain transactions via the bridgehub. This will change in the future with the support of interop. + +### L1Nullifier + +While the endgoal is to unify L1 and L2 asset routers, in reality, it may not be that easy: while L2 asset routers get called by L1→L2 transactions, L1 ones don't and require manual finalization of transactions, which involves proof verification, etc. To move this logic outside of the L1AssetRouter, it was moved into a separate L1Nullifier contract. + +_This is the contract the previous L1SharedBridge will be upgraded to, so it should have the backwards compatible storage._ + +### NativeTokenVault (L1/L2) + +NativeTokenVault is an asset handler that is available on all chains and is also predeployed. It is provides the functionality of the most basic bridging: locking funds on one chain and minting the bridged equivalent on the other one. On L2 chains NTV is predeployed at the `0x10004` address. + +The L1 and L2 versions of the NTV are almost identical in functionality, the main differences come from the differences of the deployment functionality in L1 and L2 envs, where the former uses standard CREATE2 and the latter uses low level calls to `CONTRACT_DEPLOYER`system contract. + +Also, the L1NTV has the following specifics: + +- It operates the `chainBalance` mapping, ensuring that the chains do not go beyond their balances. +- It allows recovering from failed L1→L2 transfers. +- It needs to both be able to retrieve funds from the former L1SharedBridge (now this contract has L1Nullifier in its place), but also needs to support the old SDK that gives out allowance to the “l1 shared bridge” value returned from the API, i.e. in our case this is will the L1AssetRouter. + +### L2SharedBridgeLegacy + +L2AssetRouter has to be pre-deployed onto a specific address. The old L2SharedBridge will be upgraded to L2SharedBridgeLegacy contract. The main purpose of this contract is to ensure compatibility with the incoming deposits and re-route them to the shared bridge. + +This contract is never deployed for new chains. + +### Summary + +![image.png](./img/bridge_contracts.png) + +> New bridge contracts diff --git a/docs/bridging/asset_router/img/bridge_contracts.png b/docs/bridging/asset_router/img/bridge_contracts.png new file mode 100644 index 000000000..f3f6802cd Binary files /dev/null and b/docs/bridging/asset_router/img/bridge_contracts.png differ diff --git a/docs/bridging/asset_router/img/custom_asset_handler_registration.png b/docs/bridging/asset_router/img/custom_asset_handler_registration.png new file mode 100644 index 000000000..a57e69f92 Binary files /dev/null and b/docs/bridging/asset_router/img/custom_asset_handler_registration.png differ diff --git a/docs/bridging/asset_router/overview.md b/docs/bridging/asset_router/overview.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/bridging/bridgehub/img/L1_L2_tx_processing_on_L2.png b/docs/bridging/bridgehub/img/L1_L2_tx_processing_on_L2.png new file mode 100644 index 000000000..cfe75d5cc Binary files /dev/null and b/docs/bridging/bridgehub/img/L1_L2_tx_processing_on_L2.png differ diff --git a/docs/bridging/bridgehub/img/gateway_architecture.png b/docs/bridging/bridgehub/img/gateway_architecture.png new file mode 100644 index 000000000..a9302ec7e Binary files /dev/null and b/docs/bridging/bridgehub/img/gateway_architecture.png differ diff --git a/docs/bridging/bridgehub/img/requestL2TransactionDirect.png b/docs/bridging/bridgehub/img/requestL2TransactionDirect.png new file mode 100644 index 000000000..95621fb7b Binary files /dev/null and b/docs/bridging/bridgehub/img/requestL2TransactionDirect.png differ diff --git a/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_depositEthToUSDC.png b/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_depositEthToUSDC.png new file mode 100644 index 000000000..12f2f116c Binary files /dev/null and b/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_depositEthToUSDC.png differ diff --git a/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_token.png b/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_token.png new file mode 100644 index 000000000..6cc290fde Binary files /dev/null and b/docs/bridging/bridgehub/img/requestL2TransactionTwoBridges_token.png differ diff --git a/docs/bridging/bridgehub/overview.md b/docs/bridging/bridgehub/overview.md new file mode 100644 index 000000000..54067fb0f --- /dev/null +++ b/docs/bridging/bridgehub/overview.md @@ -0,0 +1,243 @@ +# BridgeHub & Asset Routers + +[back to readme](../../README.md) + +## Bridgehub as the main chain registry + +Bridgehub is the most important contract in the system, that stores: + +- A mapping from chainId to chains address +- A mapping from chainId to the CTM it belongs to. +- A mapping from chainId to its base token (i.e. the token that is used for paying fees) +- etc + +> Note sure what CTM is? Check our the [overview](../../settlement_contracts/zkchain_basics.md) for contracts for settlement layer. + +Overall, it is the main registry for all the contracts. Note, that a clone of Bridgehub is also deployed on each L2 chain, but this clone is only used on settlement layers. All the in all, the architecture of the entire ecosystem can be seen below: + +![Contracts](./img/gateway_architecture.png) + +> This document will not cover how ZK Gateway works, you can check it out in [a separate doc](../../gateway/overview.md). + +## Asset router as the main asset bridging entrypoint + +The main entry for passing value between chains is the AssetRouter, it is responsible for facilitating bridging between multiple asset types. To read more in detail on how it works, please refer to custom [asset bridging documentation](../asset_router/overview.md). + +For the purpose of this document, it is enough to treat the Asset Router as a blackbox that is responsible for processing escrowing funds on the source chain and minting them on the destination chain. + +> For those that are aware of the [previous ZKsync architecture](https://github.com/code-423n4/2024-03-zksync/blob/main/docs/Smart%20contract%20Section/L1%20ecosystem%20contracts.md), its role is similar to L1SharedBridge that we had before. Note, however, that it is a different contract with much enhanced functionality. Also, note that the L1SharedBridge will NOT be upgraded to the L1AssetRouter. For more details about migration, please check out [the migration doc](../../upgrade_history/gateway_upgrade/gateway_diff_review.md). + +### Handling base tokens + +On L2, _a base token_ (not to be consfused with a _native token_, i.e. an ERC20 token with a main contract on the chain) is the one that is used for `msg.value` and it is managed at `L2BaseToken` system contract. We need its logic to be strictly defined in `L2BaseToken`, since the base asset is expected to behave the exactly the same as ether on EVM. For now this token contract does not support base minting and burning of the asset, nor further customization. + +In other words, in the current release base assets can only be transferred through `msg.value`. They can also only be minted when they are backed 1-1 on L1. + +## L1→L2 communication via `Bridgehub.requestL2TransactionDirect` + +L1→L2 communication allows users on L1 to create a request for a transaction to happen on L2. This is the primary censorship resistance mechanism. If you are interested, you can read more on L1→L2 communications [here](../../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md), but for now just understanding that L1→L2 communication allows to request transactions to happen on L2 is enough. + +The L1→L2 communication is also the only way to mint a base asset at the moment. Fees to the operator as well as `msg.value` will be minted on `L2BaseToken` after the corresponding L1→L2 tx has been processed. + +To request an L1→L2 transaction, the `BridgeHub.requestL2TransactionDirect` function needs to be invoked. The user should pass the struct with the following parameters: + +```solidity +struct L2TransactionRequestDirect { + uint256 chainId; + uint256 mintValue; + address l2Contract; + uint256 l2Value; + bytes l2Calldata; + uint256 l2GasLimit; + uint256 l2GasPerPubdataByteLimit; + bytes[] factoryDeps; + address refundRecipient; +} +``` + +Most of the params are self-explanatory & replicate the logic of ZKsync Era. The only non-trivial fields are: + +- `mintValue` is the total amount of the base tokens that should be minted on L2 as the result of this transaction. The requirement is that `request.mintValue >= request.l2Value + request.l2GasLimit * derivedL2GasPrice(...)`, where `derivedL2GasPrice(...)` is the gas price to be used by this L1→L2 transaction. The exact price is defined by the ZKChain. + +Here is a quick guide on how this transaction is routed through the bridgehub. + +1. The bridgehub retrieves the `baseTokenAssetId` of the chain with the corresponding `chainId` and calls `L1AssetRouter.bridgehubDepositBaseToken` method. The `L1AssetRouter` will then use standard token depositing mechanism to burn/escrow the respective amount of the `baseTokenAssetId`. You can read more about it in [the asset router doc](../asset_router/overview.md). This step ensures that the baseToken will be backed 1-1 on L1. + +2. After that, it just routes the corresponding call to the ZKChain with the corresponding `chainId` . It is now the responsibility of the ZKChain to validate that the transaction is correct and can be accepted by it. This validation includes, but not limited to: + + - The fact that the user paid enough funds for the transaction (basically `request.l2GasLimit * derivedL2GasPrice(...) + request.l2Value >= request.mintValue`. + - The fact the transaction is always executable (the `request.l2GasLimit` is not high enough). + - etc. + +3. After the ZKChain validates the tx, it includes it into its priority queue. Once the operator executes this transaction on L2, the `mintValue` of the baseToken will be minted on L2. The `derivedL2GasPrice(...) * gasUsed` will be given to the operator’s balance. The other funds can be routed either of the following way: + +If the transaction is successful, the `request.l2Value` will be minted on the `request.l2Contract` address (it can potentially transfer these funds within the transaction). The rest are minted to the `request.refundRecipient` address. In case the transaction is not successful, all of the base token will be minted to the `request.refundRecipient` address. These are the same rules as for the ZKsync Era. + +**_Diagram of the L1→L2 transaction flow on L1 for direct user calls, the baseToken can be ETH or an ERC20:_** + +![requestL2TransactionDirect (ETH) (2).png](./img/requestL2TransactionDirect.png) + +**_Diagram of the L1→L2 transaction flow on L2 (it is the same regardless of the baseToken):_** + +![requestL2TransactionTwoBridges](./img/requestL2TransactionTwoBridges_token.png) + +![L1-_L2 tx processing on L2.png](./img/L1_L2_tx_processing_on_L2.png) + +### Limitations of custom base tokens in the current release + +ZKsync Era uses ETH as a base token. Upon creation of an ZKChain other chains may want to use their own custom base tokens. Note, that for the current release all the possible base tokens are whitelisted. The other limitation is that all the base tokens must be backed 1-1 on L1 as well as they are solely implemented with `L2BaseToken` contract. In other words: + +- No custom logic is allowed on L2 for base tokens +- Base tokens can not be minted on L2 without being backed by the corresponding L1 amount. + +If someone wants to build a protocol that mints base tokens on L2, the option for now is to “mint” an infinite amount of those on L1, deposit on L2 and then give those out as a way to “mint”. We will update this in the future. + +## General architecture and initialization of SharedBridge for a new ZKChain + +Once the chain is created, its L2AssetRouter will be automatically deployed upon genesis. You can read more about it in the [Chain creation flow](../../chain_management/chain_genesis.md). + +## `requestL2TransactionTwoBridges` + +`L1AssetRouter` is used as the main "glue" for value bridging across chains. Whenever a token that is not native needs to be bridged between two chains an L1<>L2 transaction out of the name of an AssetRouter needs to be performed. For more details, check out the [asset router documentation](../asset_router/overview.md). But for this section it is enough to understand that we need to somehow make a transaction out of the name of `L1AssetRouter` to its L2 counterpart to deliver the message about certain amount of asset being bridged. + +> In the next paragraphs we will often refer to `L1AssetRouter` as performing something. It is good enough for understanding of how bridgehub functionality works. Under the hood though, it mainly serves as common entry that calls various asset handlers that are chosen based on asset id. You can read more about it in the [asset router documentation](../asset_router/asset_router.md). + +Let’s say that a ZKChain has ETH as its base token. Let’s say that the depositor wants to bridge USDC to that chain. We can not use `BridgeHub.requestL2TransactionDirect`, because it only takes base token `mintValue` and then starts an L1→L2 transaction rightaway out of the name of the user and not the `L1AssetRouter`. + +We need some way to atomically deposit both ETH and USDC to the shared bridge + start a transaction from `L1AssetRouter`. For that we have a separate function on `Bridgehub`: `BridgeHub.requestL2TransactionTwoBridges`. The reason behind the name “two bridges” is a bit historical: the transaction supposed compose to do actions with two bridges: the bridge responsible for base tokens and the second bridge responsible for any other token. + +Note, however, that only `L1AssetRouter` can be used to bridge base tokens. And the role of the second bridge can be played by any contract that supports the protocol desrcibed below. + +When calling `BridgeHub.requestL2TransactionTwoBridges` the following struct needs to be provided: + +```solidity +struct L2TransactionRequestTwoBridgesOuter { + uint256 chainId; + uint256 mintValue; + uint256 l2Value; + uint256 l2GasLimit; + uint256 l2GasPerPubdataByteLimit; + address refundRecipient; + address secondBridgeAddress; + uint256 secondBridgeValue; + bytes secondBridgeCalldata; +} +``` + +The first few fields are the same as for the simple L1→L2 transaction case. However there are three new fields: + +- `secondBridgeAddress` is the address of the bridge (or contract in general) which will need to perform the L1->L2 transaction. In this case it should be the same `L1AssetRouter` +- `secondBridgeValue` is the `msg.value` to be sent to the bridge which is responsible for the asset being deposited (in this case it is `L1AssetRouter` ). This can be used to deposit ETH to ZKChains that have base token that is not ETH. +- `secondBridgeCalldata` is the data to pass to the second contract. `L1AssetRouter` supports multiple formats of calldata, the list can be seen in the `bridgehubDeposit` function of the `L1AssetRouter`. + +The function will do the following: + +#### L1 + +1. It will deposit the `request.mintValue` of the ZKChain’s base token the same way as during a simple L1→L2 transaction. These funds will be used for funding the `l2Value` and the fee to the operator. +2. It will call the `secondBridgeAddress` (`L1AssetRouter`) once again and this time it will deposit the funds to the `L1AssetRouter`, but this time it will be deposit not to pay the fees, but rather for the sake of bridging the desired token. + +This call will return the parameters to call the l2 contract with (the address of the L2 bridge counterpart, the calldata and factory deps to call it with). 3. After the BridgeHub will call the ZKChain to add the corresponding L1→L2 transaction to the priority queue. 4. The BridgeHub will call the `SharedBridge` once again so that it can remember the hash of the corresponding deposit transaction. [This is needed in case the deposit fails](#claiming-failed-deposits). + +#### L2 + +1. After some time, the corresponding L1→L2 is created. +2. The L2AssetRouter will receive the message and re-route it to the asset handler of the bridged token. To read more about how it works, check out the [asset router documentation](../asset_router/overview.md). + +**_Diagram of a depositing ETH onto a chain with USDC as the baseToken. Note that some contract calls (like `USDC.transferFrom` are omitted for the sake of consiceness):_** + +![requestL2TransactionTwoBridges (SharedBridge) (1).png](./img/requestL2TransactionTwoBridges_depositEthToUSDC.png) + +## Generic usage of `BridgeHub.requestL2TransactionTwoBridges` + +`L1AssetRouter` is the only bridge that can handle base tokens. However, the `BridgeHub.requestL2TransactionTwoBridges` could be used by `secondBridgeAddress` on L1. A notable example of how it is done is how our [CTMDeploymentTracker](../../../l1-contracts/contracts/bridgehub/CTMDeploymentTracker.sol) uses it to register the correct CTM address on Gateway. You can read more about how Gateway works in [its documentation](../../gateway/overview.md). + +Let’s do a quick recap on how it works: + +When calling `BridgeHub.requestL2TransactionTwoBridges` the following struct needs to be provided: + +```solidity +struct L2TransactionRequestTwoBridgesOuter { + uint256 chainId; + uint256 mintValue; + uint256 l2Value; + uint256 l2GasLimit; + uint256 l2GasPerPubdataByteLimit; + address refundRecipient; + address secondBridgeAddress; + uint256 secondBridgeValue; + bytes secondBridgeCalldata; +} +``` + +- `secondBridgeAddress` is the address of the L1 contract that needs to perform the L1->L2 transaction. +- `secondBridgeValue` is the `msg.value` to be sent to the `secondBridgeAddress`. +- `secondBridgeCalldata` is the data to pass to the `secondBridgeAddress`. This can be interpreted any way it wants. + +1. Firstly, the Bridgehub will deposit the `request.mintValue` the same way as during a simple L1→L2 transaction. These funds will be used for funding the `l2Value` and the fee to the operator. +2. After that, the `secondBridgeAddress.bridgehubDeposit` with the following signature is called + +```solidity +struct L2TransactionRequestTwoBridgesInner { + // Should be equal to a constant `keccak256("TWO_BRIDGES_MAGIC_VALUE")) - 1` + bytes32 magicValue; + // The L2 contract to call + address l2Contract; + // The calldata to call it with + bytes l2Calldata; + // The factory deps to call it with + bytes[] factoryDeps; + // Just some 32-byte value that can be used for later processing + // It is called `txDataHash` as it *should* be used as a way to facilitate + // reclaiming failed deposits. + bytes32 txDataHash; +} + +function bridgehubDeposit( + uint256 _chainId, + // The actual user that does the deposit + address _prevMsgSender, + // The msg.value of the L1->L2 transaction to be created + uint256 _l2Value, + // Custom bridge-specific data + bytes calldata _data +) external payable returns (L2TransactionRequestTwoBridgesInner memory request); +``` + +Now the job of the contract will be to “validate” whether they are okay with the transaction to come. For instance, the `CTMDeploymentTracker` checks that the `_prevMsgSender` is the owner of `CTMDeploymentTracker` and has the necesasry rights to perform the transaction out of the name of it. + +Ultimately, the correctly processed `bridgehubDeposit` function basically grants `BridgeHub` the right to create an L1→L2 transaction out of the name of the `secondBridgeAddress`. Since it is so powerful, the first returned value must be a magical constant that is equal to `keccak256("TWO_BRIDGES_MAGIC_VALUE")) - 1`. The fact that it was a somewhat non standard signature and a struct with the magical value is the major defense against “accidental” approvals to start a transaction out of the name of an account. + +Aside from the magical constant, the method should also return the information an L1→L2 transaction will start its call with: the `l2Contract` , `l2Calldata`, `factoryDeps`. It also should return the `txDataHash` field. The meaning `txDataHash` will be needed in the next paragraphs. But generally it can be any 32-byte value the bridge wants. + +1. After that, an L1→L2 transaction is invoked. Note, that the “trusted” `L1AssetRouter` has enforced that the baseToken was deposited correctly (again, the step (1) can _only_ be handled by the `L1AssetRouter`), while the second bridge can provide any data to call its L2 counterpart with. +2. As a final step, following function is called: + +```solidity +function bridgehubConfirmL2Transaction( + // `chainId` of the ZKChain + uint256 _chainId, + // the same value that was returned by `bridgehubDeposit` + bytes32 _txDataHash, + // the hash of the L1->L2 transaction + bytes32 _txHash +) external; +``` + +This function is needed for whatever actions are needed to be done after the L1→L2 transaction has been invoked. + +On `L1AssetRouter` it is used to remember the hash of each deposit transaction, so that later on, the funds could be returned to user if the `L1->L2` transaction fails. The `_txDataHash` is stored so that the whenever the users will want to reclaim funds from a failed deposit, they would provide the token and the amount as well as the sender to send the money to. + +## Claiming failed deposits + +In case a deposit fails, the `L1AssetRouter` allows users to recover the deposited funds by providing a proof that the corresponding transaction indeed failed. The logic is the same as in the current Era implementation. + +## Withdrawing funds from L2 + +Funds withdrawal is a similar way to how it is done currently on Era. + +The user needs to call the `L2AssetRouter.withdraw` function on L2, while providing the token they want to withdraw. This function would then calls the corresponding L2 asset handler and ask him to burn the funds. We expand a bit more about it in the [asset router documentation](../asset_router/overview.md). + +Note, however, that it is not the way to withdraw base token. To withdraw base token, `L2BaseToken.withdraw` needs to be called. + +After the batch with the withdrawal request has been executed, the user can finalize the withdrawal on L1 by calling `L1AssetRouter.finalizeWithdrawal`, where the user provides the proof of the corresponding withdrawal message. diff --git a/docs/cab/SDK_compatibility.md b/docs/cab/SDK_compatibility.md deleted file mode 100644 index c9f2ee10a..000000000 --- a/docs/cab/SDK_compatibility.md +++ /dev/null @@ -1,25 +0,0 @@ -# SDK and contracts compatibility - -## Shared Bridge upgrade - -| | Old sdk | Bridgehub SDK | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| deposit | L1ERC20 Bridge is called. This forwards the funds and the call to the depositLegacyErc20Bridge on the L1SharedBridge. We store depositAmount in ERC and depositHappened in SharedBridge. BH is called with requestL2TransactionDirect. | Bridgehub requestL2Transaction(Direct/TwoBridges) is called, this calls bridgehubDeposit, bridgehubDepositBaseToken. We store the txHash in depositHappened. | -| finalizeWithdrawal | L1ERC20 Bridge is called. We check isWithdrawalFinalized in L1ERC20Bridge. We forward to L1SharedBridge. We check isWithdrawalFinalized and for legacy Eth Era withdrawals the Mailbox as well. We store isWithdrawalFinalized in L1SharedBridge. | L1SharedBridge is called. We check for legacy token and Eth Era withdrawals that the txs has not been finalized on the L1ERC20 and the Mailbox. We store isWithdrawalFinalized. | -| claimFailedDeposit | L1ERC20 Bridge is called. We check and delete depositAmount. L1SharedBridge is called, with checkedInLegacyBridge flag = true. We check and delete depositHappened if we can, i.e. if the deposit is not a legacy deposit ( legacy deposits never touched the L1SharedBridge). | L1SharedBridge is called, we check depositHappened and delete it. | -| l2TokenAddress | L1ERC20 Bridge is called. | L1ERC20 Bridge is called. | -| L2 withdrawal | L1ERC20 Bridge is called | L1ERC20 Bridge is called | - -## Custom Asset Bridging upgrade - -We will finalize all legacy ( before the Bridgehub upgrade) withdrawals before the Custom Asset Bridging upgrade. This will cut complexity. - -Note: in the first version the finalizeDeposit call to the L2SharedBridge is not updated for NTV assets to keep the SDK backwards compatible. - -| | Old sdk | Bridgehub SDK | Custom Asset Bridging | -| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| deposit | L1ERC20 Bridge is called. This forwards the funds and the call to the depositLegacyErc20Bridge on the L1SharedBridge. We store depositAmount in ERC and depositHappened in SharedBridge. Funds are further forwarded to NTV ( todo: do this directly from ERC20Bridge), and NTV is called to store funds. BH is called with requestL2TransactionDirect. | Bridgehub calls L1SharedBridge, AssetData encoding and token changed, L1SharedBridge can parse both | Bridgehub calls L1SharedBridge, AssetData encoding and token changed, L1SharedBridge can parse both | -| finalizeWithdrawal | L1ERC20 Bridge is called. We check isWithdrawalFinalized in L1ERC20Bridge. We forward to L1SharedBridge. We check the withdrawal is not legacy before the BH upgrade. We store isWithdrawalFinalized in L1SharedBridge. | L1SharedBridge is called. We change token -> assetId. We check the withdrawal is not before the BH upgrade. We store isWithdrawalFinalized in L1SharedBridge. Forward to NTV to bridgeMint. | L1SharedBridge is called. We check the withdrawal is not before the BH upgrade. We store isWithdrawalFinalized in L1SharedBridge. Forward to NTV to bridgeMint. | -| claimFailedDeposit | L1ERC20 Bridge is called | L1SharedBridge is called | L1SharedBridge is called | -| l2TokenAddress | L1ERC20 Bridge is called | L1ERC20 Bridge is called | L1ERC20 Bridge is called | -| L2 withdrawal | L1ERC20 Bridge is called | L1SharedBridge is called | L1SharedBridge is called | diff --git a/docs/cab/asset-registration.png b/docs/cab/asset-registration.png deleted file mode 100644 index faec62f0d..000000000 Binary files a/docs/cab/asset-registration.png and /dev/null differ diff --git a/docs/cab/automatic-bridging.png b/docs/cab/automatic-bridging.png deleted file mode 100644 index c1d5d9195..000000000 Binary files a/docs/cab/automatic-bridging.png and /dev/null differ diff --git a/docs/cab/contracts-review-cab.md b/docs/cab/contracts-review-cab.md deleted file mode 100644 index 3fa46229c..000000000 --- a/docs/cab/contracts-review-cab.md +++ /dev/null @@ -1,78 +0,0 @@ -# Custom Asset Bridging - -## High-level Overview - -### Reason for changes - -The goal was to be build a modular bridge which separates the logic of L1<>L2 messaging from the holding of the asset. This enables bridging many custom tokens, assets which accrue value over time (like LRTs), WETH, and even custom assets like NFTs. - -This upgrade only contains the framework, the logic of the custom bridges can be developed by third parties. - -### Major changes - -In order to achieve it, we separated the liquidity managing logic from the Shared Bridge to `Asset Handlers`. The basic cases will be handled by `Native Token Vaults`, which are handling all of the standard `ERC20 tokens`, as well as `ETH`. - -### New concepts - -- AssetDeploymentTracker => contract that manages the deployment of asset handlers across chains. It is the contract that registers these asset handlers in the AssetRouters. -- AssetHandler => contract that manages liquidity (burns/mints, locks/unlocks) for specific token (or a set of them) -- assetId => identifier to track bridged assets across chains linked to specific asset handler. - -### Normal flow - -Assets Handlers are registered in the Routers based on their assetId. The assetId is used to identify the asset when bridging, it is sent with the cross-chain transaction data and Router routes the data to the appropriate Handler. If the asset handler is not registered in the L2 Router, then the L1->L2 bridging transaction will fail on the L2 (expect for NTV assets, see below). - -`assetId = keccak256(chainId, asset deployment tracker = msg.sender, additionalData)` - -Asset registration is handled by the AssetDeploymentTracker. It is expected that this contract is deployed on the L1. Registration can be permissionless depending on the Asset (e.g. the AssetHandler can be deployed on the chain at a predefined address, this can message the L1 ADT, which can then register the asset in the Router). Registering the L1 Handler in the L1 Router can be done via a direct function call from the L1 Deployment Tracker. Registration in the L2 Router is done indirectly via the L1 Router. - -![Asset Registration](./asset-registration.png) - -The Native Token Vault is a special case of the Asset Handler, as we want it to support automatic bridging. This means it should be possible to bridge a L1 token to an L2 without deploying the Token contract beforehand and without registering it in the L2 Router. For NTV assets, L1->L2 transactions where the AssetHandler is not registered will not fail, but the message will be automatically be forwarded to the L2NTV. Here the contract checks that the asset is indeed deployed by the L1NTV, by checking that the assetId contains the correct ADT address (note, for NTV assets the ADT is the NTV and the used address is the L2NTV address). If the assetId is correct, the token contract is deployed. - -![Automatic Bridge](./automatic-bridging.png) - -## Known Issues - -### storage layout - -L2SharedBridge will be a system contract, L2NativeTokenVault will replace it (the storage layout is still not yet backwards compatible) - -### bridgehubDeposit API change - -> /// @notice Allows bridgehub to acquire mintValue for L1->L2 transactions. - - /// @dev If the corresponding L2 transaction fails, refunds are issued to a refund recipient on L2. - function bridgehubDepositBaseToken( - uint256 _chainId, - bytes32 _assetId, - -Note, that the new SB is not compatible with both: - -- old Mailbox on Era -- old Bridgehub -- And vice versa. - -We need to either: - -- ensure that all 3 get upgraded at the same time. Upgrading BH and SB at the same time is feasible IMHO. But upgrading DP (Mailbox) in the same transaction may not be. -- have a concrete plan for such case. E.g. explicitly tell that the legacy deposits will stop working. In this case we need to check (at the very least visually) that the worst thing that can happen is just deposits not working and not some funds lost -- Add the corresponding legacy functions - -### Not allowing legacy withdrawals - -> require(!\_isEraLegacyEthWithdrawal(\_chainId, \_l2BatchNumber), "ShB: legacy eth withdrawal"); - -No method to finalize an old withdrawal. -We will manually finalize all legacy withdrawals before the upgrade, i.e. withdrawals that happened before the previous Bridgehub upgrade. - -### Custom Errors not implemented - -> require(expectedDepositAmount == \_depositAmount, "3T"); // The token has non-standard transfer logic - -Custom errors will be introduced for all contracts. - -## Migration plan - -- Bulkheads will need to be migrated (methods added) -- Tokens will have to be transferred (methods added) diff --git a/docs/chain_management/admin_role.md b/docs/chain_management/admin_role.md new file mode 100644 index 000000000..81585f748 --- /dev/null +++ b/docs/chain_management/admin_role.md @@ -0,0 +1,114 @@ +# Safe ChainAdmin management + +[back to readme](../README.md) + +While the ecosystem does a [decentralized trusted governance](https://blog.zknation.io/introducing-zk-nation/), each chain has its own Chain Admin. While the upgrade parameters are chosen by the governance, chain admin is still a powerful role and should be managed carefully. + +In this document we will explore what are the abilities of the ChainAdmin, how dangerous they are and how to mitigate potential issues. + +## General guidelines + +The system does not restrict in any way how the admin of the chain should be implemented. However special caution should be taken to keep it safe. + +The general guideline is that an admin of a ZK chain should be _at least_ a well-distributed multisig. Having it as an EOA is definitely a bad idea since having this address stolen can lead to [chain being permanently frozen](#setting-da-layer). + +Additional measures may be taken [to self-restrict](#proposed-modular-chainadmin-implementation) the ChainAdmin to ensure that some operations can be only done in safe fashion. + +Generally all the functionality of chain admin should be treated with maximal security and caution, and having hotkey separate roles in rare circuimstances, e.g. to call `setTokenMultiplier` in case of an ERC-20 based chain. + +## Chain Admin functionality + +### Setting validators for a chain + +The admin of a chain can call `ValidatorTimelock` on the settlement layer to add or remove validators, i.e. addresses that have the right to `commit`/`verify`/`execute` batches etc. + +The system is protected against malicious validators, they can never steal funds from users. However, this role is still relatively powerful: If the DA layer is not reliable, and a batch does get executed, the funds may be frozen. This is why the chains should be [cautious about DA layers that they use](#setting-da-layer). Note, that on L1 the `ValidatorTimelock` has 21h delay, while on Gateway this timelock will not be present. + +In case the malicious block has not been executed yet, it can be reverted. + +### Setting DA layer + +This is one of the most powerful settings that a chain can have: setting a custom DA layer. The dangers of doing this wrong are obvious: lack of proper data availability solution may lead to funds being frozen. (Note: that funds can never be _stolen_ due to ZKP checks of the VM execution). + +Sometimes, users may need assurances that a chain will never become frozen even under a malicious chain admin. A general though unstable approach is discussed [here](#proposed-modular-chainadmin-implementation), however this release comes with a solution specially tailored for rollups: the `isPermanentRollup` setting. + +#### `isPermanentRollup` setting + +Chain also exposes the `AdminFacet.makePermanentRollup` function. It will turn a chain into a permanent rollup, ensuring that DA validator pairs can be only set to values that are approved by decentralized governance to be used for rollups. + +This functionality is obviously dangerous in a sense that it is permanent and revokes the right of the chain to change its DA layer. On the other hand, it ensures perpetual safety for users. This is the option that ZKsync Era plans to use. + +This setting is preserved even when migrating to [gateway](../gateway/overview.md). If this setting was set while chain is on top of Gateway, and it migrates back to L1, it will keep this status, i.e. it is fully irrevocable. + +### `changeFeeParams` method + +This method allows to change how the fees are charged for priority operations. + +The worst impact of setting this value wrongly is having L1->L2 transactions underpriced. + +### `setTokenMultiplier` method + +This method allows to set the token multiplier, i.e. the ratio between the price of ETH and the price of the token. It will be used for L1->L2 priority transactions. + +Typically, `ChainAdmin`s of ERC20 chains will have a special hotkey responsible for calling this function to keep the price up to date. An example on how it is implemented in the current system can be seen [here](https://github.com/matter-labs/era-contracts/blob/aafee035db892689df3f7afe4b89fd6467a39313/l1-contracts/contracts/governance/ChainAdmin.sol#L23). + +The worst impact of setting this value wrongly is having L1->L2 transactions underpriced. + +### `setPubdataPricingMode` + +This method allows to set whether the pubdata price will be taken into account for priority operations. + +The worst impact of setting this value wrongly is having L1->L2 transactions underpriced. + +### `setTransactionFilterer` + +This method allows to set a transaction filterer, i.e. an additional validator for all incoming L1->L2 transactions. The worst impact is users' transactions being censored. + +### Migration to another settlement layer + +The upgrade can start migration of a chain to another settlement layer. Currently all the settlement layers are whitelisted, so generally this operation is harmless (except for the inconvenience in case the migration was unplanned). + +However, some caution needs to be applied to migrate properly as described in the section below. + +## Chain admin when migrating to gateway + +When a chain migrates to gateway, it provides the address of the new admin on L2. The following rules apply: + +- If a ZK chain has already been deployed on a settlement layer, its admin stays the same. +- If a ZK chain has not been deployed yet, then the new admin is set. + +The above means that in the current release the admin of the chain on the new settlement layer is "detached" from the admin on L1. It is the responsibility of the chain to set the L2 admin correctly: either it should have the same signers or, even better in the long run, put the aliased L1 admin to have most of the abilities inside the L2 chain admin. + +Since most of the Admin's functionality above are related to L1->L2 operations, the L1 chain admin will continue playing a crucial role even after the chain migrates to Gateway. However, some of the new functionality are relevant on the chain admin on the settlement layer only: + +- Managing DA +- Managing new validators +- It is the admin of the settlement layer that do migrations of chains + +As such, the choice of the L2 Admin is very important. Also, if the chain admin on the new settlement layer is not accessible (e.g. accidentally wrong address was chosen), the chain is lost: + +- No validators will be set +- The chain can not migrate back + +Overall **very special care** needs to be taken when selecting an admin for the migration to a new settlement layer. + +## Proposed modular `ChainAdmin` implementation + +> **Warning**. The proposed implementation here will likely **not** be used by the Matter Labs team for ZKsync Era due to the issues listed in the issues section. This code, however, is still in scope of the audit and may serve as a future basis of a more long term solution. + +In order to ensure that the architecture here flexible enough for future other chains to use, it uses a modular architecture to ensure that other chains could fit it to their needs. By default, this contract is not even `Ownable`, and anyone can execute transactions out of the name of it. In order to add new features such as restricting calling dangerous methods and access control, _restrictions_ should be added there. Each restriction is a contract that implements the `IRestriction` interface. The following restrictions have been implemented so far: + +- `AccessControlRestriction` that allows to specify which addresses can call which methods. In the case of Era, only the `DEFAULT_ADMIN_ROLE` will be able to call any methods. Other chains with non-ETH base token may need an account that would periodically call the L1 contract to update the ETH price there. They may create the `SET_TOKEN_MULTIPLIER_ROLE` role that is required to update the token price and give its rights to some hot private key. + +- `PermanentRestriction` that ensures that: + +a) This restriction could not be lifted, i.e. the chain admin of the chain must forever have it. Even if the address of the `ChainAdmin` changes, it ensures that the new admin has this restriction turned on. +b) It specifies the calldata this which certain methods can be called. For instance, in case a chain wants to keep itself permanently tied to certain DA, it will ensure that the only DA validation method that can be used is rollup. Some sort of decentralized governance could be chosen to select which DA validation pair corresponds to this DA method. + +The approach above does not only helps to protect the chain, but also provides correct information for chains that are present in our ecosystem. For instance, if a chain claims to perpetually have a certain property, having the `PermanentRestriction` as part of the chain admin can ensure all observers of that. + +### Issues and limitations + +Due to specifics of [migration to another settlement layers](#migration-to-another-settlement-layer) (i.e. that migrations do not overwrite the admin), maintaining the same `PermanentRestriction` becomes hard in case a restriction has been added on top of the chain admin inside one chain, but not the other. + +While very flexible, this modular approach should still be polished enough before recommending it as a generic solution for everyone. However, the provided new [ChainAdmin](../../l1-contracts/contracts/governance/ChainAdmin.sol) can still be helpful for new chains as with the `AccessControlRestriction` it provides a ready-to-use framework for role-based managing of the chain. Using `PermanentRestriction` for now is discouraged however. diff --git a/docs/chain_management/chain_genesis.md b/docs/chain_management/chain_genesis.md new file mode 100644 index 000000000..8431868a9 --- /dev/null +++ b/docs/chain_management/chain_genesis.md @@ -0,0 +1,72 @@ +# Creating new chains with BridgeHub + +[back to readme](../README.md) + +The main contract of the whole hyperchain ecosystem is called _`BridgeHub`_. It contains: + +- the registry from chainId to CTMs that is responsible for that chainId +- the base token for each chainId. +- the whitelist of CTMs +- the whitelist of tokens allowed to be `baseTokens` of chains. +- the whitelist of settlement layers +- etc + +BridgeHub is responsible for creating new STs. It is also the main point of entry for L1→L2 transactions for all the STs. Users won't be able to interact with STs directly, all the actions must be done through the BridgeHub, which will ensure that the fees have been paid and will route the call to the corresponding ST. One of the reasons it was done this way was to have the unified interface for all STs that will ever be included in the hyperchain ecosystem. + +To create a chain, the `BridgeHub.createNewChain` function needs to be called: + +```solidity +/// @notice register new chain. New chains can be only registered on Bridgehub deployed on L1. Later they can be moved to any other layer. +/// @notice for Eth the baseToken address is 1 +/// @param _chainId the chainId of the chain +/// @param _chainTypeManager the state transition manager address +/// @param _baseTokenAssetId the base token asset id of the chain +/// @param _salt the salt for the chainId, currently not used +/// @param _admin the admin of the chain +/// @param _initData the fixed initialization data for the chain +/// @param _factoryDeps the factory dependencies for the chain's deployment +function createNewChain( + uint256 _chainId, + address _chainTypeManager, + bytes32 _baseTokenAssetId, + // solhint-disable-next-line no-unused-vars + uint256 _salt, + address _admin, + bytes calldata _initData, + bytes[] calldata _factoryDeps +) external +``` + +BridgeHub will check that the CTM as well as the base token are whitelisted and route the call to the State + +![newChain (2).png](./img/create_new_chain.png) + +### Creation of a chain in the current release + +In the future, ST creation will be permissionless. A securely random `chainId` will be generated for each chain to be registered. However, generating 32-byte chainId is not feasible with the current SDK expectations on EVM and so for now chainId is of type `uint48`. And so it has to be chosen by the admin of `BridgeHub`. Also, for the current release we would want to avoid chains being able to choose their own initialization parameter to prevent possible malicious input. + +For this reason, there will be an entity called `admin` which is basically a hot key managed by us and it will be used to deploy new STs. + +So the flow for deploying their own ST for users will be the following: + +1. Users tell us that they want to deploy a ST with certain governance, CTM (we’ll likely allow only one for now), and baseToken. +2. Our server will generate a chainId not reserved by any other major chain and the `admin` will call the `BridgeHub.createNewChain` . This will call the `CTM.createNewChain` that will deploy the instance of the rollup as well as initialize the first transaction there — the system upgrade transaction needed to set the chainId on L2. + +After that, the ST is ready to be used. Note, that the admin of the newly created chain (this will be the organization that will manage this chain from now on) will have to conduct certain configurations before the chain [can be used securely](../chain_management/admin_role.md). + +## Built-in contracts and their initialization + +Each single ZK Chain has a set of the following contracts that, while not belong to kernel space, are built-in and provide important functionality: + +- Bridgehub (the source code is identical to the L1 one). The role of bridgehub is to facilitate cross chain transactions. It contains a mapping from chainId to the address of the diamond proxy of the chain. It is really used only on the L1 and Gateway, i.e. layers that can serve as a settlement layer. +- L2AssetRouter. The new iteration of the SharedBridge. +- L2NativeTokenVault. The Native token vault on L2. +- MessageRoot (the source code is identical to the L1 one). Similar to bridgehub, it facilitates cross-chain communication, but is practically unused on all chains except for L1/GW. + +To reuse as much code as possible from L1 and also to allow easier initialization, most of these contracts are not initialized as just part of the genesis storage root. Instead, the data for their initialization is part of the original diamondcut for the chain. In the same initial upgrade transaction when the chainId is initialized, these contracts are force-deployed and initialized also. An important part in it plays the new `L2GenesisUpgrade` contract, which is pre-deployed in a user-space contract, but it is delegate-called by the `ComplexUpgrader` system contract (already exists as part of genesis and existed before this upgrade). + +## Additional limitations for the current version + +In the current version creating new chains will not be permissionless. That is needed to ensure that no malicious input can be provided there. + +Also, since in the current release, there will be little benefits from shared liquidity, i.e. the there will be no direct ZKChain<>ZKChain transfers supported, as a measure of additional security we’ll also keep track of balances for each individual ZKChain and will not allow it to withdraw more than it has deposited into the system. diff --git a/docs/chain_management/chain_type_manager.md b/docs/chain_management/chain_type_manager.md new file mode 100644 index 000000000..26a01f604 --- /dev/null +++ b/docs/chain_management/chain_type_manager.md @@ -0,0 +1,70 @@ +# Chain Type Manager (CTM) + +[back to readme](../README.md) + +> If someone is already familiar with the [previous version](https://github.com/code-423n4/2024-03-zksync) of ZKsync architecture, this contract was previously known as "State Transition Manager (CTM)". + +Currently bridging between different zk rollups requires the funds to pass through L1. This is slow & expensive. + +The vision of seamless internet of value requires transfers of value to be _both_ seamless and trustless. This means that for instance different STs need to share the same L1 liquidity, i.e. a transfer of funds should never touch L1 in the process. However, it requires some sort of trust between two chains. If a malicious (or broken) rollup becomes a part of the shared liquidity pool it can steal all the funds. + +However, can two instances of the same zk rollup trust each other? The answer is yes, because no new additions of rollups introduce new trust assumptions. Assuming there are no bugs in circuits, the system will work as intended. + +How can two rollups know that they are two different instances of the same system? We can create a factory of such contracts (and so we would know that each new rollup created by this instance is correct one). But just creating correct contracts is not enough. Ethereum changes, new bugs may be found in the original system & so an instance that does not keep itself up-to-date with the upgrades may exploit some bug from the past and jeopardize the entire system. Just deploying is not enough. We need to constantly make sure that all STs are up to date and maintain whatever other invariants are needed for these STs to trust each other. + +Let’s define as _Chain Type Manager_ (CTM) \*\*as a contract that is responsible for the following: + +- It serves as a factory to deploy STs (new ZK chains) +- It is responsible for ensuring that all the STs deployed by it are up-to-date. + +Note, that this means that STs have a “weaker” governance. I.e. governance can only do very limited number of things, such as setting the validator. ST admin can not set its own upgrades and it can only “execute” the upgrade that has already been prepared by the CTM. + +In the long term vision STs deployment will be permissionless, however CTM will always remain the main point of trust and will have to be explicitly whitelisted by the decentralized governance of the entire ecosystem before its ST can get the access to the shared liquidity. + +## Configurability in the current release + +For now, only one CTM will be supported — the one that deploys instances of ZKsync Era, possibly using other DA layers. To read more about different DA layers, check out [this document](../settlement_contracts/data_availability/custom_da.md). + +The exact process of deploying & registering a ST can be [read here](./chain_genesis.md). Overall, each ST in the current release will have the following parameters: + +| ST parameter | Updatability | Comment | +| --------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| chainId | Permanent | Permanent identifier of the ST. Due to wallet support reasons, for now chainId has to be small (48 bits). This is one of the reasons why for now we’ll deploy STs manually, to prevent STs from having the same chainId as some another popular chain. In the future it will be trustlessly assigned as a random 32-byte value. | +| baseTokenAssetId | Permanent | Each ST can have their own custom base token (i.e. token used for paying the fees). It is set once during creation and can never be changed. Note, that we refer to and "asset id" here instead of an L1 address. To read more about what is assetId and how it works check out the document for [asset router](../bridging/asset_router/overview.md) | +| chainTypeManager | Permanent | The CTM that deployed the ST. In principle, it could be possible to migrate between CTMs (assuming both CTMs support that). However, in practice it may be very hard and as of now such functionality is not supported. | +| admin | By admin of ST | The admin of the ST. It has some limited powers to govern the chain. To read more about which powers are available to a chain admin and which precautions should be taken, check [out this document](../chain_management/admin_role.md) | +| validatorTimelock | CTM | For now, we want all the chains to use the same 21h timelock period before their batches are finalized. Only CTM can update the address that can submit state transitions to the rollup (that is, the validatorTimelock). | +| validatorTimelock.validator | By admin of ST | The admin of ST can choose who can submit new batches to the ValidatorTimelock. | +| priorityTx FeeParams | By admin of ST | The admin of a ZK chain can amend the priority transaction fee params. | +| transactionFilterer | By admin of ST | A chain may put an additional filter to the incoming L1->L2 transactions. This may be needed by a permissioned chain (e.g. a Validium bank-lile corporate chain). | +| DA validation / permanent rollup status | By admin of ST | A chain can decide which DA layer to use. You check out more about [safe DA management here](./admin_role.md) | +| executing upgrades | By admin of ST | While exclusively CTM governance can set the content of the upgrade, STs will typically be able to choose suitable time for them to actually execute it. In the current release, STs will have to follow our upgrades. | +| settlement layer | By admin of ST | The admin of the chain can enact migrations to other settlement layers. | + +> Note, that if we take a look at the access control for the corresponding functions inside the [AdminFacet](../../l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol), the may see that a lot of methods from above that are marked as "By admin of ST" could be in theory amended by the ChainTypeManager. However, this sort of action requires approval from decentralized governance. Also, in case of an urgent high risk situation, the decentralized governance might force upgrade the contract via CTM. + +## Upgradability in the current release + +In the current release, each chain will be an instance of ZKsync Era and so the upgrade process of each individual ST will be similar to that of ZKsync Era. + +1. Firstly, the governance of the CTM will publish the server (including sequencer, prover, etc) that support the new version . This is done offchain. Enough time should be given to various zkStack devs to update their version. +2. The governance of the CTM will publish the upgrade onchain by automatically executing the following three transactions: + + - `setChainCreationParams` ⇒ to ensure that new chains will be created with the version + - `setValidatorTimelock` (if needed) ⇒ to ensure that the new chains will use the new validator timelock right-away + - `setNewVersionUpgrade` ⇒ to save the upgrade information that each ST will need to follow to conduct the upgrade on their side. + +3. After that, each ChainAdmin can upgrade to the new version in suitable time for them. + +> Note, that while the governance does try to give the maximal possible time for chains to upgrade, the governance will typically put restrictions (aka deadlines) on the time by which the chain has to be upgraded. If the deadline is passed, the chain can not commit new batches until the upgrade is executed. + +### Emergency upgrade + +In case of an emergency, the [security council](https://blog.zknation.io/introducing-zk-nation/) has the ability to freeze the ecosystem and conduct an emergency upgrade. + +In case we are aware that some of the committed batches on an ST are dangerous to be executed, the CTM can call `revertBatches` on that ST. For faster reaction, the admin of the ChainTypeManager has the ability to do so without waiting for govenrnace approval that may take a lot of time. This action does not lead to funds being lost, so it is considered suitable for the partially trusted role of the admin of the ChainTypeManager. + +### Issues & caveats + +- If an ZK chain skips an upgrade (i.e. it has version X, it did not upgrade to `X + 1` and now the latest protocol version is `X + 2` there is no built-in way to upgrade). This team will require manual intervention from us to upgrade. +- The approach of calling `revertBatches` for malicious STs is not scalable (O(N) of the number of chains). The situation is very rare, so it is fine in the short term, but not in the long run. diff --git a/docs/chain_management/img/create_new_chain.png b/docs/chain_management/img/create_new_chain.png new file mode 100644 index 000000000..b71fecfeb Binary files /dev/null and b/docs/chain_management/img/create_new_chain.png differ diff --git a/docs/chain_management/upgrade_process.md b/docs/chain_management/upgrade_process.md new file mode 100644 index 000000000..8484c3ad4 --- /dev/null +++ b/docs/chain_management/upgrade_process.md @@ -0,0 +1,41 @@ +# Upgrade process document + +[back to readme](../README.md) + +## Intro + +This document assumes that you have understanding about [the structure](../settlement_contracts/zkchain_basics.md) on individual chains' L1 contracts. + +Upgrading the ecosystem of ZKChains is a complicated process. ZKSync is a complex ecosystem with many chains and contracts and each upgrade is unique, but there are some steps that repeat for most upgrades. These are mostly how we interact with the CTM, the diamond facets, the L1→L2 upgrade, how we update the verification keys. + +Where each upgrade consists of two parameters: + +- Facet cuts - change of the internal implementation of the diamond proxy +- Diamond Initialization - delegate call to the specified address wit`h specified data + +The second parameter is very powerful and flexible enough to move majority of upgrade logic there. + +## Upgrade structure + +Upgrade information is composed in the form of a [DiamondCutData](../../l1-contracts/contracts/state-transition/libraries/Diamond.sol#L75) struct. During the upgrade, the chain's DiamondProxy will delegateCall the `initAddress` with the provided `initCalldata`, while the facets that the `DiamondProxy` will be changed according to the `facetCuts`. This scheme is very powerful and it allows to change anything in the contract. However, we typically have a very specific set of changes that we need to do. To facilitate these, two contracts have been created: + +1. [BaseZkSyncUpgrade](../../l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol) - Generic template with function that can be useful for upgrades +2. [DefaultUpgrade](../../l1-contracts/contracts/upgrades/DefaultUpgrade.sol) - Default implementation of the `BaseZkSyncUpgrade`, contract that is most often planned to be used as diamond initialization when doing upgrades. + +> Note, that the Gateway upgrade will be more complex than the usual ones and so a similar, but separate [process](../upgrade_history/gateway_upgrade/upgrade_process.md) will be used for it. It will also use its own custom implementation of the `BaseZkSyncUpgrade`: [GatewayUpgrade](../../l1-contracts/contracts/upgrades/GatewayUpgrade.sol). + +### Protocol version + +For tracking upgrade versions on different networks (private testnet, public testnet, mainnet) we use protocol version, which is basically just a number denoting the deployed version. The protocol version is different from Diamond Cut `proposalId`, since `protocolId` only shows how much upgrade proposal was proposed/executed, but nothing about the content of upgrades, while the protocol version is needed to understand what version is deployed. + +In the [BaseZkSyncUpgrade](../../l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol) & [DefaultUpgrade](../../l1-contracts/contracts/upgrades/DefaultUpgrade.sol) we allow to arbitrarily increase the proposal version while upgrading a system, but only increase it. We are doing that since we can skip some protocol versions if for example found a bug there (but it was deployed on another network already). + +## Protocol upgrade transaction + +During upgrade, we typically need not only update the L1 contracts, but also the L2 ones. This is achieved by creating an upgrade transactions. More details on how those are processed inside the system can be read [here](../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md). + +## Whitelisting and executing upgrade + +Note, that due to how powerful the upgrades are, if we allowed any [chain admin](../chain_management/admin_role.md) to inact any upgrade it wants, it could allow malicious chains to potentially break some of the ecosystem invariants. Because of that, any upgrade should be firstly whitelisted by the decentralized governance through calling the `setNewVersionUpgrade` function of the [ChainTypeManager](../../l1-contracts/contracts/state-transition/ChainTypeManager.sol). + +In order to execute the upgrade, the chain admin would call the `upgradeChainFromVersion` function from the [Admin](../../l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol) facet. diff --git a/docs/consensus/consensus-registry.md b/docs/consensus/consensus-registry.md new file mode 100644 index 000000000..d2a37e994 --- /dev/null +++ b/docs/consensus/consensus-registry.md @@ -0,0 +1,20 @@ +# Consensus Registry + +As part of the decentralization effort we plan to introduce two new roles into the system: + +- Validators, which are nodes that are meant to receive L2 blocks from the sequencer, execute them locally and broadcast their signature over the block if it’s valid. If the sequencer receives enough of these signatures, the L2 block is considered finalized. Nodes that are following the chain or syncing will only accept blocks that are finalized. +- Attesters, which basically do the same thing as validators but for L1 batches instead of L2 blocks. Just like with L2 blocks, if a L1 batch is accompanied with enough attester signatures then it’s considered finalized. How these signature are used is different from validators signatures though. These signatures are meant to be submitted to L1 together with the L1 batch when it’s committed. And the L1 contracts are meant to only accept L1 batches that come with enough signatures from the correct attesters. But that functionality is not implemented yet. + +The `ConsensusRegistry` contract implements a small part of that entire flow. In order to verify the L2 block and L1 batch signatures we need to know the public keys of the validators and attesters that signed them. And we also want that set of validators and attesters to be dynamic. The `ConsensusRegistry` contract is going to store and manage the current set of validators and attesters and expose methods to add, remove and modify validators/attesters. + +## Users + +There are basically three types of users that will call this contract: + +- The contract owner. This is generally meant to be some multisig or governance contract. In this case, it will initially be Matter Labs multisig and later it will be changed to be ZKsync’s governance. It can call any method in the contract and basically can modify the validator and attester sets at will. There are methods that are exclusive to it though. Namely add nodes, remove nodes, change validator/attester weights (the relative voting power of each validator/attester) and commit validator/attester committees (creates a snapshot of the current nodes and that updates the validator/attester committees). +- The node owners. The entities that will run the validators and attesters. They change over time as nodes get added/removed. They can only activate/deactivate their nodes (deactivated nodes do not get selected to be part of committees) and change their validator/attester public keys. +- The sequencer plus anyone running an external node. They need to verify L1 batch and L2 block signatures so they need to get the attester and validator committees for each batch. There are getter methods for this. + +## Future integration + +Currently `ConsensusRegistry` contract is not directly connected to the protocol. The plan is to read the validator committee from the consensus registry contract on each new batch. And, with upcoming protocol upgrades, start verifying the validator signatures onchain in each submitted batch. diff --git a/docs/gateway/Custom-da-contracts.png b/docs/gateway/Custom-da-contracts.png deleted file mode 100644 index b97d9755d..000000000 Binary files a/docs/gateway/Custom-da-contracts.png and /dev/null differ diff --git a/docs/gateway/Hyperchain-scheme.png b/docs/gateway/Hyperchain-scheme.png deleted file mode 100644 index b5ec44b01..000000000 Binary files a/docs/gateway/Hyperchain-scheme.png and /dev/null differ diff --git a/docs/gateway/L1-GM-Chain.png b/docs/gateway/L1-GM-Chain.png deleted file mode 100644 index 84b0bd0f3..000000000 Binary files a/docs/gateway/L1-GM-Chain.png and /dev/null differ diff --git a/docs/gateway/L1-L2.png b/docs/gateway/L1-L2.png deleted file mode 100644 index 41ac428f7..000000000 Binary files a/docs/gateway/L1-L2.png and /dev/null differ diff --git a/docs/gateway/chain-asset-id-registration.png b/docs/gateway/chain-asset-id-registration.png deleted file mode 100644 index 98dff79b2..000000000 Binary files a/docs/gateway/chain-asset-id-registration.png and /dev/null differ diff --git a/docs/gateway/chain-migration.md b/docs/gateway/chain-migration.md deleted file mode 100644 index c638cc5c9..000000000 --- a/docs/gateway/chain-migration.md +++ /dev/null @@ -1,13 +0,0 @@ -# Chain migration - -Chain migration uses the Custom Asset Bridging framework: - -- CTMs can be deployed on the Gateway. Each CTM has its own assetId. -- The CTM Deployment Tracker deployed on L1 registers assetId in the L1 and L2 AssetRouters, with the Bridgehub as the AssetHandler. It also registers the L1 and L2 CTM contracts to be associated to the assetId in the Bridgehubs. -- Bridging of a chain happens via the Bridgehub, AssetRouters, and CTM. - -![CTM assetId registration](./chain-asset-id-registration.png) -_Note these are separate calls_ - -![Chain migration](./chain-migration.png) -_Note these are a single call with an L1->L2 txs_ diff --git a/docs/gateway/chain-migration.png b/docs/gateway/chain-migration.png deleted file mode 100644 index 668d9bfa7..000000000 Binary files a/docs/gateway/chain-migration.png and /dev/null differ diff --git a/docs/gateway/chain_migration.md b/docs/gateway/chain_migration.md new file mode 100644 index 000000000..2fe254e7b --- /dev/null +++ b/docs/gateway/chain_migration.md @@ -0,0 +1,43 @@ +# Chain migration + +[back to readme](../README.md) + +## Ecosystem Setup + +Chain migration reuses lots of logic from standard custom asset bridging which is enabled by the AssetRouter. The easiest way to imagine is that ZKChains are NFTs that are being migrated from one chain to another. Just like in case of the NFT contract, an CTM is assumed to have an `assetId := keccak256(abi.encode(L1_CHAIN_ID, address(ctmDeployer), bytes32(uint256(uint160(_ctmAddress)))))`. I.e. these are all assets with ADT = ctmDeployer contract on L1. + +CTMDeployer is a very lightweight contract used to facilitate chain migration. Its main purpose is to server as formal asset deployment tracker for CTMs. It serves two purposes: + +- Assign bridgehub as the asset handler for the “asset” of the CTM on the supported settlement layer. + +Currently, it can only be done by the owner of the CTMDeployer, but in the future, this method can become either permissionless or callable by the CTM owner. + +- Tell bridgehub which address on the L2 should serve as the L2 representation of the CTM on L1. Currently, it can only be done by the owner of the CTMDeployer, but in the future, this method can become callable by the CTM owner. + +![image.png](./img/ctm_gw_registration.png) + +## The process of migration L1→GW + +![image.png](./img/migrate_to_gw.png) + +## Chain migration GW → L1 + +Chain migration from from L1 to GW works similar to how NFT bridging from L1 to another chain would work. Migrating back will use the same mechanism as for withdrawals. + +Note, that for L2→L1 withdrawals via bridges we never provide a recovery mechanism. The same is the case with GW → L1 messaging, i.e. it is assumed that such migrations are always executable on L1. + +You can read more about how the safety is ensured in the “Migration invariants & protocol upgradability” section. + +![image.png](./img/migrate_from_gw.png) + +## Chain migration GW_1 → GW_2 + +In this release we plan to only support a single whitelisted settlement layer, but if in the future more will be supported, as of now the plan is to migrate the chain firstly to L1 and then to GW. + +## Chain migration invariants & protocol upgradability + +Note, that once a chain migrates to a new settlement layer, there are two deployments of contracts for the same ZKChain. What’s more, the L1 part will always be used. + +There is a need to ensure that the chains work smoothly during migration and there are not many issues during the protocol upgrade. + +You can read more about it [here](./gateway_protocol_upgrades.md). diff --git a/docs/gateway/contracts-review-gateway.md b/docs/gateway/contracts-review-gateway.md deleted file mode 100644 index 5e14df72e..000000000 --- a/docs/gateway/contracts-review-gateway.md +++ /dev/null @@ -1,68 +0,0 @@ -# Contracts review - Gateway - -## Intro - -The ZK Gateway is a proof composition layer that will allow chains to settle seamlessly to Ethereum while doing interop (interop not yet supported). In this first version the Gateway is an instance of the EraVM. - -List of changes and new features: - -- Priority Queue uses a Merkle tree structure to store the transactions. This is needed for efficient migration to and from the Gateway. The merkle tree is a DynamicIncrementalMerkleTree, for more information see the PriorityQueue doc. -- Custom Data Availability contracts. This is needed to handle the relayed data availability on the Gateway. -- L1 -> Gateway -> ZKChain transactions. This is done by forwarding transactions to Chain's Mailbox on the Gateway via the Gateway's Mailbox. -- ZKChain -> Gateway -> L1 transactions. This is done by aggregating the logs of different chains in the MessageRoot contract, and sending a single log to L1. -- Migration of chains to and from the Gateway. This is done using our Custom Asset Bridging framework, each CTM has an assetId and is managed by a shared CTMDeploymentTracker, the L2AssetRouter = L2SharedBridge is deployed on the Gateway, but only holds the chains as assets, with the Bridgehub as the AssetHandler. - -Other smaller changes: - -- The setChainId upgrade is updated to become the Genesis upgrade with an L2 contract (deployed at genesis in user-space). -- The Bridgehub, MessageRoot, L2SharedBridge and L2NativeTokenVault contracts are now deployed at genesis on the L2 at fixed addresses in user space. -- The SharedBridges are renamed to AssetRouters. -- Merkle.sol was moved from state-transition/libraries to common/libraries. - -Known issues, and features that still need to be implemented: - -- ZKChain -> Gateway -> L1 transactions are not yet supported. -- Chains cannot yet leave the Gateway. Failed migration to the Gateway cannot yet be reclaimed. -- Upgrade process, how do we upgrade to CAB bridge, to the new system contracts. -- We had the syncLayer internal name previously for the Gateway. This has not been replaced everywhere yet. -- permissions for some functions are not properly restricted yet, mostly they are missing a modifier. -- Bridgehub setAssetHandlerAddress `address sender` might be an issue. -- MessageRoot should be renamed to MessageRootAggregator - -![Untitled](./ZKChain-scheme.png) - -## Initial Scope - -- l1-contracts/contracts/ - - FullMerkle.sol - - DynamicIncrementalMerkle.sol - - Merkle.sol - - PriorityTree.sol - - CalldataDA.sol - - ReleyedSLDAValidator.sol - - Mailbox/\_writePriorityOp function (not other functions) - - Executor.sol -- da-contracts/contracts/\* -- system-contracts/contracts/ - - PubdataChunkPublisher.sol - - L1Messenger.sol - - Compressor.sol -- l2-contracts/contracts/ - - data-availability/\* - - L2ContractHelper.sol - -## Later scope - -The majority of the rest of the changes. This makes the scope quite big, so please focus on the initial scope in more detail, and if you have time include the later scope. - -- MessageRoot.sol -- CTMDeploymentTracker.sol -- Bridgehub.sol -- Config.sol -- L2ContractAddresses.sol -- ChainTypeManager.sol -- ValidatorTimelock.sol -- DiamondInit.sol -- ZKChainStorage.sol -- Admin.sol -- L1GenesisUpgrade.sol diff --git a/docs/gateway/gateway_da.md b/docs/gateway/gateway_da.md new file mode 100644 index 000000000..67bd2081b --- /dev/null +++ b/docs/gateway/gateway_da.md @@ -0,0 +1,27 @@ +# Custom DA layers + +[back to readme](../README.md) + +## Prerequisites + +To better understand this document, it is better to have grasp on how [custom DA handling protocol](../settlement_contracts/data_availability/custom_da.md) works. + +## Rollup DA + +If a chain intends to be a rollup, it needs to relay its pubdata to L1 via L1Messenger system contract. Thus, typically the L1DAValidator will be different from the one that they used on Ethereum. + +For chains that use our [standard pubdata format](../settlement_contracts/data_availability/rollup_da.md), we provide the [following relayed L1 DA validator](../../l1-contracts/contracts/state-transition/data-availability/RelayedSLDAValidator.sol) that relays all the data to L1. + +### Security notes for Gateway-based rollups + +An important note is that when reading the state diffs from L1, the observer will read messages that come from the L2DAValidator. To be more precise, the contract used is `RelayedSLDAValidator` which reads the data and publishes it to L1 by calling the L1Messenger contract. + +If anyone could call this contract, the observer from L1 could get wrong data for pubdata for this particular batch. To prevent this, it ensures that only the chain can call it. + +## Validium DA + +Validiums can reuse [the same DA validator](../../l1-contracts/contracts/state-transition/data-availability/ValidiumL1DAValidator.sol) that they used on L1. Note, that it has to be redeployed on the Gateway. + +## Custom DA + +As already stated before, the DA validation is done on the settlement layer. Thus, if you use a custom DA layer you need to ensure that its verification can be done on Gateway. diff --git a/docs/gateway/gateway_protocol_upgrades.md b/docs/gateway/gateway_protocol_upgrades.md new file mode 100644 index 000000000..11558d533 --- /dev/null +++ b/docs/gateway/gateway_protocol_upgrades.md @@ -0,0 +1,159 @@ +# Gateway protocol versioning and upgradability + +[back to readme](../README.md) + +One of the hardest part about gateway (GW) is how do we synchronize interaction between L1 and L2 parts that can potentially have different versions of contracts. This synchronization should be compatible with any future CTM that may be present on the gateway. + +Here we describe various scenarios of standard/emergency upgrades and how will those play out in the gateway setup. + +## General idea + +We do not enshrine any particular approach on the protocol level of the GW. The following is the approach used by the standard Era CTM, which also manages GW. + +Upgrades will be split into two parts: + +- “Inactive chain upgrades” ⇒ intended to update contract code only and not touch the state or touch it very little. The main motivation is to be able to upgrade the L1 contracts without e.g. adding new upgrade transactions. +- “Active chain upgrades” ⇒ same as the ones that we have today: full-on upgrade that also updates bootloader, insert system upgrade transaction and so on. + +In other words: + +`active upgrade = inactive upgrade + bootloader changes + setting upgrade tx` + +The other difference is that while “active chain upgrades” are usually always needed to be forced in order to ensure that contracts/protocol are up to date, the “inactive chain upgrades” typically involve changes in the facets’ bytecode and will only be needed before migration is complete to ensure that contracts are compatible. + +To reduce the boilerplate / make management of the upgrades easier, the abstraction will be basically implemented at the upgrade implementation level, that will check `if block.chainid == s.settlementLayer { ... perform active upgrade stuff } else { ... perform inactive upgrade stuff, typically nothing m}.` + +## Lifecycle of a chain + +While the chain settles on L1 only, it will just do “active chain upgrades”. Everything is the same as now. + +When a chain starts its migration to a new settlement layer (regardless of whether it is gateway or not): + +1. It will be checked the that the protocolVersion is the latest in the CTM in the current settlement layer (just in case to not have to bother with backwards compatibility). +2. The `s.settlementLayer` will be set for the chain. Now the chain becomes inactive and it can only take “inactive” upgrades. +3. When migration finishes, it will be double checked that the `protocolVersion` is the same as the one in the target chains’ CTM. + +If the chain has already been deployed there, it will be checked that the `protocolVersion` of the deployed contracts there is the same as the one of the chain that is being moved. 4. All “inactive” instances of a chain can receive “inactive” upgrades of a chain. The single “active” instance of a chain (the one on the settlement layer) can receive only active upgrades. + +In case step (3) fails (or for any other reason the chain fails), the migration recovery process should be available. (`L1AssetRouter.bridgeRecoverFailedTransfer` method). Recovering a chain id basically just changing its `settlementLayerId` to the current block.chainid. It will be double checked that the chain has not conducted any inactive upgrades in the meantime, i.e. the `protocolVersion` of the chain is the same as the one when the chain started its migration. + +In case we ever do need to do more than simply resetting `settlementLayerId` for a chain in case of a failed migration, it is the responsibility of the CTM to ensure that the logic is compatible for all the versions. + +## Stuck state for L1→GW migration + +The only unrecoverable state that a chain can achieve is: + +- It tries to migrate and it fails. +- While the migration has happening an “inactive” upgrade has been conducted. +- Now recovery of the chain is not possible as the “protocol version” check will fail. + +This is considered to be a rare event, but it will be strongly recommended that before conducting any inactive upgrades the migration transaction should be finalized. + +In the future, we could actively force it, i.e. require confirmation of a successful migration before any upgrades on a migrated chain could be done. + +## Safety guards for GW→L1 migrations + +Migrations from GW to L1 do not have any chain recovery mechanism, i.e. if the step (3) from the above fails for some reason (e.g. a new protocol version id is available on the CTM), then the chain is basically lost. + +### Protocol version safety guards + +- Before a new protocol version is released, all the migrations will be paused, i.e. the `pauseMigration` function will be called by the owner of the Bridgehub on both L1 and L2. It should prevent migrations happening in the risky period when the new version is published to the CTM. +- Assuming that no new protocol versions are published to CTM during the migration, the migration must succeed, since both CTM on GW and on L1 will have the same version and so the checks will work fine. +- The finalization of any chain withdrawal is permissionless and so in the short term the team could help finalize the outstanding migrations to prevent funds loss. + +> The approach above is somewhat tricky as it requires careful coordination with the governance to ensure that at the time of when the new protocol version is published to CTM, there are no outstanding migrations. + +In the future we will either make it more robust or add a recovery mechanism for failed GW → L1 migrations. + +> + +### Batch number safety guards + +Another potential place that may lead for a chain to not be migratable to L1 is if the number of outstanding batches is very high, which can lead to migration to cost too much gas and being not executable no L1. + +To prevent that, it is required for chains that migrate from GW that all their batches are executed. This ensures that the number of batches’ hashes to be copied on L1 is constant (i.e. just 1 last batch). + +## Motivation + +The job of this proposal is to reduce the number of potential states in which the system can find itself in to a minimum. The cases that are removed: + +- Need to be able to migrate to a chain that has contracts from a different protocol version +- Need to be able for CTM to support migration of chains with different versions. Only `bridgeRecoverFailedTransfer` has to be supported for all the versions, but its logic is very trivial. + +The reason why we can not conduct “active” upgrades everywhere on both L1 and L2 part is that for the settlement layer we need to write the new protocol upgrade tx, while NOT allowing to override it. On other hand, for the “inactive” chain contracts, we need to ignore the upgrade transaction. + +## Forcing “active chain upgrade” + +For L1-based chains, forcing those upgrades will work exactly same as before. Just during `commitBatches` the CTM double checks that the protocol version is up to date. + +The admin of the CTM (GW) will call the CTM (GW) with the new protocol version’s data. This transaction should not fail, but even if it does fail, we should be able to just re-try. For now, the GW operator will be trusted to not be malicious + +### Case of malicious Gateway operator + +In the future, malicious Gateway operator may try to exploit a known vulnerability in an CTM. + +The recommended approach here is the following: + +- Admin of the CTM (GW) will firstly commit to the upgrade (for example, preemptively freeze all the chains). +- Once the chains are frozen, it can use L1→L2 communication to pass the new protocol upgrade to CTM. + +> The approach above basically states that “if operator is censoring, we’ll be able to use standard censorship-resistance mechanism of a chain to bypass it”. The freezing part is just a way to not tell to the world the issue before all chains are safe from exploits. + +It is the responsibility of the CTM to ensure that all the supported settlement layers are trusted enough to uphold to the above protocol. Using any sort of Validiums will be especially discouraged, since in theory those could get frozen forever without any true censorship resistance mechanisms. + +Also, note that the freezing period should be long enough to ensure that censorship resistance mechanisms have enough time to kick in + +> + +## Forcing “inactive chain upgrade” + +Okay, imagine that there is a bug in an L1 implementation of a chain that has migrated to Gateway. This is a rather rare event as most of the action happens on the settlement layer, together with the ability to steal the most of funds. + +In case such situation does happen however, the current plan is just to: + +- Freeze the ecosystem. +- Ask the admins nicely to upgrade their implementation. Decentralized token governance can also force-upgrade those via CTM on L1. + +## Backwards compatibility + +With this proposal the protocol version on the L1 part and on the settlement layer part is completely out of sync. This means that all new mailboxes need to support both accepting and sending all versions of relayed (L1 → GW → L2) transactions. + +For now, this is considered okay. In the future, some stricter versioning could apply. + +## Notes + +### Regular chain migration moving chain X from Y to Z (where Y is Z’s settlement layer) + +So assume that Y is L1, and Z is ‘Gateway’. + +Definition: + +`ZKChain(X)` - ‘a.k.a ST / DiamondProxy’ for a given chain id X + +`CTM(X)` - the State transition manager for a given chain id X + +1. check that `ZKChain(X).protocol_version == CTM(X).protocol_version` on chain Y. +2. Start ‘burn’ process (on chain Y) + 1. collect `‘payload’` from `ZKChain(X)` and `CTM(X)` and `protocol_version` on chain Y. + 2. set `ZKChain(X).settlement_layer` to `address(ZKChain(Z))` on chain Y. +3. Start ‘mint’ process (on chain Z) + 1. check that `CTM(X).protocol_version == payload.protocol_version` + 2. Create new `ZKChain(X)` on chain Z and register in the local bridgehub & CTM. + 3. pass `payload` to `ZKChain(X)` and `CTM(X)` to initialize the state. +4. If ‘mint’ fails - recover (on chain Y) + 1. check that `ZKChain(X).protocol_version == payload.protocol_version` + 1. important, here we’re actually looking at the ‘HYPERCHAIN’ protocol version and not necessarily CTM protocol version. + 2. set `ZKChain(X).settlement_layer` to `0` on chain Y. + 3. pass `payload` to `IZKChain(X)` and `CTM(X)` to initialize the state. + +### ‘Reverse’ chain migration - moving chain X ‘back’ from Z to Y + +(moving back from gateway to L1). + +1. Same as above (check protocol version - but on chain Z) +2. Same as above (start burn process - but on chain Z) +3. Same as above (start ‘mint’ - but on chain Y) + 1. same as above + 2. creation is probably not needed - as the contract was already there in a first place. + 3. same as above - but the state is ‘re-initialized’ +4. Same as above - but on chain ‘Z’ diff --git a/docs/gateway/img/ctm_gw_registration.png b/docs/gateway/img/ctm_gw_registration.png new file mode 100644 index 000000000..03dc68518 Binary files /dev/null and b/docs/gateway/img/ctm_gw_registration.png differ diff --git a/docs/gateway/img/gateway_architecture.png b/docs/gateway/img/gateway_architecture.png new file mode 100644 index 000000000..a9302ec7e Binary files /dev/null and b/docs/gateway/img/gateway_architecture.png differ diff --git a/docs/gateway/img/l1_l2_messaging.png b/docs/gateway/img/l1_l2_messaging.png new file mode 100644 index 000000000..886c13174 Binary files /dev/null and b/docs/gateway/img/l1_l2_messaging.png differ diff --git a/docs/gateway/img/l1_l3_messaging.png b/docs/gateway/img/l1_l3_messaging.png new file mode 100644 index 000000000..a2b4db935 Binary files /dev/null and b/docs/gateway/img/l1_l3_messaging.png differ diff --git a/docs/gateway/img/migrate_from_gw.png b/docs/gateway/img/migrate_from_gw.png new file mode 100644 index 000000000..b30576043 Binary files /dev/null and b/docs/gateway/img/migrate_from_gw.png differ diff --git a/docs/gateway/img/migrate_to_gw.png b/docs/gateway/img/migrate_to_gw.png new file mode 100644 index 000000000..6615791e1 Binary files /dev/null and b/docs/gateway/img/migrate_to_gw.png differ diff --git a/docs/gateway/MessageRoot.png b/docs/gateway/img/nested_l3_l1_messaging.png similarity index 100% rename from docs/gateway/MessageRoot.png rename to docs/gateway/img/nested_l3_l1_messaging.png diff --git a/docs/gateway/img/nested_l3_l1_messaging_2.png b/docs/gateway/img/nested_l3_l1_messaging_2.png new file mode 100644 index 000000000..5426e8e01 Binary files /dev/null and b/docs/gateway/img/nested_l3_l1_messaging_2.png differ diff --git a/docs/gateway/img/new_bridging_contracts.png b/docs/gateway/img/new_bridging_contracts.png new file mode 100644 index 000000000..f3f6802cd Binary files /dev/null and b/docs/gateway/img/new_bridging_contracts.png differ diff --git a/docs/gateway/messaging-via-gateway.md b/docs/gateway/messaging-via-gateway.md deleted file mode 100644 index bfffdb429..000000000 --- a/docs/gateway/messaging-via-gateway.md +++ /dev/null @@ -1,23 +0,0 @@ -# Messaging via Gateway - -Messaging for chains using the Gateway has two components, receiving messages from L1 and sending messages to it. - -## L1 -> Gateway -> ZK Chain transactions - -Transaction are sent from the Chain's Mailbox (on L1) to the Gateway's L1 Mailbox. From here they are routed to the BH on the Gateway, which forwards them to the Chain's Mailbox on the Gateway. - -![Direct L1->L2 messaging](./L1-L2.png) - -![L1->L2 messaging via the Gateway](./L1->GM->Chain.png) - -## ZK Chain -> Gateway -> L1 transactions - -Messages sent from the ZK Chain to L1 are aggregated in the MessageRoot contract on the Gateway. Logs are first aggregated for a single chain across batches in a DynamicIncrementleMerkleTree, and then the roots of chains are aggregated in a FullMerkle Tree. - -![MessageRoot aggregation on the Gateway](./MessageRoot.png) - -The benefits of this architecture are: - -- the DI Merkle Tree allows chains to send multiple batches after each other, while not "burying" older batches (the Merkle paths to them will not be long unlike in a rolling hash solution). -- the Full Merkle Tree allows each chain to update the tree individually, they only need to recalculate a single branch. Storage is cheaper on the Gateway than on L1. -- Rollups publish all their L2->L1 transaction data, but for Validiums chains need to have access to the chain-level message roots to be able to construct merkle paths to every message. The Full Merkle provides this. diff --git a/docs/gateway/messaging_via_gateway.md b/docs/gateway/messaging_via_gateway.md new file mode 100644 index 000000000..fc6681ad3 --- /dev/null +++ b/docs/gateway/messaging_via_gateway.md @@ -0,0 +1,50 @@ +# Messaging via Gateway + +[back to readme](../README.md) + +## Deeper dive into MessageRoot contract and how L3→L1 communication works + +Before, when were just settling on L1, a chain’s message root was just the merkle tree of L2→L1 logs that were sent within this batch. However, this new model will have to be amended to be able to perform messages to L1 coming from an L3 that settles on top of Gateway. + +The description of how L3→L1 messages are aggregated in the MessageRoots and proved on L1 can be read in the [nested l3 l1 messaging](./nested_l3_l1_messaging.md) section. + +## L1→L3 messaging + +As a recap, here is how messaging works for chains that settle on L1: + +![Direct L1->L2 messaging](./img/l1_l2_messaging.png) + +- The user calls the bridgehub, which routes the message to the chain. +- The operator eventually sees the transaction via an event on L1 and it will process it on L2. + +With gateway, the situation will be a bit more complex: + +![L1->L2 messaging via the Gateway](./img/l1_l3_messaging.png) + +Since now, the contracts responsible for batch processing were moved to Gateway, now all the priority transactions have to be relayed to that chain so that the validation could work. + +- (Steps 1-3) The user calls Bridgehub. The base token needs to be deposited via L1AssetRouter (usually the NTV will be used). +- (Step 4-5). The Bridgehub calls the chain where the transaction is targeted to. The chain sees that its settlement layer is another chain and so it calls it and asks to relay this transaction to gateway +- (Steps 6-7). priority transaction from `SETTLEMENT_LAYER_RELAY_SENDER` to the Bridgehub is added to the Gateway chain’s priority queue. Once the Gateway operator sees the transaction from L1, it processed it. The transaction itself will eventually call the DiamondProxy of the initial called chain. +- (Step 8) At some point, the operator of the chain will see that the priority transaction has been included to the gateway and it will process it on the L3. +- Step 9 from the picture above is optional and in case the callee of the L1→L3 transaction is the L2AssetRouter (i.e. the purpose of the transaction was bridging funds), then the L2AssetRouter will call asset handler of the asset (in case of standard bridged tokens, it will be the NativeTokenVault). It will be responsible for minting the corresponding number of tokens to the user. + +So under the hood there are 2 cross chain transactions happening: + +1. One from L1 to GW +2. The second one from GW to the L3. + +From another point with bridging we have methods that allow users to recover funds in case of a failed L1→L2 transaction. E.g. if the user tried to bridge USDC to a Zk Chain, but did not provide enough L2 gas, it can still recover the funds. + +This functionality works by letting user prove that the bridging transaction failed and then the funds are released back to the original sender on L1. With the approach above where there are multiple cross chain transactions involved, it could become 2x hard to maintain: now both of these could fail. + +To simplify things, for now, we provide the L1→GW with a large amount of gas (72kk, i.e. the maximal amount allowed to be passed on L2). We believe that it is not possible to create a relayed transaction that would fail, assuming that a non malicious recipient CTM is used on L2. + +> Note, that the above means that we currently rely on the following two facts: + +- The recipient CTM is honest and efficient. +- Creating a large transaction on L1 that would cause the L1→GW part to fail is not possible due to high L1 gas costs that would be required to create such a tx. + +Both of the assumptions above will be removed in subsequent releases, but for now this is how things are. + +> diff --git a/docs/gateway/nested_l3_l1_messaging.md b/docs/gateway/nested_l3_l1_messaging.md new file mode 100644 index 000000000..7338c939a --- /dev/null +++ b/docs/gateway/nested_l3_l1_messaging.md @@ -0,0 +1,184 @@ +# Nested L3→L1 messages tree design for Gateway + +[back to readme](../README.md) + +## Introduction + +This document assumes that the reader is already aware of what SyncLayer (or how it is now called Gateway) is. To reduce the interactions with L1, on SyncLayer we will gather all the batch roots from all the chains into the tree with following structure: + +![NestedL3L1Messaging.png](./img/nested_l3_l1_messaging.png) +![NestedL3L1Messaging.png](./img/nested_l3_l1_messaging_2.png) + +> Note: + +“Multiple arrows” from `AggregatedRoot` to `chainIdRoot` and from each `chainIdRoot` to `batchRoot` are for illustrational purposes only. + +In fact, the tree above will be a binary merkle tree, where the `AggregatedRoot` will be the root of the tree of `chainIdRoot`, while `chainIdRoot` is the merkle root of a binary merkle tree of `batchRoot`. + +> + +For each chain that settles on L1, the root will have the following format: + +`settledMessageRoot = keccak256(LocalRoot, AggregatedRoot)` + +where `localRoot` is the root of the tree of messages that come from the chain itself, while the `AggregatedRoot` is the root of aggregated messages from all of the chains that settle on top of the chain. + +In reality, `AggregatedRoot` will have a meaningful value only on SyncLayer and L1. On other chains it will be a root of an empty tree. + +The structure has the following recursive format: + +- `settledMessageRoot = keccak256(LocalRoot, AggregatedRoot)` +- `LocalRoot` — the root of the binary merkle tree over `UserLog[]`. (the same as the one we have now). It only contains messages from the current batch. +- `AggregatedRoot` — the root of the binary merkle tree over `ChainIdLeaf[]`. +- `ChainIdLeaf = keccak256(CHAIN_ID_LEAF_PADDING, chain_id, ChainIdRoot`) +- `CHAIN_ID_LEAF_PADDING` — it is a constant padding, needed to ensure that the preimage of the ChainIdLeaf is larger than 64 bytes and so it can not be an internal node. +- `chain_id` — the chain id of the chain the batches of which are aggregated. +- `ChainIdRoot` = the root of the binary merkle tree `BatchRootLeaf[]`. +- `BatchRootLeaf = keccak256(BATCH_LEAF_HASH_PADDING, batch_number, SettledRootOfBatch).` + +In other words, we get the recursive structure, where for leaves of it, i.e. chains that do not aggregate any other chains, have empty `AggregatedRoot`. + +## Appending new batch root leaves + +At the execution stage of every batch, the ZK Chain would call the `MessageRoot.addChainBatchRoot` function, while providing the `SettledRootOfBatch` for the chain. Then, the `BatchRootLeaf` will be calculated and appended to the incremental merkle tree with which the `ChainIdRoot` & `ChainIdLeaf` is calculated, which will be updated in the merkle tree of `ChainIdLeaf`s. + +At the end of the batch, the L1Messenger system contract would query the MessageRoot contract for the total aggregated root, i.e. the root of all `ChainIdLeaf`s . Calculate the settled root `settledMessageRoot = keccak256(LocalRoot, AggregatedRoot)` and propagate it to L1. + +Only the final aggregated root will be stored on L1. + +## Proving that a message belongs to a chain on top of SyncLayer + +The process will consist of two steps: + +1. Construct the needed `SettledRootOfBatch` for the current chain’s batch. +2. Prove that it belonged to the gateway. + +If the depth of recursion is larger than 1, then step (1) could be repeated multiple times. + +Right now for proving logs the following interface is exposed on L1 side: + +```solidity +struct L2Log { + uint8 l2ShardId; + bool isService; + uint16 txNumberInBatch; + address sender; + bytes32 key; + bytes32 value; +} + +function proveL2LogInclusion( + uint256 _chainId, + uint256 _batchNumber, + uint256 _index, + L2Log calldata _log, + bytes32[] calldata _proof +) external view override returns (bool) { + address hyperchain = getHyperchain(_chainId); + return IZkSyncHyperchain(hyperchain).proveL2LogInclusion(_batchNumber, _index, _log, _proof); +} +``` + +Let’s define a new function: + +```solidity +function proveL2LeafInclusion( + uint256 _chainId, + uint256 _batchNumber, + uint256 _mask, + bytes32 _leaf, + bytes32[] calldata _proof +) external view override returns (bool) {} +``` + +This function will prove that a certain 32-byte leaf belongs to the tree. Note, that the fact that the `leaf` is 32-bytes long means that the function could work successfully for internal leaves also. To prevent this it will be the callers responsibility to ensure that the preimage of the leaf is larger than 32-bytes long and/or use other ways to ensuring that the function will be called securely. + +This function will be internally used by the existing `_proveL2LogInclusion` function to prove that a certain log existed + +We want to avoid breaking changes to SDKs, so we will modify the `zks_getL2ToL1LogProof` to return the data in the following format (the results of it are directly passed into the `proveL2LeafInclusion` method, so returned value must be supported by the contract): + +First `bytes32` corresponds to the metadata of the proof. The zero-th byte should tell the version of the metadata and must be equal to the `SUPPORTED_PROOF_METADATA_VERSION` (a constant of `0x01`). + +Then, it should contain the number of 32-byte words that are needed to restore the current `BatchRootLeaf` , i.e. `logLeafProofLen` (it is called this way as it proves that a leaf belongs to the `SettledRootOfBatch`). The second byte contains the `batchLeafProofLen` . It is the length of the merkle path to prove that the `BatchRootLeaf` belonged to the `ChainIdRoot` . + +Then, the following happens: + +- We consume the `logLeafProofLen` items to produce the `SettledRootOfBatch`. The last word is typically the aggregated root for the chain. + +If the settlement layer of the chain is the chain itself, we can just end here by verifying that the provided batch message root is correct. + +If the chain is not a settlement layer of itself, we then need to calculate: + +- `BatchRootLeaf = keccak256(BATCH_LEAF_HASH_PADDING, SettledRootOfBatch, batch_number).` +- Consume one element from the `_proofs` array to get the mask for the merkle path of the batch leaf in the chain id tree. +- Consume `batchLeafProofLen` elements to construct the `ChainIdRoot` +- After that, we calculate the `chainIdLeaf = keccak256(CHAIN_ID_LEAF_PADDING, chainIdRoot, chainId` + +Now, we have the _supposed_ `chainIdRoot` for the chain inside its settlement layer. The only thing left to prove is that this root belonged to some batch of the settlement layer. + +Then, the following happens: + +- One element from `_proof` array is consumed and expected to maintain the batchNumber of the settlement layer when this chainid root was present as well as mask for the reconstruction of the merkle tree. +- The other element from the `_proof` contains the address of the settlement layer, where the address will be checked. + +Now, we can call the function to verify that the batch belonged to the settlement layer: + +```solidity + IMailbox(settlementLayerAddress).proveL2LeafInclusion( + settlementLayerBatchNumber, + settlementLayerBatchRootMask, + chainIdLeaf, + // Basically pass the rest of the `_proof` array + extractSliceUntilEnd(_proof, ptr) + ); +``` + +The other slice of the `_proof` array is expected to have the same structure as before: + +- Metadata +- Merkle path to construct the `SettledRootOfBatch` +- In case there are any more aggregation layers, additional info to prove that the batch belonged to it. + +## Trust assumptions + +Note, that the `_proof` field is provided by potentially malicious users. The only part that really checks anything with L1 state is the final step of the aggregated proof verification, i.e. that the settled root of batch of the final top layer was present on L1. + +It puts a lot of trust in the settlement layers as it can steal funds from chains and “verify” incorrect L3→L1 logs if it wants to. It is the job of the chain itself to ensure that it trusts the aggregation layer. It is also the job of the STM to ensure that the settlement layers that are used by its chains are secure. + +Also, note that that `address` of the settlement layer is provided by the user. Assuming that the settlement layer is trusted, this scheme works fine, since the `chainIdLeaf` belongs to it only if the chain really ever settled there. I.e. so the protection from maliciously chosen settlement layers is the fact that the settlement layers are trusted to never include batches that they did not have. + +## Additional notes on security + +### Redundance of data + +Currently, we never clear the `MessageRoot` in other words, the aggregated root contains more and more batches’ settlement roots, leading to the following two facts: + +- The aggregated proofs’ length starts to logarithmically depend on the number of total batches ever finalized on top of this settlement layer (it also depends logarithmically on the number of chains in the settlement layer). I.e. it is `O(log(total_chains) + log(total_batches) + log(total_logs_in_the_batch))` in case of a single aggregation layer. +- The same data may be referenced from multiple final aggregated roots. + +It is the responsibility of the chain to ensure that each message has a unique id and can not be replayed. Currently a tuple of `chain_batch_number, chain_message_id` is used. While there are multiple message roots from which such a tuple could be proven from, it is still okay as it will be nullified only once. + +Another notable example of the redundancy of data, is that we also have total `MessageRoot` on L1, which contains the aggregated root of all chains, while for chains that settle on L1, we still store the `settledBatchRoot` for the efficiency. + +### Data availability guarantees + +We want to maintain the security invariant that users can always withdraw their funds from rollup chains. In other words, all L3→L1 logs that come from rollups should be eventually propagated to L1, and also regardless of how other chains behave an honest chain should always provide the ability for their users to withdraw. + +Firstly, unless the chain settles on L1, this requires a trusted settlement layer. That is, not trusted operator of the gateway, but it works properly, i.e. appends messages correctly, publishes the data that it promises to publish, etc. This is already the case for the Gateway as it is a ZK rollup fork of Era, and while the operator may censor transactions, it can not lie and is always forced to publish all state diffs. + +Secondly, we guarantee that all the stored `ChainIdLeaf`s are published on L1, even for Validiums. Publishing a single 32 byte value per relatively big Gateway batch has little price for Validiums, but it ensures that the settlement root of the gateway can always be constructed. And, assuming that the preimage for the chain root could be constructed, this gives an ability to ability to recover the proof for any L3→L1 coming from a rollup. + +But how can one reconstruct the total chain tree for a particular rollup chain? A rollup would relay all of its pubdata to L1, meaning that by observing L1, the observer would know all the L3→L1 logs that happened in a particular batch. It means that for each batch it can restore the `LocalRoot` (in case the `AggregatedRoot` is non-zero, it could be read from e.g. the storage which is available via the standard state diffs). This allows to calculate the `BatchRootLeaf` for the chain. The only thing missing is understanding which batches were finalized on gateway in order to construct the merkle path to the `ChainRootLeaf`. + +To understand which SL was used by a batch for finalization, one could simply brute force over all settlement layers ever used to find out where the settledBatchRoot is stored.. This number is expected to be rather small. + +## Legacy support + +In order to ease the server migration, we support legacy format of L2→L1 logs proving, i.e. just provide a proof that assumes that stored `settledMessageRoot` is identical to local root, i.e. the hash of logs in the batch. + +To differentiate between legacy format and the one, the following approach is used; + +- Except for the first 3 bytes the first word in the new format contains 0s, which is unlikely in the old format, where leaves are hashed. +- I.e. if the last 29 bytes are zeroes, then it is assumed to be the new format and vice versa. + +In the next release the old format will be removed. diff --git a/docs/gateway/overview.md b/docs/gateway/overview.md new file mode 100644 index 000000000..ea50dc459 --- /dev/null +++ b/docs/gateway/overview.md @@ -0,0 +1,25 @@ +# Gateway + +[back to readme](../README.md) + +Gateway is a proof aggregation layer, created to solve the following problems: + +- Fast interop (interchain communication) would require quick proof generation and verification. The latter can be very expensive on L1. Gateway provides an L1-like interface for chains, while giving a stable price for compute. +- Generally proof aggregation can reduce costs for users, if there are multiple chains settling on top of the same layer. It can reduce the costs of running a Validium even further. + +In this release, Gateway is basically a fork of Era, that will be deployed within the same CTM as other ZK Chains. This allows us to reuse most of the existing code for Gateway. + +> In some places in code you can meet words such as “settlement layer” or the abbreviation “sl”. “Settlement layer” is a general term that describes a chain that other chains can settle to. Right now, the list of settlement layers is whitelisted and only Gateway will be allowed to be a settlement layer (along with L1). + +## High level gateway architecture + +![image.png](./img/gateway_architecture.png) + +## Read more + +- [General overview](overview.md) +- [Chain migration](chain_migration.md) +- [L1->L3 messaging via gateway](messaging_via_gateway.md) +- [L3->L1 messaging via gateway](nested_l3_l1_messaging.md) +- [Gateway protocol versioning](gateway_protocol_upgrades.md) +- [DA handling on Gateway](gateway_da.md) diff --git a/docs/glossary.md b/docs/glossary.md new file mode 100644 index 000000000..c0a1b29a8 --- /dev/null +++ b/docs/glossary.md @@ -0,0 +1,11 @@ +# Glossary + +[back to readme](./README.md) + +- **Validator/Operator** - a privileged address that can commit/verify/execute L2 batches. +- **L2 batch (or just batch)** - An aggregation of multiple L2 blocks. Note, that while the API operates on L2 blocks, + the prove system operates on batches, which represent a single proved VM execution, which typically contains multiple + L2 blocks. +- **Facet** - implementation contract. The word comes from the EIP-2535. +- **Gas** - a unit that measures the amount of computational effort required to execute specific operations on the + ZKsync Era network. diff --git a/docs/img/reading_order.png b/docs/img/reading_order.png new file mode 100644 index 000000000..c5309e681 Binary files /dev/null and b/docs/img/reading_order.png differ diff --git a/docs/l2_system_contracts/batches_and_blocks_on_zksync.md b/docs/l2_system_contracts/batches_and_blocks_on_zksync.md new file mode 100644 index 000000000..723317e64 --- /dev/null +++ b/docs/l2_system_contracts/batches_and_blocks_on_zksync.md @@ -0,0 +1,103 @@ +# Batches & L2 blocks on ZKsync + +[back to readme](../README.md) + +## Glossary + +- Batch - a set of transactions that the bootloader processes (`commitBatches`, `proveBatches`, and `executeBatches` work with it). A batch consists of multiple transactions. +- L2 blocks - non-intersecting sub-sets of consecutively executed transactions in a batch. This is the kind of block you see in the API. This is the one that is used for `block.number`/`block.timestamp`/etc. + +> Note that sometimes in code you can see notion of "virtual blocks". In the past, we returned batch information for `block.number`/`block.timestamp`. However due to DevEx issues we decided to move to returned these values for L2 blocks. Virtual blocks were used during migration, but are not used anymore. You consider that there is one virtual block per one L2 block and it has exactly the same properties. + +## Motivation + +L2 blocks were created for fast soft confirmation in wallets and block explorer. For example, MetaMask shows transactions as confirmed only after the block in which transaction execution was mined. So if the user needs to wait for the batch confirmation it would take at least a few minutes (for soft confirmation) and hours for full confirmation which is very bad UX. But API could return soft confirmation much earlier through L2 blocks. + +## Adapting for Solidity + +In order to get the returned value for `block.number`, `block.timestamp`, `blockhash` our compiler used the following functions: + +- `getBlockNumber` +- `getBlockTimestamp` +- `getBlockHashEVM` + +These return values for L2 blocks. + +## Blocks’ processing and consistency checks + +Our `SystemContext` contract allows to get information about batches and L2 blocks. Some of the information is hard to calculate onchain. For instance, time. The timing information (for both batches and L2 blocks) are provided by the operator. In order to check that the operator provided some realistic values, certain checks are done on L1. Generally though, we try to check as much as we can on L2. + +### Initializing L1 batch + +At the start of the batch, the operator [provides](../../system-contracts/bootloader/bootloader.yul#L3935) the timestamp of the batch, its number and the hash of the previous batch. The root hash of the Merkle tree serves as the root hash of the batch. + +The SystemContext can immediately check whether the provided number is the correct batch number. It also immediately sends the previous batch hash to L1, where it will be checked during the commit operation. Also, some general consistency checks are performed. This logic can be found [here](../../system-contracts/contracts/SystemContext.sol#L469). + +### L2 blocks processing and consistency checks + +#### `setL2Block` + +Before each transaction, we call `setL2Block` [method](../../system-contracts/bootloader/bootloader.yul#L2884). There we will provide some data about the L2 block that the transaction belongs to: + +- `_l2BlockNumber` The number of the new L2 block. +- `_l2BlockTimestamp` The timestamp of the new L2 block. +- `_expectedPrevL2BlockHash` The expected hash of the previous L2 block. +- `_isFirstInBatch` Whether this method is called for the first time in the batch. +- `_maxVirtualBlocksToCreate` The maximum number of virtual block to create with this L2 block. This is a legacy field that is always equal either to 0 or 1. + +If two transactions belong to the same L2 block, only the first one may have non-zero `_maxVirtualBlocksToCreate`. The rest of the data must be same. + +The `setL2Block` [performs](../../system-contracts/contracts/SystemContext.sol#L355) a lot of similar consistency checks to the ones for the L1 batch. + +#### L2 blockhash calculation and storage + +Unlike L1 batch’s hash, the L2 blocks’ hashes can be checked on L2. + +The hash of an L2 block is `keccak256(abi.encode(_blockNumber, _blockTimestamp, _prevL2BlockHash, _blockTxsRollingHash))`. Where `_blockTxsRollingHash` is defined in the following way: + +`_blockTxsRollingHash = 0` for an empty block. + +`_blockTxsRollingHash = keccak(0, tx1_hash)` for a block with one tx. + +`_blockTxsRollingHash = keccak(keccak(0, tx1_hash), tx2_hash)` for a block with two txs, etc. + +To add a transaction hash to the current miniblock we use the `appendTransactionToCurrentL2Block` function of the `SystemContext` contract. + +Since ZKsync is a state-diff based rollup, there is no way to deduce the hashes of the L2 blocks based on the transactions’ in the batch (because there is no access to the transaction’s hashes). At the same time, in order to execute `blockhash` method, the VM requires the knowledge of some of the previous L2 block hashes. In order to save up on pubdata (by making sure that the same storage slots are reused, i.e. we only have repeated writes) we [store](../../system-contracts/contracts/SystemContext.sol#L73) only the last 257 block hashes. You can read more on what are the repeated writes and how the pubdata is processed [here](../settlement_contracts/data_availability/standard_pubdata_format.md). + +We store only the last 257 blocks, since the EVM requires only 256 previous ones and we use 257 as a safe margin. + +#### Legacy blockhash + +For L2 blocks that were created before we switched to the formulas from above, we use the following formula for their hash: + +`keccak256(abi.encodePacked(uint32(_blockNumber)))` + +These are only very old blocks on ZKsync Era and other ZK chains don't have such blocks. + +#### Timing invariants + +While the timestamp of each L2 block is provided by the operator, there are some timing invariants that the system preserves: + +- For each L2 block its timestamp should be > the timestamp of the previous L2 block +- For each L2 block its timestamp should be ≥ timestamp of the batch it belongs to +- Each batch must start with a new L2 block (i.e. an L2 block can not span across batches). +- The timestamp of a batch must be ≥ the timestamp of the latest L2 block which belonged to the previous batch. +- The timestamp of the last miniblock in batch can not go too far into the future. This is enforced by publishing an L2→L1 log, with the timestamp which is then checked on L1. + +### Fictive L2 block & finalizing the batch + +At the end of the batch, the bootloader calls the `setL2Block` [one more time](../../system-contracts/bootloader/bootloader.yul#L4110) to allow the operator to create a new empty block. This is done purely for some of the technical reasons inside the node, where each batch ends with an empty L2 block. + +We do not enforce that the last block is empty explicitly as it complicates the development process and testing, but in practice, it is, and either way, it should be secure. + +Also, at the end of the batch we send the timestamps of the batch as well as the timestamp of the last miniblock in order to check on L1 that both of these are realistic. Checking any other L2 block’s timestamp is not required since all of them are enforced to be between those two. + +## Additional note on blockhashes + +In the past, we had to apply different formulas based on whether or not the migration from batch environment info to L2 block info has finished. You can find these checks [here](../../system-contracts/contracts/SystemContext.sol#L137). But note, that the migration has ended quite some time ago, so in reality only the two cases above can be met: + +- When the block is out of the readable range. +- When it is a normal L2 block and so its hash has to be used. + +The only edge case is when we ask for miniblock block number for which the base hash is returned. This edge case will be removed in future releases. diff --git a/docs/l2_system_contracts/elliptic_curve_precompiles.md b/docs/l2_system_contracts/elliptic_curve_precompiles.md new file mode 100644 index 000000000..a3caa1f01 --- /dev/null +++ b/docs/l2_system_contracts/elliptic_curve_precompiles.md @@ -0,0 +1,251 @@ +# Elliptic curve precompiles + +[back to readme](../README.md) + +Precompiled contracts for elliptic curve operations are required in order to perform zkSNARK verification. + +The operations that you need to be able to perform are elliptic curve point addition, elliptic curve point scalar multiplication, and elliptic curve pairing. + +This document explains the precompiles responsible for elliptic curve point addition and scalar multiplication and the design decisions. You can read the specification [here](https://eips.ethereum.org/EIPS/eip-196). + +## Introduction + +On top of having a set of opcodes to choose from, the EVM also offers a set of more advanced functionalities through precompiled contracts. These are a special kind of contracts that are bundled with the EVM at fixed addresses and can be called with a determined gas cost. The addresses start from 1, and increment for each contract. New hard forks may introduce new precompiled contracts. They are called from the opcodes like regular contracts, with instructions like CALL. The gas cost mentioned here is purely the cost of the contract and does not consider the cost of the call itself nor the instructions to put the parameters in memory. + +For Go-Ethereum, the code being run is written in Go, and the gas costs are defined in each precompile spec. + +In the case of ZKsync Era, ecAdd and ecMul precompiles are written as a smart contract for two reasons: + +- zkEVM needs to be able to prove their execution (and at the moment it cannot do that if the code being run is executed outside the VM) +- Writing custom circuits for Elliptic curve operations is hard, and time-consuming, and after all such code is harder to maintain and audit. + +## Field Arithmetic + +The BN254 (also known as alt-BN128) is an elliptic curve defined by the equation $y^2 = x^3 + 3$ over the finite field $\mathbb{F}_p$, being $p = 21888242871839275222246405745257275088696311157297823662689037894645226208583. The modulus is less than 256 bits, which is why every element in the field is represented as a `uint256`. + +The arithmetic is carried out with the field elements encoded in the Montgomery form. This is done not only because operating in the Montgomery form speeds up the computation but also because the native modular multiplication, which is carried out by Yul's `mulmod` opcode, is very inefficient. + +Instructions set on ZKsync and EVM are different, so the performance of the same Yul/Solidity code can be efficient on EVM, but not on zkEVM and opposite. + +One such very inefficient command is `mulmod`. On EVM there is a native opcode that makes modulo multiplication and it costs only 8 gas, which compared to the other opcodes costs is only 2-3 times more expensive. On zkEVM we don’t have native `mulmod` opcode, instead, the compiler does full-with multiplication (e.g. it multiplies two `uint256`s and gets as a result an `uint512`). Then the compiler performs long division for reduction (but only the remainder is kept), in the generic form it is an expensive operation and costs many opcode executions, which can’t be compared to the cost of one opcode execution. The worst thing is that `mulmod` is used a lot for the modulo inversion, so optimizing this one opcode gives a huge benefit to the precompiles. + +### Multiplication + +As said before, multiplication was carried out by implementing the Montgomery reduction, which works with general moduli and provides a significant speedup compared to the naïve approach. + +The squaring operation is obtained by multiplying a number by itself. However, this operation can have an additional speedup by implementing the SOS Montgomery squaring. + +### Inversion + +Inversion was performed using the extended binary Euclidean algorithm (also known as extended binary greatest common divisor). This algorithm is a modification of Algorithm 3 `MontInvbEEA` from [Montgomery inversion](https://cetinkayakoc.net/docs/j82.pdf). + +### Exponentiation + +The exponentiation was carried out using the square and multiply algorithm, which is a standard technique for this operation. + +## Montgomery Form + +Let’s take a number `R`, such that `gcd(N, R) == 1` and `R` is a number by which we can efficiently divide and take module over it (for example power of two or better machine word, aka 2^256). Then transform every number to the form of `x * R mod N` / `y * R mod N` and then we get efficient modulo addition and multiplication. The only thing is that before working with numbers we need to transform them to the form from `x mod N` to the `x * R mod N` and after performing operations transform the form back. + +For the latter, we will assume that `N` is the module that we use in computations, and `R` is $2^{256}$, since we can efficiently divide and take module over this number and it practically satisfies the property of `gcd(N, R) == 1`. + +### Montgomery Reduction Algorithm (REDC) + +> Reference: + +```solidity +/// @notice Implementation of the Montgomery reduction algorithm (a.k.a. REDC). +/// @dev See +/// @param lowestHalfOfT The lowest half of the value T. +/// @param higherHalfOfT The higher half of the value T. +/// @return S The result of the Montgomery reduction. +function REDC(lowestHalfOfT, higherHalfOfT) -> S { + let q := mul(lowestHalfOfT, N_PRIME()) + let aHi := add(higherHalfOfT, getHighestHalfOfMultiplication(q, P())) + let aLo, overflowed := overflowingAdd(lowestHalfOfT, mul(q, P())) + if overflowed { + aHi := add(aHi, 1) + } + S := aHi + if iszero(lt(aHi, P())) { + S := sub(aHi, P()) + } +} + +``` + +By choosing $R = 2^{256}$ we avoided 2 modulo operations and one division from the original algorithm. This is because in Yul, native numbers are uint256 and the modulo operation is native, but for the division, as we work with a 512-bit number split into two parts (high and low part) dividing by $R$ means shifting 256 bits to the right or what is the same, discarding the low part. + +### Montgomery Addition/Subtraction + +Addition and subtraction in Montgomery form are the same as ordinary modular addition and subtraction because of the distributive law + +$$ +\begin{align*} +aR+bR=(a+b)R,\\ +aR-bR=(a-b)R. +\end{align*} +$$ + +```solidity +/// @notice Computes the Montgomery addition. +/// @dev See for further details on the Montgomery multiplication. +/// @param augend The augend in Montgomery form. +/// @param addend The addend in Montgomery form. +/// @return ret The result of the Montgomery addition. +function montgomeryAdd(augend, addend) -> ret { + ret := add(augend, addend) + if iszero(lt(ret, P())) { + ret := sub(ret, P()) + } +} + +/// @notice Computes the Montgomery subtraction. +/// @dev See for further details on the Montgomery multiplication. +/// @param minuend The minuend in Montgomery form. +/// @param subtrahend The subtrahend in Montgomery form. +/// @return ret The result of the Montgomery subtraction. +function montgomerySub(minuend, subtrahend) -> ret { + ret := montgomeryAdd(minuend, sub(P(), subtrahend)) +} + +``` + +We do not use `addmod`. That's because in most cases the sum does not exceed the modulus. + +### Montgomery Multiplication + +The product of $aR \mod N$ and $bR \mod N$ is $REDC((aR \mod N)(bR \mod N))$. + +```solidity +/// @notice Computes the Montgomery multiplication using the Montgomery reduction algorithm (REDC). +/// @dev See for further details on the Montgomery multiplication. +/// @param multiplicand The multiplicand in Montgomery form. +/// @param multiplier The multiplier in Montgomery form. +/// @return ret The result of the Montgomery multiplication. +function montgomeryMul(multiplicand, multiplier) -> ret { + let hi := getHighestHalfOfMultiplication(multiplicand, multiplier) + let lo := mul(multiplicand, multiplier) + ret := REDC(lo, hi) +} + +``` + +### Montgomery Inversion + +```solidity +/// @notice Computes the Montgomery modular inverse skipping the Montgomery reduction step. +/// @dev The Montgomery reduction step is skipped because a modification in the binary extended Euclidean algorithm is used to compute the modular inverse. +/// @dev See the function `binaryExtendedEuclideanAlgorithm` for further details. +/// @param a The field element in Montgomery form to compute the modular inverse of. +/// @return invmod The result of the Montgomery modular inverse (in Montgomery form). +function montgomeryModularInverse(a) -> invmod { + invmod := binaryExtendedEuclideanAlgorithm(a) +} +``` + +As said before, we use a modified version of the bEE algorithm that lets us “skip” the Montgomery reduction step. + +The regular algorithm would be $REDC((aR \mod N)^{−1}(R^3 \mod N))$ which involves a regular inversion plus a multiplication by a value that can be precomputed. + +## ECADD + +Precompile for computing elliptic curve point addition. The points are represented in affine form, given by a pair of coordinates $(x,y)$. + +Affine coordinates are the conventional way of expressing elliptic curve points, which use 2 coordinates. The math is concise and easy to follow. + +For a pair of constants $a$ and $b$, an elliptic curve is defined by the set of all points $(x,y)$ that satisfy the equation $y^2=x^3+ax+b$, plus a special “point at infinity” named $O$. + +### Point Doubling + +To compute $2P$ (or $P+P$), there are three cases: + +- If $P = O$, then $2P = O$. +- Else $P = (x, y)$ + + - If $y = 0$, then $2P = O$. + - Else $y≠0$, then + + $$ + \begin{gather*} \lambda = \frac{3x_{p}^{2} + a}{2y_{p}} \\ x_{r} = \lambda^{2} - 2x_{p} \\ y_{r} = \lambda(x_{p} - x_{r}) - y_{p}\end{gather*} + $$ + +The complicated case involves approximately 6 multiplications, 4 additions/subtractions, and 1 division. There could also be 4 multiplications, 6 additions/subtractions, and 1 division, and if you want you could trade a multiplication with 2 more additions. + +### Point Addition + +To compute $P + Q$ where $P \neq Q$, there are four cases: + +- If $P = 0$ and $Q \neq 0$, then $P + Q = Q$. +- If $Q = 0$ and $P \neq 0$, then $P + Q = P$. +- Else $P = (x_{p},\ y_{p})$ and$Q = (x_{q},\ y_{q})$ + + - If $x_{p} = x_{q}$ (and necessarily $y_{p} \neq y_{q}$), then $P + Q = O$. + - Else $x_{p} \neq x_{q}$, then + + $$ + \begin{gather*} \lambda = \frac{y_{2} - y_{1}}{x_{2} - x_{1}} \\ x_{r} = \lambda^{2} - x_{p} - x_{q} \\ y_{r} = \lambda(x_{p} - x_{r}) - y_{p}\end{gather*} + $$ + + and $P + Q = R = (x_{r},\ y_{r})$. + +The complicated case involves approximately 2 multiplications, 6 additions/subtractions, and 1 division. + +## ECMUL + +Precompile for computing elliptic curve point scalar multiplication. The points are represented in homogeneous projective coordinates, given by the coordinates $(x , y , z)$. Transformation into affine coordinates can be done by applying the following transformation: +$(x,y) = (X.Z^{-1} , Y.Z^{-1} )$ if the point is not the point at infinity. + +The key idea of projective coordinates is that instead of performing every division immediately, we defer the divisions by multiplying them into a denominator. The denominator is represented by a new coordinate. Only at the very end, do we perform a single division to convert from projective coordinates back to affine coordinates. + +In affine form, each elliptic curve point has 2 coordinates, like $(x,y)$. In the new projective form, each point will have 3 coordinates, like $(X,Y,Z)$, with the restriction that $Z$ is never zero. The forward mapping is given by $(x,y)→(xz,yz,z)$, for any non-zero $z$ (usually chosen to be 1 for convenience). The reverse mapping is given by $(X,Y,Z)→(X/Z,Y/Z)$, as long as $Z$ is non-zero. + +### Point Doubling + +The affine form case $y=0$ corresponds to the projective form case $Y/Z=0$. This is equivalent to $Y=0$, since $Z≠0$. + +For the interesting case where $P=(X,Y,Z)$ and $Y≠0$, let’s convert the affine arithmetic to projective arithmetic. + +After expanding and simplifying the equations ([demonstration here](https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates)), the following substitutions come out + +$$ +\begin{align*} T &= 3X^{2} + aZ^{2},\\ U &= 2YZ,\\ V &= 2UXY,\\ W &= T^{2} - 2V \end{align*} +$$ + +Using them, we can write + +$$ +\begin{align*} X_{r} &= UW \\ Y_{r} &= T(V−W)−2(UY)^{2} \\ Z_{r} &= U^{3} \end{align*} +$$ + +As we can see, the complicated case involves approximately 18 multiplications, 4 additions/subtractions, and 0 divisions. + +### Point Addition + +The affine form case $x_{p} = x_{q}$ corresponds to the projective form case $X_{p}/Z_{p} = X_{q}/Z_{q}$. This is equivalent to $X_{p}Z_{q} = X_{q}Z_{p}$, via cross-multiplication. + +For the interesting case where $P = (X_{p},\ Y_{p},\ Z_{p})$ , $Q = (X_{q},\ Y_{q},\ Z_{q})$, and $X_{p}Z_{q} ≠ X_{q}Z_{p}$, let’s convert the affine arithmetic to projective arithmetic. + +After expanding and simplifying the equations ([demonstration here](https://www.nayuki.io/page/elliptic-curve-point-addition-in-projective-coordinates)), the following substitutions come out + +$$ +\begin{align*} +T_{0} &= Y_{p}Z_{q}\\ +T_{1} &= Y_{q}Z_{p}\\ +T &= T_{0} - T_{1}\\ +U_{0} &= X_{p}Z_{q}\\ +U_{1} &= X_{q}Z_{p}\\ +U &= U_{0} - U_{1}\\ +U_{2} &= U^{2}\\ +V &= Z_{p}Z_{q}\\ +W &= T^{2}V−U_{2}(U_{0}+U_{1}) \\ +\end{align*} +$$ + +Using them, we can write + +$$ +\begin{align*} X_{r} &= UW \\ Y_{r} &= T(U_{0}U_{2}−W)−T_{0}U^{3} \\ Z_{r} &= U^{3}V \end{align*} +$$ + +As we can see, the complicated case involves approximately 15 multiplications, 6 additions/subtractions, and 0 divisions. diff --git a/docs/l2_system_contracts/system_contracts_bootloader_description.md b/docs/l2_system_contracts/system_contracts_bootloader_description.md new file mode 100644 index 000000000..771f1c977 --- /dev/null +++ b/docs/l2_system_contracts/system_contracts_bootloader_description.md @@ -0,0 +1,728 @@ +# System contracts/bootloader description (VM v1.5.0) + +[back to readme](../README.md) + +## Bootloader + +On standard Ethereum clients, the workflow for executing blocks is the following: + +1. Pick a transaction, validate the transactions & charge the fee, execute it +2. Gather the state changes (if the transaction has not reverted), apply them to the state. +3. Go back to step (1) if the block gas limit has not been yet exceeded. + +However, having such flow on ZKsync (i.e. processing transaction one-by-one) would be too inefficient, since we have to run the entire proving workflow for each individual transaction. That’s what we need the _bootloader_ for: instead of running N transactions separately, we run the entire batch (set of blocks, more can be found [here](./batches_and_blocks_on_zksync.md)) as a single program that accepts the array of transactions as well as some other batch metadata and processes them inside a single big “transaction”. The easiest way to think about bootloader is to think in terms of EntryPoint from EIP4337: it also accepts the array of transactions and facilitates the Account Abstraction protocol. + +The hash of the code of the bootloader is stored on L1 and can only be changed as a part of a system upgrade. Note, that unlike system contracts, the bootloader’s code is not stored anywhere on L2. That’s why we may sometimes refer to the bootloader’s address as formal. It only exists for the sake of providing some value to `this` / `msg.sender`/etc. When someone calls the bootloader address (e.g. to pay fees) the EmptyContract’s code is actually invoked. + +## System contracts + +While most of the primitive EVM opcodes can be supported out of the box (i.e. zero-value calls, addition/multiplication/memory/storage management, etc), some of the opcodes are not supported by the VM by default and they are implemented via “system contracts” — these contracts are located in a special _kernel space,_ i.e. in the address space in range `[0..2^16-1]`, and they have some special privileges, which users’ contracts don’t have. These contracts are pre-deployed at the genesis and updating their code can be done only via system upgrade, managed from L1. + +The use of each system contract will be explained down below. + +### Pre-deployed contracts + +Some of the contracts need to be predeployed at the genesis, but they do not need the kernel space rights. To give them minimal permissiones, we predeploy them at consecutive addresses that start right at the `2^16`. These will be described in the following sections. + +## zkEVM internals + +Full specification of the zkEVM is beyond the scope of this document. However, this section will give you most of the details needed for understanding the L2 system smart contracts & basic differences between EVM and zkEVM. + +### Registers and memory management + +On EVM, during transaction execution, the following memory areas are available: + +- `memory` itself. +- `calldata` the immutable slice of parent memory. +- `returndata` the immutable slice returned by the latest call to another contract. +- `stack` where the local variables are stored. + +Unlike EVM, which is stack machine, zkEVM has 16 registers. Instead of receiving input from `calldata`, zkEVM starts by receiving a _pointer_ in its first register (_basically a packed struct with 4 elements: the memory page id, start and length of the slice to which it points to_) to the calldata page of the parent. Similarly, a transaction can receive some other additional data within its registers at the start of the program: whether the transaction should invoke the constructor ([more about deployments here](#contractdeployer--immutablesimulator)), whether the transaction has `isSystem` flag, etc. The meaning of each of these flags will be expanded further in this section. + +_Pointers_ are separate type in the VM. It is only possible to: + +- Read some value within a pointer. +- Shrink the pointer by reducing the slice to which pointer points to. +- Receive the pointer to the returndata/as a calldata. +- Pointers can be stored only on stack/registers to make sure that the other contracts can not read memory/returndata of contracts they are not supposed to. +- A pointer can be converted to the u256 integer representing it, but an integer can not be converted to a pointer to prevent unallowed memory access. +- It is not possible to return a pointer that points to a memory page with id smaller than the one for the current page. What this means is that it is only possible to `return` only pointer to the memory of the current frame or one of the pointers returned by the subcalls of the current frame. + +#### Memory areas in zkEVM + +For each frame, the following memory areas are allocated: + +- _Heap_ (plays the same role as `memory` on Ethereum). +- _AuxHeap_ (auxiliary heap). It has the same properties as Heap, but it is used for the compiler to encode calldata/copy the returndata from the calls to system contracts to not interfere with the standard Solidity memory alignment. +- _Stack_. Unlike Ethereum, stack is not the primary place to get arguments for opcodes. The biggest difference between stack on zkEVM and EVM is that on ZKsync stack can be accessed at any location (just like memory). While users do not pay for the growth of stack, the stack can be fully cleared at the end of the frame, so the overhead is minimal. +- _Code_. The memory area from which the VM executes the code of the contract. The contract itself can not read the code page, it is only done implicitly by the VM. + +Also, as mentioned in the previous section, the contract receives the pointer to the calldata. + +#### Managing returndata & calldata + +Whenever a contract finishes its execution, the parent’s frame receives a _pointer_ as `returndata`. This pointer may point to the child frame’s Heap/AuxHeap or it can even be the same `returndata` pointer that the child frame received from some of its child frames. + +The same goes with the `calldata`. Whenever a contract starts its execution, it receives the pointer to the calldata. The parent frame can provide any valid pointer as the calldata, which means it can either be a pointer to the slice of parent’s frame memory (heap or auxHeap) or it can be some valid pointer that the parent frame has received before as calldata/returndata. + +Contracts simply remember the calldata pointer at the start of the execution frame (it is by design of the compiler) and remembers the latest received returndata pointer. + +Some important implications of this is that it is now possible to do the following calls without any memory copying: + +A → B → C + +where C receives a slice of the calldata received by B. + +The same goes for returning data: + +A ← B ← C + +There is no need to copy returned data if the B returns a slice of the returndata returned by C. + +Note, that you can _not_ use the pointer that you received via calldata as returndata (i.e. return it at the end of the execution frame). Otherwise, it would be possible that returndata points to the memory slice of the active frame and allow editing the `returndata`. It means that in the examples above, C could not return a slice of its calldata without memory copying. + +Note, that the rule above is implemented by the principle "it is not possible to return a slice of data with memory page id lower than the memory page id of the current heap", since a memory page with smaller id could only be created before the call. That's why a user contract can usually safely return a slice of previously returned returndata (since it is guaranteed to have a higher memory page id). However, system contracts have an exemption from the rule above. It is needed in particular to the correct functionality of the `CodeOracle` system contract. You can read more about it [here](#codeoracle). So the rule of thumb is that returndata from `CodeOracle` should never be passed along. + +Some of these memory optimizations can be seen utilized in the [EfficientCall](../../system-contracts/contracts/libraries/EfficientCall.sol#L34) library that allows to perform a call while reusing the slice of calldata that the frame already has, without memory copying. + +#### Returndata & precompiles + +Some of the operations which are opcodes on Ethereum, have become calls to some of the system contracts. The most notable examples are `Keccak256`, `SystemContext`, etc. Note, that, if done naively, the following lines of code would work differently on ZKsync and Ethereum: + +```solidity +pop(call(...)) +keccak(...) +returndatacopy(...) +``` + +Since the call to keccak precompile would modify the `returndata`. To avoid this, our compiler does not override the latest `returndata` pointer after calls to such opcode-like precompiles. + +### ZKsync specific opcodes + +While some Ethereum opcodes are not supported out of the box, some of the new opcodes were added to facilitate the development of the system contracts. + +Note, that this lists does not aim to be specific about the internals, but rather explain methods in the [SystemContractHelper.sol](../../system-contracts/contracts/libraries/SystemContractHelper.sol#L44) + +#### **Only for kernel space** + +These opcodes are allowed only for contracts in kernel space (i.e. system contracts). If executed in other places they result in `revert(0,0)`. + +- `mimic_call`. The same as a normal `call`, but it can alter the `msg.sender` field of the transaction. +- `to_l1`. Sends a system L2→L1 log to Ethereum. The structure of this log can be seen [here](../../l1-contracts/contracts/common/Messaging.sol#L23). +- `event`. Emits an L2 log to ZKsync. Note, that L2 logs are not equivalent to Ethereum events. Each L2 log can emit 64 bytes of data (the actual size is 88 bytes, because it includes the emitter address, etc). A single Ethereum event is represented with multiple `event` logs constitute. This opcode is only used by `EventWriter` system contract. +- `precompile_call`. This is an opcode that accepts two parameters: the uint256 representing the packed parameters for it as well as the ergs to burn. Besides the price for the precompile call itself, it burns the provided ergs and executes the precompile. The action that it does depend on `this` during execution: + - If it is the address of the `ecrecover` system contract, it performs the ecrecover operation + - If it is the address of the `sha256`/`keccak256` system contracts, it performs the corresponding hashing operation. + - It does nothing (i.e. just burns ergs) otherwise. It can be used to burn ergs needed for L2→L1 communication or publication of bytecodes onchain. +- `setValueForNextFarCall` sets `msg.value` for the next `call`/`mimic_call`. Note, that it does not mean that the value will be really transferred. It just sets the corresponding `msg.value` context variable. The transferring of ETH should be done via other means by the system contract that uses this parameter. Note, that this method has no effect on `delegatecall` , since `delegatecall` inherits the `msg.value` of the previous frame. +- `increment_tx_counter` increments the counter of the transactions within the VM. The transaction counter used mostly for the VM’s internal tracking of events. Used only in bootloader after the end of each transaction. +- `decommit` will return a pointer to a slice with the corresponding bytecode hash preimage. If this bytecode has been unpacked before, the memory page where it was unpacked will be reused. If it has never been unpacked before, it will be unpacked into the current heap. + +Note, that currently we do not have access to the `tx_counter` within VM (i.e. for now it is possible to increment it and it will be automatically used for logs such as `event`s as well as system logs produced by `to_l1`, but we can not read it). We need to read it to publish the _user_ L2→L1 logs, so `increment_tx_counter` is always accompanied by the corresponding call to the [SystemContext](#systemcontext) contract. + +More on the difference between system and user logs can be read [here](../settlement_contracts/data_availability/standard_pubdata_format.md). + +#### **Generally accessible** + +Here are opcodes that can be generally accessed by any contract. Note that while the VM allows to access these methods, it does not mean that this is easy: the compiler might not have convenient support for some use-cases yet. + +- `near_call`. It is basically a “framed” jump to some location of the code of your contract. The difference between the `near_call` and ordinary jump are: + 1. It is possible to provide an ergsLimit for it. Note, that unlike “`far_call`”s (i.e. calls between contracts) the 63/64 rule does not apply to them. + 2. If the near call frame panics, all state changes made by it are reversed. Please note, that the memory changes will **not** be reverted. +- `getMeta`. Returns an u256 packed value of [ZkSyncMeta](../../system-contracts/contracts/libraries/SystemContractHelper.sol#L18) struct. Note that this is not tight packing. The struct is formed by the [following rust code](https://github.com/matter-labs/zksync-protocol/blob/main/crates/zkevm_opcode_defs/src/definitions/abi/meta.rs#L4). +- `getCodeAddress` — receives the address of the executed code. This is different from `this` , since in case of delegatecalls `this` is preserved, but `codeAddress` is not. + +#### Flags for calls + +Besides the calldata, it is also possible to provide additional information to the callee when doing `call` , `mimic_call`, `delegate_call`. The called contract will receive the following information in its first 12 registers at the start of execution: + +- _r1_ — the pointer to the calldata. +- _r2_ — the pointer with flags of the call. This is a mask, where each bit is set only if certain flags have been set to the call. Currently, two flags are supported: 0-th bit: `isConstructor` flag. This flag can only be set by system contracts and denotes whether the account should execute its constructor logic. Note, unlike Ethereum, there is no separation on constructor & deployment bytecode. More on that can be read [here](#contractdeployer--immutablesimulator). 1-st bit: `isSystem` flag. Whether the call intends a system contracts’ function. While most of the system contracts’ functions are relatively harmless, accessing some with calldata only may break the invariants of Ethereum, e.g. if the system contract uses `mimic_call`: no one expects that by calling a contract some operations may be done out of the name of the caller. This flag can be only set if the callee is in kernel space. +- The rest r3..r12 registers are non-empty only if the `isSystem` flag is set. There may be arbitrary values passed, which we call `extraAbiParams`. + +The compiler implementation is that these flags are remembered by the contract and can be accessed later during execution via special [simulations](https://github.com/code-423n4/2024-03-zksync/blob/main/docs/VM%20Section/How%20compiler%20works/instructions/extensions/overview.md). + +If the caller provides inappropriate flags (i.e. tries to set `isSystem` flag when callee is not in the kernel space), the flags are ignored. + +#### `onlySystemCall` modifier + +Some of the system contracts can act on behalf of the user or have a very important impact on the behavior of the account. That’s why we wanted to make it clear that users can not invoke potentially dangerous operations by doing a simple EVM-like `call`. Whenever a user wants to invoke some of the operations which we considered dangerous, they must provide “`isSystem`” flag with them. + +The `onlySystemCall` flag checks that the call was either done with the “isSystemCall” flag provided or the call is done by another system contract (since Matter Labs is fully aware of system contracts). + +#### Simulations via our compiler + +In the future, we plan to introduce our “extended” version of Solidity with more supported opcodes than the original one. However, right now it was beyond the capacity of the team to do, so in order to represent accessing ZKsync-specific opcodes, we use `call` opcode with certain constant parameters that will be automatically replaced by the compiler with zkEVM native opcode. + +Example: + +```solidity +function getCodeAddress() internal view returns (address addr) { + address callAddr = CODE_ADDRESS_CALL_ADDRESS; + assembly { + addr := staticcall(0, callAddr, 0, 0xFFFF, 0, 0) + } +} +``` + +In the example above, the compiler will detect that the static call is done to the constant `CODE_ADDRESS_CALL_ADDRESS` and so it will replace it with the opcode for getting the code address of the current execution. + +Full list of opcode simulations can be found [here](https://github.com/code-423n4/2024-03-zksync/blob/main/docs/VM%20Section/How%20compiler%20works/instructions/extensions/call.md). + +We also use [verbatim-like](https://github.com/code-423n4/2024-03-zksync/blob/main/docs/VM%20Section/How%20compiler%20works/instructions/extensions/verbatim.md) statements to access ZKsync-specific opcodes in the bootloader. + +All the usages of the simulations in our Solidity code are implemented in the [SystemContractHelper](../../system-contracts/contracts/libraries//SystemContractHelper.sol) library and the [SystemContractsCaller](../../system-contracts/contracts//libraries/SystemContractsCaller.sol) library. + +#### Simulating `near_call` (in Yul only) + +In order to use `near_call` i.e. to call a local function, while providing a limit of ergs (gas) that this function can use, the following syntax is used: + +The function should contain `ZKSYNC_NEAR_CALL` string in its name and accept at least 1 input parameter. The first input parameter is the packed ABI of the `near_call`. Currently, it is equal to the number of ergs to be passed with the `near_call`. + +Whenever a `near_call` panics, the `ZKSYNC_CATCH_NEAR_CALL` function is called. + +_Important note:_ the compiler behaves in a way that if there is a `revert` in the bootloader, the `ZKSYNC_CATCH_NEAR_CALL` is not called and the parent frame is reverted as well. The only way to revert only the `near_call` frame is to trigger VM’s _panic_ (it can be triggered with either invalid opcode or out of gas error). + +_Important note 2:_ The 63/64 rule does not apply to `near_call`. Also, if 0 gas is provided to the near call, then actually all of the available gas will go to it. + +#### Notes on security + +To prevent unintended substitution, the compiler requires `--system-mode` flag to be passed during compilation for the above substitutions to work. + +> Note, that in the more recent compiler versions this the `--system-mode` has been renamed to `enable_eravm_extensions` (this can be seen in e.g. our [foundry.toml](../../l1-contracts/foundry.toml)) + +### Bytecode hashes + +On ZKsync the bytecode hashes are stored in the following format: + +- The 0th byte denotes the version of the format. Currently the only version that is used is “1”. +- The 1st byte is `0` for deployed contracts’ code and `1` for the contract code [that is being constructed](#constructing-vs-non-constructing-code-hash). +- The 2nd and 3rd bytes denote the length of the contract in 32-byte words as big-endian 2-byte number. +- The next 28 bytes are the last 28 bytes of the sha256 hash of the contract’s bytecode. + +The bytes are ordered in little-endian order (i.e. the same way as for `bytes32` ). + +#### Bytecode validity + +A bytecode is valid if it: + +- Has its length in bytes divisible by 32 (i.e. consists of an integer number of 32-byte words). +- Has a length of less than 2^16 words (i.e. its length in words fits into 2 bytes). +- Has an odd length in words (i.e. the 3rd byte is an odd number). + +Note, that it does not have to consist of only correct opcodes. In case the VM encounters an invalid opcode, it will simply revert (similar to how EVM would treat them). + +A call to a contract with invalid bytecode can not be proven. That is why it is **essential** that no contract with invalid bytecode is ever deployed on ZKsync. It is the job of the [KnownCodesStorage](#knowncodestorage) to ensure that all allowed bytecodes in the system are valid. + +## Account abstraction + +One of the other important features of ZKsync is the support of account abstraction. It is highly recommended to read the documentation on our AA protocol here: [https://docs.zksync.io/zk-stack/concepts/account-abstraction](https://docs.zksync.io/zk-stack/concepts/account-abstraction) + +#### Account versioning + +Each account can also specify which version of the account abstraction protocol do they support. This is needed to allow breaking changes of the protocol in the future. + +Currently, two versions are supported: `None` (i.e. it is a simple contract and it should never be used as `from` field of a transaction), and `Version1`. + +#### Nonce ordering + +Accounts can also signal to the operator which nonce ordering it should expect from these accounts: `Sequential` or `Arbitrary`. + +`Sequential` means that the nonces should be ordered in the same way as in EOAs. This means, that, for instance, the operator will always wait for a transaction with nonce `X` before processing a transaction with nonce `X+1`. + +`Arbitrary` means that the nonces can be ordered in arbitrary order. It is supported by the server right now, i.e. if there is a contract with arbitrary nonce ordering, its transactions will likely either be rejected or get stuck in the mempool due to nonce mismatch. + +Note, that this is not enforced by system contracts in any way. Some sanity checks may be present, but the accounts are allowed to do however they like. It is more of a suggestion to the operator on how to manage the mempool. + +#### Returned magic value + +Now, both accounts and paymasters are required to return a certain magic value upon validation. This magic value will be enforced to be correct on the mainnet, but will be ignored during fee estimation. Unlike Ethereum, the signature verification + fee charging/nonce increment are not included as part of the intrinsic costs of the transaction. These are paid as part of the execution and so they need to be estimated as part of the estimation for the transaction’s costs. + +Generally, the accounts are recommended to perform as many operations as during normal validation, but only return the invalid magic in the end of the validation. This will allow to correctly (or at least as correctly as possible) estimate the price for the validation of the account. + +## Bootloader + +Bootloader is the program that accepts an array of transactions and executes the entire ZKsync batch. This section will expand on its invariants and methods. + +### Playground bootloader vs proved bootloader + +For convenience, we use the same implementation of the bootloader both in the mainnet batches and for emulating ethCalls or other testing activities. _Only_ _proved_ bootloader is ever used for batch-building and thus this document describes only it. + +### Start of the batch + +It is enforced by the ZKPs, that the state of the bootloader is equivalent to the state of a contract transaction with empty calldata. The only difference is that it starts with all the possible memory pre-allocated (to avoid costs for memory expansion). + +For additional efficiency (and our convenience), the bootloader receives its parameters inside its memory. This is the only point of non-determinism: the bootloader _starts with its memory pre-filled with any data the operator wants_. That’s why it is responsible for validating the correctness of it and it should never rely on the initial contents of the memory to be correct & valid. + +For instance, for each transaction, we check that it is [properly ABI-encoded](../../system-contracts/bootloader/bootloader.yul#L4044) and that the transactions [go exactly one after another](../../system-contracts/bootloader/bootloader.yul#L4037). We also ensure that transactions do not exceed the limits of the memory space allowed for transactions. + +### Transaction types & their validation + +While the main transaction format is the internal `Transaction` [format](../../system-contracts/contracts/libraries/TransactionHelper.sol#L25), it is a struct that is used to represent various kinds of transactions types. It contains a lot of `reserved` fields that could be used depending in the future types of transactions without need for AA to change the interfaces of their contracts. + +The exact type of the transaction is marked by the `txType` field of the transaction type. There are 6 types currently supported: + +- `txType`: 0. It means that this transaction is of legacy transaction type. The following restrictions are enforced: +- `maxFeePerErgs=getMaxPriorityFeePerErg` since it is pre-EIP1559 tx type. +- `reserved1..reserved4` as well as `paymaster` are 0. `paymasterInput` is zero. +- Note, that unlike type 1 and type 2 transactions, `reserved0` field can be set to a non-zero value, denoting that this legacy transaction is EIP-155-compatible and its RLP encoding (as well as signature) should contain the `chainId` of the system. +- `txType`: 1. It means that the transaction is of type 1, i.e. transactions access list. ZKsync does not support access lists in any way, so no benefits of fulfilling this list will be provided. The access list is assumed to be empty. The same restrictions as for type 0 are enforced, but also `reserved0` must be 0. +- `txType`: 2. It is EIP1559 transactions. The same restrictions as for type 1 apply, but now `maxFeePerErgs` may not be equal to `getMaxPriorityFeePerErg`. +- `txType`: 113. It is ZKsync transaction type. This transaction type is intended for AA support. The only restriction that applies to this transaction type: fields `reserved0..reserved4` must be equal to 0. +- `txType`: 254. It is a transaction type that is used for upgrading the L2 system. This is the only type of transaction is allowed to start a transaction out of the name of the contracts in kernel space. +- `txType`: 255. It is a transaction that comes from L1. There are almost no restrictions explicitly imposed upon this type of transaction, since the bootloader at the end of its execution sends the rolling hash of the executed priority transactions. The L1 contract ensures that the hash did indeed match the [hashes of the priority transactions on L1](../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L376). + +You can also read more on L1->L2 transactions and upgrade transactions [here](../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md). + +However, as already stated, the bootloader’s memory is not deterministic and the operator is free to put anything it wants there. For all of the transaction types above the restrictions are imposed in the following ([method](../../system-contracts/bootloader/bootloader.yul#L3107)), which is called before starting processing the transaction. + +### Structure of the bootloader’s memory + +The bootloader expects the following structure of the memory (here by word we denote 32-bytes, the same machine word as on EVM): + +#### **Batch information** + +The first 8 words are reserved for the batch information provided by the operator. + +- `0` word — the address of the operator (the beneficiary of the transactions). +- `1` word — the hash of the previous batch. Its validation will be explained later on. +- `2` word — the timestamp of the current batch. Its validation will be explained later on. +- `3` word — the number of the new batch. +- `4` word — the fair pubdata price. More on how our pubdata is calculated can be read [here](./zksync_fee_model.md). +- `5` word — the “fair” price for L2 gas, i.e. the price below which the `baseFee` of the batch should not fall. For now, it is provided by the operator, but it in the future it may become hardcoded. +- `6` word — the base fee for the batch that is expected by the operator. While the base fee is deterministic, it is still provided to the bootloader just to make sure that the data that the operator has coincides with the data provided by the bootloader. +- `7` word — reserved word. Unused on proved batch. + +The batch information slots [are used at the beginning of the batch](../../system-contracts/bootloader/bootloader.yul#3921). Once read, these slots can be used for temporary data. + +#### **Temporary data for debug & transaction processing purposes** + +- `[8..39]` – reserved slots for debugging purposes +- `[40..72]` – slots for holding the paymaster context data for the current transaction. The role of the paymaster context is similar to the [EIP4337](https://eips.ethereum.org/EIPS/eip-4337)’s one. You can read more about it in the account abstraction documentation. +- `[73..74]` – slots for signed and explorer transaction hash of the currently processed L2 transaction. +- `[75..142]` – 68 slots for the calldata for the KnownCodesContract call. +- `[143..10142]` – 10000 slots for the refunds for the transactions. +- `[10143..20142]` – 10000 slots for the overhead for batch for the transactions. This overhead is suggested by the operator, i.e. the bootloader will still double-check that the operator does not overcharge the user. +- `[20143..30142]` – slots for the “trusted” gas limits by the operator. The user’s transaction will have at its disposal `min(MAX_TX_GAS(), trustedGasLimit)`, where `MAX_TX_GAS` is a constant guaranteed by the system. Currently, it is equal to 80 million gas. In the future, this feature will be removed. +- `[30143..70146]` – slots for storing L2 block info for each transaction. You can read more on the difference L2 blocks and batches [here](./batches_and_blocks_on_zksync.md). +- `[70147..266754]` – slots used for compressed bytecodes each in the following format: + - 32 bytecode hash + - 32 zeroes (but then it will be modified by the bootloader to contain 28 zeroes and then the 4-byte selector of the `publishCompressedBytecode` function of the `BytecodeCompressor`) + - The calldata to the bytecode compressor (without the selector). +- `[266755..266756]` – slots where the hash and the number of current priority ops is stored. More on it in the priority operations [section](../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md). + +#### L1Messenger Pubdata + +- `[266757..1626756]` – slots where the final batch pubdata is supplied to be verified by the [L2DAValidator](../settlement_contracts/data_availability/custom_da.md). + +But briefly, this space is used for the calldata to the L1Messenger’s `publishPubdataAndClearState` function, which accepts the address of the L2DAValidator as well as the pubdata for it to check. The L2DAValidator is a contract that is responsible to ensure efficiency [when handling pubdata](../settlement_contracts/data_availability/custom_da.md). Typically, the calldata `L2DAValidator` would include uncompressed preimages for bytecodes, L2->L1 messages, L2->L1 logs, etc as their compressed counterparts. However, the exact implementation may vary across various ZK chains. + +Note, that while the realistic number of pubdata that can be published in a batch is ~780kb, the size of the calldata to L1Messenger may be a lot larger due to the fact that this method also accepts the original uncompressed state diff entries. These will not be published to L1, but will be used to verify the correctness of the compression. + +One of "worst case" scenarios for the number of state diffs in a batch is when 780kb of pubdata is spent on repeated writes, that are all zeroed out. In this case, the number of diffs is 780kb / 5 = 156k. This means that they will have accoomdate 42432000 bytes of calldata for the uncompressed state diffs. Adding 780kb on top leaves us with roughly 43212000 bytes needed for calldata. 1350375 slots are needed to accommodate this amount of data. We round up to 1360000 slots just in case. + +In theory though much more calldata could be used (if for instance 1 byte is used for enum index). It is the responsibility of the +operator to ensure that it can form the correct calldata for the L1Messenger. + +#### **Transaction’s meta descriptions** + +- `[1626756..1646756]` words — 20000 slots for 10000 transaction’s meta descriptions (their structure is explained below). + +For internal reasons related to possible future integrations of zero-knowledge proofs about some of the contents of the bootloader’s memory, the array of the transactions is not passed as the ABI-encoding of the array of transactions, but: + +- We have a constant maximum number of transactions. At the time of this writing, this number is 10000. +- Then, we have 10000 transaction descriptions, each ABI encoded as the following struct: + +```solidity +struct BootloaderTxDescription { + // The offset by which the ABI-encoded transaction's data is stored + uint256 txDataOffset; + // Auxiliary data on the transaction's execution. In our internal versions + // of the bootloader it may have some special meaning, but for the + // bootloader used on the mainnet it has only one meaning: whether to execute + // the transaction. If 0, no more transactions should be executed. If 1, then + // we should execute this transaction and possibly try to execute the next one. + uint256 txExecutionMeta; +} +``` + +#### **Reserved slots for the calldata for the paymaster’s postOp operation** + +- `[1646756..1646795]` words — 40 slots which could be used for encoding the calls for postOp methods of the paymaster. + +To avoid additional copying of transactions for calls for the account abstraction, we reserve some of the slots which could be then used to form the calldata for the `postOp` call for the account abstraction without having to copy the entire transaction’s data. + +#### **The actual transaction’s descriptions** + +- `[1646796..1967599]` + +Starting from the 487312 word, the actual descriptions of the transactions start. (The struct can be found by this [link](../../system-contracts/contracts/libraries/TransactionHelper.sol#L25)). The bootloader enforces that: + +- They are correctly ABI encoded representations of the struct above. +- They are located without any gaps in memory (the first transaction starts at word 653 and each transaction goes right after the next one). +- The contents of the currently processed transaction (and the ones that will be processed later on are untouched). Note, that we do allow overriding data from the already processed transactions as it helps to preserve efficiency by not having to copy the contents of the `Transaction` each time we need to encode a call to the account. + +#### **VM hook pointers** + +- `[1967600..1967602]` + +These are memory slots that are used purely for debugging purposes (when the VM writes to these slots, the server side can catch these calls and give important insight information for debugging issues). + +#### **Result ptr pointer** + +- `[1967602..1977602]` + +These are memory slots that are used to track the success status of a transaction. If the transaction with number `i` succeeded, the slot `937499 - 10000 + i` will be marked as 1 and 0 otherwise. + +### General flow of the bootloader’s execution + +1. At the start of the batch it [reads the initial batch information](../../system-contracts/bootloader/bootloader.yul#L3928) and [sends the information](../../system-contracts/bootloader/bootloader.yul#L2857) about the current batch to the SystemContext system contract. +2. It goes through each of [transaction’s descriptions](../../system-contracts/bootloader/bootloader.yul#L4016) and checks whether the `execute` field is set. If not, it ends processing of the transactions and ends execution of the batch. If the execute field is non-zero, the transaction will be executed and it goes to step 3. +3. Based on the transaction’s type it decides whether the transaction is an L1 or L2 transaction and processes them accordingly. More on the processing of the L1 transactions can be read [here](#l1-l2-transactions). More on L2 transactions can be read [here](#l2-transactions). + +### L2 transactions + +On ZKsync, every address is a contract. Users can start transactions from their EOA accounts, because every address that does not have any contract deployed on it implicitly contains the code defined in the [DefaultAccount.sol](../../system-contracts/contracts/DefaultAccount.sol) file. Whenever anyone calls a contract that is not in kernel space (i.e. the address is ≥ 2^16) and does not have any contract code deployed on it, the code for `DefaultAccount` will be used as the contract’s code. + +Note, that if you call an account that is in kernel space and does not have any code deployed there, right now, the transaction will revert. + +We process the L2 transactions according to our account abstraction protocol: [https://docs.zksync.io/build/developer-reference/account-abstraction](https://docs.zksync.io/build/developer-reference/account-abstraction). + +1. We [deduct](../../system-contracts/bootloader/bootloader.yul#L1263) the transaction’s upfront payment for the overhead for the block’s processing. You can read more on how that works in the fee model [description](./zksync_fee_model.md). +2. Then we calculate the gasPrice for these transactions according to the EIP1559 rules. +3. We [conduct the validation step](../../system-contracts/bootloader/bootloader.yul#L1287) of the AA protocol: + + - We calculate the hash of the transaction. + - If enough gas has been provided, we near_call the validation function in the bootloader. It sets the tx.origin to the address of the bootloader, sets the ergsPrice. It also marks the factory dependencies provided by the transaction as marked and then invokes the validation method of the account and verifies the returned magic. + - Calls the accounts and, if needed, the paymaster to receive the payment for the transaction. Note, that accounts may not use `block.baseFee` context variable, so they have no way to know what exact sum to pay. That’s why the accounts typically firstly send `tx.maxFeePerErg * tx.ergsLimit` and the bootloader [refunds](../../system-contracts/bootloader/bootloader.yul#L792) for any excess funds sent. + +4. [We perform the execution of the transaction](../../system-contracts/bootloader/bootloader.yul#L1352). Note, that if the sender is an EOA, tx.origin is set equal to the `from` the value of the transaction. During the execution of the transaction, the publishing of the compressed bytecodes happens: for each factory dependency if it has not been published yet and its hash is currently pointed to in the compressed bytecodes area of the bootloader, a call to the bytecode compressor is done. Also, at the end the call to the KnownCodeStorage is done to ensure all the bytecodes have indeed been published. +5. We [refund](../../system-contracts/bootloader/bootloader.yul#L1206) the user for any excess funds he spent on the transaction: + + - Firstly, the `postTransaction` operation is called to the paymaster. + - The bootloader asks the operator to provide a refund. During the first VM run without proofs the provide directly inserts the refunds in the memory of the bootloader. During the run for the proved batches, the operator already knows what which values have to be inserted there. You can read more about it in the [documentation](./zksync_fee_model.md) of the fee model. + - The bootloader refunds the user. + +6. We notify the operator about the [refund](../../system-contracts/bootloader/bootloader.yul#L1217) that was granted to the user. It will be used for the correct displaying of gasUsed for the transaction in explorer. + +### L1->L2 transactions + +L1->L2 transactions are transactions that were initiated on L1. We assume that `from` has already authorized the L1→L2 transactions. It also has its L1 pubdata price as well as ergsPrice set on L1. + +Most of the steps from the execution of L2 transactions are omitted and we set `tx.origin` to the `from`, and `ergsPrice` to the one provided by transaction. After that, we use [mimicCall](#zksync-specific-opcodes) to provide the operation itself from the name of the sender account. + +Note, that for L1→L2 transactions, `reserved0` field denotes the amount of ETH that should be minted on L2 as a result of this transaction. `reserved1` is the refund receiver address, i.e. the address that would receive the refund for the transaction as well as the msg.value if the transaction fails. + +There are two kinds of L1->L2 transactions: + +- Priority operations, initiated by users (they have type `255`). +- Upgrade transactions, that can be initiated during system upgrade (they have type `254`). + +You can read more about differences between those in the corresponding [document](../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md). + +### End of the batch + +At the end of the batch we set `tx.origin` and `tx.gasprice` context variables to zero to save L1 gas on calldata and send the entire bootloader balance to the operator, effectively sending fees to him. + +Also, we [set](../../system-contracts/bootloader/bootloader.yul#L4110) the fictive L2 block’s data. Then, we call the system context to ensure that it publishes the timestamp of the L2 block as well as L1 batch. We also reset the `txNumberInBlock` counter to avoid its state diffs from being published on L1. You can read more about block processing on ZKsync [here](./batches_and_blocks_on_zksync.md). + +After that, we publish the hash as well as the number of priority operations in this batch. More on it [here](../settlement_contracts/priority_queue/processing_of_l1->l2_txs.md). + +Then, we call the L1Messenger system contract for it to compose the pubdata to be published on L1. You can read more about the pubdata processing [here](../settlement_contracts/data_availability/standard_pubdata_format.md). + +## System contracts + +Most of the details on the implementation and the requirements for the execution of system contracts can be found in the doc-comments of their respective code bases. This chapter serves only as a high-level overview of such contracts. + +All the codes of system contracts (including `DefaultAccount`s) are part of the protocol and can only be change via a system upgrade through L1. + +### SystemContext + +This contract is used to support various system parameters not included in the VM by default, i.e. `chainId`, `origin`, `ergsPrice`, `blockErgsLimit`, `coinbase`, `difficulty`, `baseFee`, `blockhash`, `block.number`, `block.timestamp.` + +It is important to note that the constructor is **not** run for this contract upon genesis, i.e. the constant context values are set on genesis explicitly. Notably, if in the future we want to upgrade the contracts, we will do it via [ContractDeployer](#contractdeployer--immutablesimulator) and so the constructor will be run. + +This contract is also responsible for ensuring validity and consistency of batches, L2 blocks. The implementation itself is rather straightforward, but to better understand this contract, please take a look at the [page](./batches_and_blocks_on_zksync.md) about the block processing on ZKsync. + +### AccountCodeStorage + +The code hashes of accounts are stored inside the storage of this contract. Whenever a VM calls a contract with address `address` it retrieves the value under storage slot `address` of this system contract, if this value is non-zero, it uses this as the code hash of the account. + +Whenever a contract is called, the VM asks the operator to provide the preimage for the codehash of the account. That is why data availability of the code hashes is paramount. + +#### Constructing vs Non-constructing code hash + +In order to prevent contracts from being able to call a contract during its construction, we set the marker (i.e. second byte of the bytecode hash of the account) as `1`. This way, the VM will ensure that whenever a contract is called without the `isConstructor` flag, the bytecode of the default account (i.e. EOA) will be substituted instead of the original bytecode. + +### BootloaderUtilities + +This contract contains some of the methods which are needed purely for the bootloader functionality but were moved out from the bootloader itself for the convenience of not writing this logic in Yul. + +### DefaultAccount + +Whenever a contract that does **not** both: + +- belong to kernel space +- have any code deployed on it (the value stored under the corresponding storage slot in `AccountCodeStorage` is zero) + +The code of the default account is used. The main purpose of this contract is to provide EOA-like experience for both wallet users and contracts that call it, i.e. it should not be distinguishable (apart of spent gas) from EOA accounts on Ethereum. + +### Ecrecover + +The implementation of the ecrecover precompile. It is expected to be used frequently, so written in pure yul with a custom memory layout. + +The contract accepts the calldata in the same format as EVM precompile, i.e. the first 32 bytes are the hash, the next 32 bytes are the v, the next 32 bytes are the r, and the last 32 bytes are the s. + +It also validates the input by the same rules as the EVM precompile: + +- The v should be either 27 or 28, +- The r and s should be less than the curve order. + +After that, it makes a precompile call and returns empty bytes if the call failed, and the recovered address otherwise. + +### Empty contracts + +Some of the contracts are relied upon to have EOA-like behaviour, i.e. they can be always called and get the success value in return. An example of such address is 0 address. We also require the bootloader to be callable so that the users could transfer ETH to it. + +For these contracts, we insert the `EmptyContract` code upon genesis. It is basically a noop code, which does nothing and returns `success=1`. + +### SHA256 & Keccak256 + +Note that, unlike Ethereum, keccak256 is a precompile (_not an opcode_) on ZKsync. + +These system contracts act as wrappers for their respective crypto precompile implementations. They are expected to be used frequently, especially keccak256, since Solidity computes storage slots for mapping and dynamic arrays with its help. That's why we wrote contracts on pure yul with optimizing the short input case. In the past both `sha256` and `keccak256` performed padding within the smart contracts, this is no longer true with `sha256` performing padding in the smart contracts and `keccak256` in the zk-circuits. Hashing is then completed for both within the zk-circuits. + +It's important to note that the crypto part of the `sha256` precompile expects to work with padded data. This means that a bug in applying padding may lead to an unprovable transaction. + +### EcAdd & EcMul + +These precompiles simulate the behaviour of the EVM's EcAdd and EcMul precompiles and are fully implemented in Yul without circuit counterparts. You can read more about them [here](./elliptic_curve_precompiles.md). + +### L2BaseToken & MsgValueSimulator + +Unlike Ethereum, zkEVM does not have any notion of any special native token. That’s why we have to simulate operations with the native token (in which fees are charged) via two contracts: `L2BaseToken` & `MsgValueSimulator`. + +`L2BaseToken` is a contract that holds the balances of native token for the users. This contract does NOT provide ERC20 interface. The only method for transferring native token is `transferFromTo`. It permits only some system contracts to transfer on behalf of users. This is needed to ensure that the interface is as close to Ethereum as possible, i.e. the only way to transfer native token is by doing a call to a contract with some `msg.value`. This is what `MsgValueSimulator` system contract is for. + +Whenever anyone wants to do a non-zero value call, they need to call `MsgValueSimulator` with: + +- The calldata for the call equal to the original one. +- Pass `value` and whether the call should be marked with `isSystem` in the first extra abi params. +- Pass the address of the callee in the second extraAbiParam. + +More information on the extraAbiParams can be read [here](#flags-for-calls). + +#### Support for `.send/.transfer` + +On Ethereum, whenever a call with non-zero value is done, some additional gas is charged from the caller's frame and in return a `2300` gas stipend is given out to the callee frame. This stipend is usually enough to emit a small event, but it is enforced that it is not possible to change storage within these `2300` gas. This also means that in practice some users might opt to do `call` with 0 gas provided, relying on the `2300` stipend to be passed to the callee. This is the case for `.call/.transfer`. + +While using `.send/.transfer` is generally not recommended, as a step towards better EVM compatibility, since vm1.5.0 a _partial_ support of these functions is present with ZKsync Era. It is the done via the following means: + +- Whenever a call is done to the `MsgValueSimulator` system contract, `27000` gas is deducted from the caller's frame and it passed to the `MsgValueSimulator` on top of whatever gas the user has originally provided. The number was chosen to cover for the execution of the transferring of the balances as well as other constant size operations by the `MsgValueSimulator`. Note, that since it will be the frame of `MsgValueSimulator` that will actually call the callee, the constant must also include the cost for decommitting the code of the callee. Decoding bytecode of any size would be prohibitevely expensive and so we support only callees of size up to `100000` bytes. +- `MsgValueSimulator` ensures that no more than `2300` out of the stipend above gets to the callee, ensuring the reentrancy protection invariant for these functions holds. + +Note, that unlike EVM any unused gas from such calls will be refunded. + +The system preserves the following guarantees about `.send/.transfer`: + +- No more than `2300` gas will be received by the callee. Note, [that a smaller, but a close amount](../../system-contracts/contracts/test-contracts/TransferTest.sol#L33) may be passed. +- It is not possible to do any storage changes within this stipend. This is enforced by having cold write cost more than `2300` gas. Also, cold write cost always has to be prepaid whenever executing storage writes. More on it can be read [here](../l2_system_contracts/zksync_fee_model.md#io-pricing). +- Any callee with bytecode size of up to `100000` will work. + +The system does not guarantee the following: + +- That callees with bytecode size larger than `100000` will work. Note, that a malicious operator can fail any call to a callee with large bytecode even if it has been decommitted before. More on it can be read [here](../l2_system_contracts/zksync_fee_model.md#io-pricing). + +As a conclusion, using `.send/.transfer` should be generally avoided, but when avoiding is not possible it should be used with small callees, e.g. EOAs, which implement [DefaultAccount](../../system-contracts/contracts/DefaultAccount.sol). + +### KnownCodeStorage + +This contract is used to store whether a certain code hash is “known”, i.e. can be used to deploy contracts. On ZKsync, the L2 stores the contract’s code _hashes_ and not the codes themselves. Therefore, it must be part of the protocol to ensure that no contract with unknown bytecode (i.e. hash with an unknown preimage) is ever deployed. + +The factory dependencies field provided by the user for each transaction contains the list of the contract’s bytecode hashes to be marked as known. We can not simply trust the operator to “know” these bytecodehashes as the operator might be malicious and hide the preimage. We ensure the availability of the bytecode in the following way: + +- If the transaction comes from L1, i.e. all its factory dependencies have already been published on L1, we can simply mark these dependencies as “known”. +- If the transaction comes from L2, i.e. (the factory dependencies are yet to publish on L1), we make the user pays by burning ergs proportional to the bytecode’s length. After that, we send the L2→L1 log with the bytecode hash of the contract. It is the responsibility of the L1 contracts to verify that the corresponding bytecode hash has been published on L1. + +It is the responsibility of the [ContractDeployer](#contractdeployer--immutablesimulator) system contract to deploy only those code hashes that are known. + +The KnownCodesStorage contract is also responsible for ensuring that all the “known” bytecode hashes are also [valid](#bytecode-validity). + +### ContractDeployer & ImmutableSimulator + +`ContractDeployer` is a system contract responsible for deploying contracts on ZKsync. It is better to understand how it works in the context of how the contract deployment works on ZKsync. Unlike Ethereum, where `create`/`create2` are opcodes, on ZKsync these are implemented by the compiler via calls to the ContractDeployer system contract. + +For additional security, we also distinguish the deployment of normal contracts and accounts. That’s why the main methods that will be used by the user are `create`, `create2`, `createAccount`, `create2Account`, which simulate the CREATE-like and CREATE2-like behavior for deploying normal and account contracts respectively. + +#### **Address derivation** + +Each rollup that supports L1→L2 communications needs to make sure that the addresses of contracts on L1 and L2 do not overlap during such communication (otherwise it would be possible that some evil proxy on L1 could mutate the state of the L2 contract). Generally, rollups solve this issue in two ways: + +- XOR/ADD some kind of constant to addresses during L1→L2 communication. That’s how rollups closer to full EVM-equivalence solve it, since it allows them to maintain the same derivation rules on L1 at the expense of contract accounts on L1 having to redeploy on L2. +- Have different derivation rules from Ethereum. That is the path that ZKsync has chosen, mainly because since we have different bytecode than on EVM, CREATE2 address derivation would be different in practice anyway. + +You can see the rules for our address derivation in `getNewAddressCreate2`/ `getNewAddressCreate` methods in the ContractDeployer. + +Note, that we still add a certain constant to the addresses during L1→L2 communication in order to allow ourselves some way to support EVM bytecodes in the future. + +#### **Deployment nonce** + +On Ethereum, the same nonce is used for CREATE for accounts and EOA wallets. On ZKsync this is not the case, we use a separate nonce called “deploymentNonce” to track the nonces for accounts. This was done mostly for consistency with custom accounts and for having multicalls feature in the future. + +#### **General process of deployment** + +- After incrementing the deployment nonce, the contract deployer must ensure that the bytecode that is being deployed is available. +- After that, it puts the bytecode hash with a [special constructing marker](#constructing-vs-non-constructing-code-hash) as code for the address of the to-be-deployed contract. +- Then, if there is any value passed with the call, the contract deployer passes it to the deployed account and sets the `msg.value` for the next as equal to this value. +- Then, it uses `mimic_call` for calling the constructor of the contract out of the name of the account. +- It parses the array of immutables returned by the constructor (we’ll talk about immutables in more details later). +- Calls `ImmutableSimulator` to set the immutables that are to be used for the deployed contract. + +Note how it is different from the EVM approach: on EVM when the contract is deployed, it executes the initCode and returns the deployedCode. On ZKsync, contracts only have the deployed code and can set immutables as storage variables returned by the constructor. + +#### **Constructor** + +On Ethereum, the constructor is only part of the initCode that gets executed during the deployment of the contract and returns the deployment code of the contract. On ZKsync, there is no separation between deployed code and constructor code. The constructor is always a part of the deployment code of the contract. In order to protect it from being called, the compiler-generated contracts invoke constructor only if the `isConstructor` flag provided (it is only available for the system contracts). You can read more about flags [here](#flags-for-calls). + +After execution, the constructor must return an array of: + +```solidity +struct ImmutableData { + uint256 index; + bytes32 value; +} +``` + +basically denoting an array of immutables passed to the contract. + +#### **Immutables** + +Immutables are stored in the `ImmutableSimulator` system contract. The way how `index` of each immutable is defined is part of the compiler specification. This contract treats it simply as mapping from index to value for each particular address. + +Whenever a contract needs to access a value of some immutable, they call the `ImmutableSimulator.getImmutable(getCodeAddress(), index)`. Note that on ZKsync it is possible to get the current execution address (you can read more about `getCodeAddress()` [here](#zksync-specific-opcodes). + +#### **Return value of the deployment methods** + +If the call succeeded, the address of the deployed contract is returned. If the deploy fails, the error bubbles up. + +### DefaultAccount + +The implementation of the default account abstraction. This is the code that is used by default for all addresses that are not in kernel space and have no contract deployed on them. This address: + +- Contains minimal implementation of our account abstraction protocol. Note that it supports the [built-in paymaster flows](https://docs.zksync.io/build/developer-reference/account-abstraction/paymasters). +- When anyone (except bootloader) calls it, it behaves in the same way as a call to an EOA, i.e. it always returns `success = 1, returndatasize = 0` for calls from anyone except for the bootloader. + +### L1Messenger + +A contract used for sending arbitrary length L2→L1 messages from ZKsync to L1. While ZKsync natively supports a rather limited number of L1→L2 logs, which can transfer only roughly 64 bytes of data a time, we allowed sending nearly-arbitrary length L2→L1 messages with the following trick: + +The L1 messenger receives a message, hashes it and sends only its hash as well as the original sender via L2→L1 log. Then, it is the duty of the L1 smart contracts to make sure that the operator has provided full preimage of this hash in the commitment of the batch. + +Note, that L1Messenger is calls the L2DAValidator and plays an important role in facilitating the [DA validation protocol](../settlement_contracts/data_availability/custom_da.md). + +### NonceHolder + +Serves as storage for nonces for our accounts. Besides making it easier for operator to order transactions (i.e. by reading the current nonces of account), it also serves a separate purpose: making sure that the pair (address, nonce) is always unique. + +It provides a function `validateNonceUsage` which the bootloader uses to check whether the nonce has been used for a certain account or not. Bootloader enforces that the nonce is marked as non-used before validation step of the transaction and marked as used one afterwards. The contract ensures that once marked as used, the nonce can not be set back to the “unused” state. + +Note that nonces do not necessarily have to be monotonic (this is needed to support more interesting applications of account abstractions, e.g. protocols that can start transactions on their own, tornado-cash like protocols, etc). That’s why there are two ways to set a certain nonce as “used”: + +- By incrementing the `minNonce` for the account (thus making all nonces that are lower than `minNonce` as used). +- By setting some non-zero value under the nonce via `setValueUnderNonce`. This way, this key will be marked as used and will no longer be allowed to be used as nonce for accounts. This way it is also rather efficient, since these 32 bytes could be used to store some valuable information. + +The accounts upon creation can also provide which type of nonce ordering do they want: Sequential (i.e. it should be expected that the nonces grow one by one, just like EOA) or Arbitrary, the nonces may have any values. This ordering is not enforced in any way by system contracts, but it is more of a suggestion to the operator on how it should order the transactions in the mempool. + +### EventWriter + +A system contract responsible for emitting events. + +It accepts in its 0-th extra abi data param the number of topics. In the rest of the extraAbiParams he accepts topics for the event to emit. Note, that in reality the event the first topic of the event contains the address of the account. Generally, the users should not interact with this contract directly, but only through Solidity syntax of `emit`-ing new events. + +### Compressor + +One of the most expensive resource for a rollup is data availability, so in order to reduce costs for the users we compress the published pubdata in several ways: + +- We compress published bytecodes. +- We compress state diffs. + +The contract provides two methods: + +- `publishCompressedBytecode` that verifies the correctness of the bytecode compression and publishes it in form of a message to the DA layer. +- `verifyCompressedStateDiffs` that can verify the correctness of our standard state diff compression. This method can be used by common L2DAValidators and it is for instance utilized by the [RollupL2DAValidator](../../l2-contracts/contracts/data-availability/RollupL2DAValidator.sol). + +You can read more about how custom DA is handled [here](../settlement_contracts/data_availability/custom_da.md). + +### Pubdata Chunk Publisher + +This contract is responsible for separating pubdata into chunks that each fit into a [4844 blob](../settlement_contracts/data_availability/rollup_da.md) and calculating the hash of the preimage of said blob. If a chunk's size is less than the total number of bytes for a blob, we pad it on the right with zeroes as the circuits will require that the chunk is of exact size. + +This contract can be utilized by L2DAValidators, e.g. [RollupL2DAValidator](../../l2-contracts/contracts/data-availability/RollupL2DAValidator.sol) uses it to compress the pubdata into blobs. + +### CodeOracle + +It is a contract that accepts the versioned hash of a bytecode and returns the preimage of it. It is similar to the `extcodecopy` functionality on Ethereum. + +It works the following way: + +1. It accepts a versioned hash and double checks that it is marked as “known”, i.e. the operator must know the preimage for such hash. +2. After that, it uses the `decommit` opcode, which accepts the versioned hash and the number of ergs to spent, which is proportional to the length of the preimage. If the preimage has been decommitted before, the requested cost will be refunded to the user. + + Note, that the decommitment process does not only happen using the `decommit` opcode, but during calls to contracts. Whenever a contract is called, its code is decommitted into a memory page dedicated to contract code. We never decommit the same preimage twice, regardless of whether it was decommitted via an explicit opcode or during a call to another contract, the previous unpacked bytecode memory page will be reused. When executing `decommit` inside the `CodeOracle` contract, the user will be firstly precharged with maximal possible price and then it will be refunded in case the bytecode has been decommitted before. + +3. The `decommit` opcode returns to the slice of the decommitted bytecode. Note, that the returned pointer always has length of 2^21 bytes, regardless of the length of the actual bytecode. So it is the job of the `CodeOracle` system contract to shrink the length of the returned data. + +### P256Verify + +This contract exerts the same behavior as the P256Verify precompile from [RIP-7212](https://github.com/ethereum/RIPs/blob/master/RIPS/rip-7212.md). Note, that since Era has different gas schedule, we do not comply with the gas costs, but otherwise the interface is identical. + +### GasBoundCaller + +This is not a system contract, but it will be predeployed on a fixed user space address. This contract allows users to set an upper bound of how much pubdata can a subcall take, regardless of the gas per pubdata. More on how pubdata works on ZKsync can be read [here](./zksync_fee_model.md). + +Note, that it is a deliberate decision not to deploy this contract in the kernel space, since it can relay calls to any contracts and so may break the assumption that all system contracts can be trusted. + +### ComplexUpgrader + +Usually an upgrade is performed by calling the `forceDeployOnAddresses` function of ContractDeployer out of the name of the `FORCE_DEPLOYER` constant address. However some upgrades may require more complex interactions, e.g. query something from a contract to determine which calls to make etc. + +For cases like this `ComplexUpgrader` contract has been created. The assumption is that the implementation of the upgrade is predeployed and the `ComplexUpgrader` would delegatecall to it. + +> Note, that while `ComplexUpgrader` existed even in the previous upgrade, it lacked `forceDeployAndUpgrade` function. This caused some serious limitations. More on how the gateway upgrade process will look like can be read [here](../upgrade_history/gateway_upgrade/upgrade_process.md). + +### Predeployed contracts + +There are some contracts need to predeployed, but having kernel space rights is not desirable for them. Such contracts are usuallypredeployed at sequential addresses starting from `2^16`. + +### Create2Factory + +Just a built-in Create2Factory. It allows to deterministically deploy contracts to the samme address on multiple chains. + +### L2GenesisUpgrade + +A contract that is responsible for facilitating initialization of a newly created chain. This is part of a [chain creation flow](../chain_management/chain_genesis.md). + +### Bridging-related contracts + +`L2Bridgehub`, `L2AssetRouter`, `L2NativeTokenVault`, as well as `L2MessageRoot`. + +These contracts are used to facilitate cross-chain communication as well value bridging. You can read more about then in [the asset router spec](../bridging/asset_router/overview.md). + +Note, that [L2AssetRouter](../../l1-contracts/contracts/bridge/asset-router/L2AssetRouter.sol) and [L2NativeTokenVault](../../l1-contracts/contracts/bridge/ntv/L2NativeTokenVault.sol) have unique code, the L2Bridgehub and L2MessageRoot share the same source code with their L1 precompiles, i.e. the L2Bridgehub has [this](../../l1-contracts/contracts/bridgehub/Bridgehub.sol) code and L2MessageRoot has [this](../../l1-contracts/contracts/bridgehub/MessageRoot.sol) code. + +### SloadContract + +During the L2GatewayUpgrade, the system contracts will need to read the storage of some other contracts, despite those lacking getters. The how it is implemented can be read in the `forcedSload` function of the [SystemContractHelper](../../system-contracts/contracts/libraries/SystemContractHelper.sol) contract. + +While it is only used for the upgrade, it was decided to leave it as a predeployed contract for future use-cases as well. + +### L2WrappedBaseTokenImplementation + +While bridging wrapped base tokens (e.g. WETH) is not yet supported. The address of it is enshrined within the native token vault (both the L1 and L2 one). For consistency with other networks, our WETH token is deployed as a TransparentUpgradeableProxy. To have the deployment process easier, we predeploy the implementation. + +## Known issues to be resolved + +The protocol, while conceptually complete, contains some known issues which will be resolved in the short to middle term. + +- Fee modeling is yet to be improved. More on it in the [document](./zksync_fee_model.md) on the fee model. +- We may add some kind of default implementation for the contracts in the kernel space (i.e. if called, they wouldn’t revert but behave like an EOA). diff --git a/docs/l2_system_contracts/zksync_fee_model.md b/docs/l2_system_contracts/zksync_fee_model.md new file mode 100644 index 000000000..5f3c44fe2 --- /dev/null +++ b/docs/l2_system_contracts/zksync_fee_model.md @@ -0,0 +1,309 @@ +# ZKsync fee model + +[back to readme](../README.md) + +This document will assume that you already know how gas & fees work on Ethereum. + +On Ethereum, all the computational, as well as storage costs, are represented via one unit: gas. Each operation costs a certain amount of gas, which is generally constant (though it may change during [upgrades](https://blog.ethereum.org/2021/03/08/ethereum-berlin-upgrade-announcement)). + +## Main differences from EVM + +ZKsync as well as other L2s have the issue that does not allow the adoption of the same model as the one for Ethereum so easily: the main reason is the requirement for publishing the pubdata on Ethereum. This means that prices for L2 transactions will depend on the volatile L1 gas prices and can not be simply hard coded. + +Also, ZKsync, being a zkRollup is required to prove every operation with zero-knowledge proofs. That comes with a few nuances. + +### Different opcode pricing + +The operations tend to have different “complexity”/”pricing” in zero-knowledge proof terms than in standard CPU terms. For instance, `keccak256` which was optimized for CPU performance, will cost more to prove. + +That’s why you will find the prices for operations on ZKsync a lot different from the ones on Ethereum. + +### I/O pricing + +On Ethereum, whenever a storage slot is read/written to for the first time, a certain amount of gas is charged for the fact that the slot has been accessed for the first time. A similar mechanism is used for accounts: whenever an account is accessed for the first time, a certain amount of gas is charged for reading the account's data. On EVM, an account's data includes its nonce, balance, and code. We use a similar mechanism but with a few differences. + +#### Storage costs + +Just like EVM, we also support "warm" and "cold" storage slots. However, the flow is a bit different: + +1. The user is firstly precharged with the maximum (cold) cost. +2. The operator is asked for a refund. +3. Then, the refund is given out to the user in place. + +In other words, unlike EVM, the user should always have enough gas for the worst case (even if the storage slot is "warm"). Also, the control of the refunds is currently enforced by the operator only and not by the circuits. + +#### Code decommitment and account access costs + +Unlike EVM, our storage does not couple accounts' balances, nonces, and bytecodes. Balance, nonce, and code hash are three separate storage variables that use standard storage "warm" and "cold" mechanisms. A different approach is used for accessing bytecodes though. + +We call the process of unpacking the bytecode as, _code decommitment_, since it is a process of transforming a commitment to code (i.e., the versioned code hash) into its preimage. Whenever a contract with a certain code hash is called, the following logic is executed: + +1. The operator is asked whether this is the first time this bytecode has been decommitted. +2. If the operator returns "yes", then the user is charged the full cost. Otherwise, the user does not pay for decommit. +3. If needed, the code is decommitted to the code page. + +Unlike storage interactions, the correctness of this process is _partially_ enforced by circuits, i.e., if step (3) is reached, i.e., the code is being decommitted, it will be proven that the operator responded correctly on step (1). However, if the program runs out of gas on step (2), the correctness of the first statement won't be proven. The reason for that is it is hard to prove in circuits at the time the decommitment is invoked whether it is indeed the first decommitment or not. + +Note that in the case of an honest operator, this approach offers a better UX, since there is no need to be precharged with the full cost beforehand. However, no program should rely on this fact. + +#### Conclusion + +As a conclusion, ZKsync Era supports a similar "cold"/"warm" mechanism to EVM, but for now, these are only enforced by the operator, i.e., the users of the applications should not rely on these. The execution is guaranteed to be correct as long as the user has enough gas to pay for the worst, i.e. "cold" scenario. + +### Memory pricing + +ZKsync Era has different memory pricing rules: + +- Whenever a user contract is called, `2^12` bytes of memory are given out for free, before starting to charge users linearly according to its length. +- Whenever a kernel space (i.e., a system) contract is called, `2^21` bytes of memory are given out for free, before starting to charge users linearly according to the length. + Note that, unlike EVM, we never use a quadratic component of the price for memory expansion. + +### Different intrinsic costs + +Unlike Ethereum, where the intrinsic cost of transactions (`21000` gas) is used to cover the price of updating the balances of the users, the nonce and signature verification, on ZKsync these prices are _not_ included in the intrinsic costs for transactions, due to the native support of account abstraction, meaning that each account type may have their own transaction cost. In theory, some may even use more zk-friendly signature schemes or other kinds of optimizations to allow cheaper transactions for their users. + +That being said, ZKsync transactions do come with some small intrinsic costs, but they are mostly used to cover costs related to the processing of the transaction by the bootloader which can not be easily measured in code in real-time. These are measured via testing and are hard coded. + +### Charging for pubdata + +An important cost factor for users is the pubdata. ZKsync Era is a state diff-based rollup, meaning that the pubdata is published not for the transaction data, but for the state changes: modified storage slots, deployed bytecodes, L2->L1 messages. This allows for applications that modify the same storage slot multiple times such as oracles, to update the storage slots multiple times while maintaining a constant footprint on L1 pubdata. Correctly a state diff rollups requires a special solution to charging for pubdata. It is explored in the next section. + +## How L2 gas price works + +### Batch overhead & limited resources of the batch + +To process the batch, the ZKsync team has to pay for proving the batch, committing to it, etc. Processing a batch involves some operational costs as well. All of these values we call “Batch overhead”. It consists of two parts: + +- The L2 requirements for proving the circuits (denoted in L2 gas). +- The L1 requirements for the proof verification as well as general batch processing (denoted in L1 gas). + +We generally try to aggregate as many transactions as possible and each transaction pays for the batch overhead proportionally to how close the transaction brings the batch to being _sealed,_ i.e. closed and prepared for proof verification and submission on L1. A transaction gets closer to sealing a batch by using the batch’s _limited resources_. + +While on Ethereum, the main reason for the existence of a batch gas limit is to keep the system decentralized & load low, i.e. assuming the existence of the correct hardware, only time would be a requirement for a batch to adhere to. In the case of ZKsync batches, there are some limited resources the batch should manage: + +- **Time.** The same as on Ethereum, the batch should generally not take too much time to be closed to provide better UX. To represent the time needed we use a batch gas limit, note that it is higher than the gas limit for a single transaction. +- **Slots for transactions.** The bootloader has a limited number of slots for transactions, i.e. it can not take more than a certain transactions per batch. +- **The memory of the bootloader.** The bootloader needs to store the transaction’s ABI encoding in its memory & this fills it up. In practical terms, it serves as a penalty for having transactions with large calldata/signatures in the case of custom accounts. +- **Pubdata bytes.** To fully appreciate the gains from the storage diffs, i.e. the fact that changes in a single slot happening in the same batch need to be published only once, we need to publish all the batch’s public data only after the transaction has been processed. Right now, we publish all the data with the storage diffs as well as L2→L1 messages, etc in a single transaction at the end of the batch. Most nodes have a limit of 128kb per transaction, so this is the limit that each ZKsync batch should adhere to. + +Each transaction spends the batch overhead proportionally to how closely it consumes the resources above. + +Note, that before the transaction is executed, the system can not know how many of the limited system resources the transaction will take, so we need to charge for the worst case and provide the refund at the end of the transaction. + +### `MAX_TRANSACTION_GAS_LIMIT` + +A recommended maximal amount of gas that a transaction can spend on computation is `MAX_TRANSACTION_GAS_LIMIT`. But in case the operator trusts the user, the operator may provide the [trusted gas limit](../../system-contracts/bootloader/bootloader.yul#L1242), i.e. the limit which exceeds `MAX_TRANSACTION_GAS_LIMIT` assuming that the operator knows what he is doing. This can be helpful in the case of a hyperchain with different parameters. + +### Derivation of `baseFee` and `gasPerPubdata` + +At the start of each batch, the operator provides the following two parameters: + +1. `FAIR_L2_GAS_PRICE`. This variable should denote what is the minimal L2 gas price that the operator is willing to accept. It is expected to cover the cost of proving/executing a single unit of zkEVM gas, the potential contribution of usage of a single gas towards sealing the batch, as well as congestion. +2. `FAIR_PUBDATA_PRICE`, which is the price of a single pubdata byte in Wei. Similar to the variable about, it is expected to cover the cost of publishing a single byte as well as the potential contribution of usage of a single pubdata byte towards sealing the batch. + +In the descriptions above by "contribution towards sealing the batch" we referred to the fact that if a batch is most often closed by a certain resource (e.g. pubdata), then the pubdata price should include this cost. + +The `baseFee` and `gasPerPubdata` are then calculated as: + +```yul +baseFee := max( + fairL2GasPrice, + ceilDiv(fairPubdataPrice, MAX_L2_GAS_PER_PUBDATA()) +) +gasPerPubdata := ceilDiv(pubdataPrice, baseFee) +``` + +While the way how we [charge for pubdata](#how-we-charge-for-pubdata) in theory allows for any `gasPerPubdata`, some SDKs expect the `gasLimit` by a transaction to be a uint64 number. We would prefer `gasLimit` for transactions to stay within JS's safe "number" range in case someone uses `number` type to denote gas there. For this reason, we will bind the `MAX_L2_GAS_PER_PUBDATA` to `2^20` gas per 1 pubdata byte. The number is chosen such that `MAX_L2_GAS_PER_PUBDATA * 2^32` is a safe JS integer. The `2^32` part is the maximal possible value for pubdata counter that could be in theory used. It is unrealistic that this value will ever appear under an honest operator, but it is needed just in case. + +Note, however, that it means that the total under high L1 gas prices `gasLimit` may be larger than `u32::MAX` and it is recommended that no more than `2^20` bytes of pubdata can be published within a transaction. + +#### Recommended calculation of `FAIR_L2_GAS_PRICE`/`FAIR_PUBDATA_PRICE` + +Let's define the following constants: + +- `BATCH_OVERHEAD_L1_GAS` - The L1 gas overhead for a batch (proof verification, etc). +- `COMPUTE_OVERHEAD_PART` - The constant that represents the possibility that a batch can be sealed because of overuse of computation resources. It has range from 0 to 1. If it is 0, the compute will not depend on the cost of closing the batch. If it is 1, the gas limit per batch will have to cover the entire cost of closing the batch. +- `MAX_GAS_PER_BATCH` - The maximum amount of gas that can be used by the batch. This value is derived from the circuits' limitation per batch. +- `PUBDATA_OVERHEAD_PART` - The constant that represents the possibility that a batch can be sealed because of overuse of pubdata. It has range from 0 to 1. If it is 0, the pubdata will not depend on the cost of closing the batch. If it is 1, the pubdata limit per batch will have to cover the entire cost of closing the batch. +- `MAX_PUBDATA_PER_BATCH` - The maximum amount of pubdata that can be used by the batch. Note that if the calldata is used as pubdata, this variable should not exceed 128kb. + +And the following fluctuating variables: + +- `MINIMAL_L2_GAS_PRICE` - The minimal acceptable L2 gas price, i.e. the price that should include the cost of computation/proving as well as potential premium for congestion. +- `PUBDATA_BYTE_ETH_PRICE` - The minimal acceptable price in ETH per each byte of pubdata. It should generally be equal to the expected price of a single blob byte or calldata byte (depending on the approach used). + +Then: + +1. `FAIR_L2_GAS_PRICE = MINIMAL_L2_GAS_PRICE + COMPUTE_OVERHEAD_PART * BATCH_OVERHEAD_L1_GAS / MAX_GAS_PER_BATCH` +2. `FAIR_PUBDATA_PRICE = PUBDATA_BYTE_ETH_PRICE + PUBDATA_OVERHEAD_PART * BATCH_OVERHEAD_L1_GAS / MAX_PUBDATA_PER_BATCH` + +For L1→L2 transactions, the `MAX_GAS_PER_BATCH` variable is equal to `L2_TX_MAX_GAS_LIMIT` (since this amount of gas is enough to publish the maximal number of pubdata in the batch). Also, for additional security, for L1->L2 transactions the `COMPUTE_OVERHEAD_PART = PUBDATA_OVERHEAD_PART = 1`, i.e. since we are not sure what exactly will be the reason for us closing the batch. For L2 transactions, typically `COMPUTE_OVERHEAD_PART = 0`, since, unlike L1→L2 transactions, in case of an attack, the operator can simply censor bad transactions or increase the `FAIR_L2_GAS_PRICE` and so the operator can use average values for better UX. + +#### Note on operator’s responsibility + +To reiterate, the formulas above are used for L1→L2 transactions on L1 to protect the operator from malicious transactions. However, for L2 transactions, it is solely the responsibility of the operator to provide the correct values. It is designed this way for more fine-grained control over the system for the zkStack operators (including Validiums, maybe Era on top of another L1, etc). + +This fee model also provides a very high degree of flexibility to the operator & so if we find out that we earn too much with a certain part, we could amend how the fair l2 gas price and fair pubdata price are generated and that’s it (there will be no further enforcements on the bootloader side). + +In the long run, the consensus will ensure the correctness of these values on the main ZKsync Era (or maybe we’ll transition to a different system). + +#### Overhead for transaction slot and memory + +We also have a limit on the number of memory that can be consumed within a batch as well as the number of transactions that can be included there. + +To simplify the codebase we've chosen the following constants: + +- `TX_OVERHEAD_GAS = 10000` -- the overhead in gas for including a transaction into a batch. +- `TX_MEMORY_OVERHEAD_GAS = 10` -- the overhead for consuming a single byte of bootloader memory. + +We've used roughly the following formulae to derive these values: + +1. `TX_OVERHEAD_GAS = MAX_GAS_PER_BATCH / MAX_TXS_IN_BATCH`. For L1->L2 transactions we used the `MAX_GAS_PER_BATCH = 80kk` and `MAX_TXS_IN_BATCH = 10k`. `MAX_GAS_PER_BATCH / MAX_TXS_IN_BATCH = 8k`, while we decided to use the 10k value to better take into account the load on the operator from storing the information about the transaction. +2. `TX_MEMORY_OVERHEAD_GAS = MAX_GAS_PER_BATCH / MAX_MEMORY_FOR_BATCH`. For L1->L2 transactions we used the `MAX_GAS_PER_BATCH = 80kk` and `MAX_MEMORY_FOR_BATCH = 32 * 600_000`. + +`MAX_GAS_PER_BATCH / MAX_MEMORY_FOR_BATCH = 4`, while we decided to use the `10` gas value to better take into account the load on the operator from storing the information about the transaction. + +Future work will focus on removing the limit on the number of transactions’ slots completely as well as increasing the memory limit. + +#### Note on L1→L2 transactions + +The formulas above apply to L1→L2 transactions. However, note that the `gas_per_pubdata` is still kept as constant as `800`. This means that a higher `baseFee` could be used for L1->L2 transactions to ensure that `gas_per_pubdata` remains at that value regardless of the price of the pubdata. + +#### Refunds + +Note, that the used constants for the fee model are probabilistic, i.e. we never know in advance the exact reason why a batch is going to be sealed. These constants are meant to cover the expenses of the operator over a longer period so we do not refund the fact that the transaction might've been charged for overhead above the level at which the transaction has brought the batch to being closed, since these funds are used to cover transactions that did not pay in full for the limited batch's resources that they used. + +#### Refunds for repeated writes + +ZKsync Era is a state diff-based rollup, i.e. the pubdata is published not for transactions, but for storage changes. This means that whenever a user writes into a storage slot, it incurs a certain amount of pubdata. However, not all writes are equal: + +- If a slot has been already written to in one of the previous batches, the slot has received a short ID, which allows it to require less pubdata in the state diff. +- Depending on the `value` written into a slot, various compression optimizations could be used and so we should reflect that too. +- Maybe the slot has been already written to in this batch so we don’t have to charge anything for it. + +You can read more about how we treat the pubdata [here](../settlement_contracts/data_availability/standard_pubdata_format.md). + +The important part here is that while such refunds are inlined (i.e. unlike the refunds for overhead they happen in place during execution and not after the whole transaction has been processed), they are enforced by the operator. Right now, the operator is the one who decides what refund to provide. + +## How we charge for pubdata + +ZKsync Era is a state diff-based rollup. It means that it is not possible to know how much pubdata a transaction will take before its execution. We _could_ charge for pubdata the following way: whenever a user does an operation that emits pubdata (writes to storage, publishes an L2->L1 message, etc.), we charge `pubdata_bytes_published * gas_per_pubdata` directly from the context of the execution. + +However, such an approach has the following disadvantages: + +- This would inherently make execution very divergent from EVM. +- It is prone to unneeded overhead. For instance, in the case of reentrancy locks, the user will still have to pay the initial price for marking the lock as used. The price will get refunded in the end, but it still worsens the UX. +- If we want to impose any sort of limit on how much computation a transaction could take (let's call this limit `MAX_TX_GAS_LIMIT`), it would mean that no more than `MAX_TX_GAS_LIMIT / gas_per_pubdata` could be published in a transaction, making this limit either too small or forcing us to increase `baseFee` to prevent the number from growing too much. + +To avoid the issues above we need to somehow decouple the gas spent on pubdata from the gas spent on execution. While calldata-based rollups precharge for calldata, we cannot do it, since the exact state diffs are known only after the transaction is finished. We'll use the approach of _post-charging._ Basically, we'll keep a counter that tracks how much pubdata has been spent and charge the user for the calldata at the end of the transaction. + +A problem with post-charging is that the user may spend all their gas within the transaction so we'll have no gas to charge for pubdata from. Note, however, that if the transaction is reverted, all the state changes that were related to it will be reverted too. That's why whenever we need to charge the user for pubdata, but it doesn't provide enough gas, the transaction will get reverted. The user will pay for the computation, but no state changes (and thus, pubdata) will be produced by the transaction. + +So it will work the following way: + +1. Firstly, we fix the amount of pubdata published so far. Let's denote it as `basePubdataSpent`. +2. We execute the validation of the transaction. +3. We check whether `(getPubdataSpent() - basePubdataSpent) * gasPerPubdata <= gasLeftAfterValidation`. If it is not, then the transaction does not cover enough funds for itself, so it should be _rejected_ (unlike revert, which means that the transaction is not even included in the block). +4. We execute the transaction itself. +5. We do the same check as in (3), but now if the transaction does not have enough gas for pubdata, it is reverted, i.e., the user still pays the fee to cover the computation for its transaction. +6. (optional, in case a paymaster is used). We repeat steps (4-5), but now for the `postTransaction` method of the paymaster. + +On the internal level, the pubdata counter is modified in the following way: + +- When there is a storage write, the operator is asked to provide by how much to increment the pubdata counter. Note that this value can be negative if, as in the example with a reentrancy guard, the storage diff is being reversed. There is currently no limit on how much the operator can charge for the pubdata. +- Whenever there is a need to publish a blob of bytes to L1 (for instance, when publishing a bytecode), the responsible system contract would increment the pubdata counter by `bytes_to_publish`. +- Whenever there is a revert in a frame, the pubdata counter gets reverted too, similar to storage & events. + +The approach with post-charging removes the unneeded overhead and decouples the gas used for the execution from the gas used for data availability, which removes any caps on `gasPerPubdata`. + +### Security considerations for protocol + +Now it has become easier for a transaction to use up more pubdata than what can be published within a batch. In such a case, we'll revert the transaction as well. + +### Security considerations for users + +The approach with post-charging introduces one distinctive feature: it is not trivial to know the final price for a transaction at the time of its execution. When a user does `.call{gas: some_gas}` the final impact on the price of the transaction may be higher than `some_gas` since the pubdata counter will be incremented during the execution and charged only at the end of the transaction. + +While for the average user, this limitation is not relevant, some specific applications may receive certain issues. + +#### Example for a queue of withdrawals + +Imagine that there is the following contract: + +```solidity +struct Withdrawal { + address token; + address to; + uint256 amount; +} + +Withdrawals[] queue; +uint256 lastProcessed; + +function processNWithdrawals(uint256 N) external nonReentrant { + uint256 current = lastProcessed + 1; + uint256 lastToProcess = current + N - 1; + + while(current <= lastToProcess) { + // If the user provided some bad token that takes more than MAX_WITHDRAWAL_GAS + // to transfer, it is the problem of the user and it will stall the queue, so + // the `_success` value is ignored. + Withdrawal storage currentQueue = queue[current]; + (bool _success, ) = currentQueue.token.call{gas: MAX_WITHDRAWAL_GAS}(abi.encodeWithSignature("transfer(to,amount)", currentQueue.to, currentQueue.amount)); + current += 1; + } + lastProcessed = lastToProcess; +} +``` + +The contract above supports a queue of withdrawals. This queue supports any type of token, including potentially malicious ones. However, the queue will never get stuck, since the `MAX_WITHDRAWAL_GAS` ensures that even if the malicious token does a lot of computation, it will be bound by this number and so the caller of the `processNWithdrawals` won't spend more than `MAX_WITHDRAWAL_GAS` per token. + +The above assumptions work in the pre-charge model (calldata based rollups) or pay-as-you-go model (pre-1.5.0 Era). However, in the post-charge model, the `MAX_WITHDRAWAL_GAS`` limits the amount of computation that can be done within the transaction, but it does not limit the amount of pubdata that can be published. Thus, if such a function publishes a very large L1→L2 message, it might make the entire top transaction fail. This effectively means that such a queue would be stalled. + +#### How to prevent this issue on the users' side + +If a user really needs to limit the amount of gas that the subcall takes, all the subcalls should be routed through a special contract, that will guarantee that the total cost of the subcall wont be larger than the gas provided (by reverting if needed). + +An implementation of this special contract can be seen [here](../../gas-bound-caller/contracts/GasBoundCaller.sol). Note, that this contract is _not_ a system one and it will be deployed on some fixed, but not kernel space address. + +#### 1. Case of when a malicious contract consumes a large, but processable amount of pubdata\*\* + +In this case, the topmost transaction will be able to sponsor such subcalls. When a transaction is processed, at most 80M gas is allowed to be passed to the execution. The rest can only be spent on pubdata during the post-charging. + +#### 2. Case of when a malicious contract consumes an unprocessable amount of pubdata\*\* + +In this case, the malicious callee published so much pubdata, that such a transaction can not be included into a batch. This effectively means that no matter how much money the topmost transaction willing to pay, the queue is stalled. + +The only way how it is combated is by setting some minimal amount of ergs that still have to be consumed with each emission of pubdata (basically to make sure that it is not possible to publish large chunks of pubdata while using negligible computation). Unfortunately, setting this minimal amount to cover the worst possible case (i.e. 80M ergs spent with maximally 100k of pubdata available, leading to 800 L2 gas / pubdata byte) would likely be too harsh and will negatively impact average UX. Overall, this _is_ the way to go, however for now the only guarantee will be that a subcall of 1M gas is always processable, which will mean that at least 80 gas will have to be spent for each published pubdata byte. Even if higher than real L1 gas costs, it is reasonable even in the long run, since all the things that are published as pubdata are state-related and so they have to be well-priced for long-term storage. + +In the future, we will guarantee the processability of subcalls of larger size by increasing the number of pubdata that can be published per batch. + +### Limiting the `gas_per_pubdata` + +As already mentioned, the transactions on ZKsync depend on volatile L1 gas costs to publish the pubdata for batch, verify proofs, etc. For this reason, ZKsync-specific EIP712 transactions contain the `gas_per_pubdata_limit` field, denoting the maximum `gas_per_pubdata` that the operator can charge the user for a single byte of pubdata. + +For Ethereum transactions (which do not contain this field), the block's `gas_per_pubdata` is used. + +## Improvements in the upcoming releases + +The fee model explained above, while fully functional, has some known issues. These will be tackled with the following upgrades. + +### L1->L2 transactions do not pay for their execution on L1 + +The `executeBatches` operation on L1 is executed in `O(N)` where N is the number of priority ops that we have in the batch. Each executed priority operation will be popped and so it incurs cost for storage modifications. As of now, we do not charge for it. + +## ZKsync Era Fee Components (Revenue & Costs) + +- On-Chain L1 Costs + - L1 Commit Batches + - The commit batch transaction submits pubdata (which is the list of updated storage slots) to L1. The cost of a commit transaction is calculated as `constant overhead + price of pubdata`. The `constant overhead` cost is evenly distributed among L2 transactions in the L1 commit transaction, but only at higher transaction loads. As for the `price of pubdata`, it is known how much pubdata each L2 transaction consumed, therefore, they are charged directly for that. Multiple L1 batches can be included in a single commit transaction. + - L1 Prove Batches + - Once the off-chain proof is generated, it is submitted to L1 to make the rollup batch final. Currently, each proof contains only one L1 batch. + - L1 Execute Batches + - The execute batches transaction processes L2 -> L1 messages and marks executed priority operations as such. Multiple L1 batches can be included in a single execute transaction. + - L1 Finalize Withdrawals + - While not strictly part of the L1 fees, the cost to finalize L2 → L1 withdrawals are covered by Matter Labs. The finalize withdrawals transaction processes user token withdrawals from ZKsync Era to Ethereum. Multiple L2 withdrawal transactions are included in each finalize withdrawal transaction. +- On-Chain L2 Revenue + - L2 Transaction Fee + - This fee is what the user pays to complete a transaction on ZKsync Era. It is calculated as `gasLimit x baseFeePerGas - refundedGas x baseFeePerGas`, or more simply, `gasUsed x baseFeePerGas`. +- Profit = L2 Revenue - L1 Costs - Off-Chain Infrastructure Costs diff --git a/docs/overview.md b/docs/overview.md new file mode 100644 index 000000000..e69de29bb diff --git a/docs/gateway/custom-da.md b/docs/settlement_contracts/data_availability/custom_da.md similarity index 96% rename from docs/gateway/custom-da.md rename to docs/settlement_contracts/data_availability/custom_da.md index acb719835..b1780eb4a 100644 --- a/docs/gateway/custom-da.md +++ b/docs/settlement_contracts/data_availability/custom_da.md @@ -1,11 +1,13 @@ # Custom DA support +[back to readme](../../README.md) + ## Intro We introduced modularity into our contracts to support multiple DA layers, easier support for Validium and Rollup mode, and to settlement via the Gateway. -![The contracts for the rollup case](./Custom-da-contracts.png) -![The general architecture](./Custom-da-external.png) +![The contracts for the rollup case](./img/custom_da.png) +![The general architecture](./img/Custom-da-external.png) ### Background diff --git a/docs/gateway/Custom-da-external.png b/docs/settlement_contracts/data_availability/img/Custom-da-external.png similarity index 100% rename from docs/gateway/Custom-da-external.png rename to docs/settlement_contracts/data_availability/img/Custom-da-external.png diff --git a/docs/settlement_contracts/data_availability/img/Rollup_DA.png b/docs/settlement_contracts/data_availability/img/Rollup_DA.png new file mode 100644 index 000000000..6f6ad084a Binary files /dev/null and b/docs/settlement_contracts/data_availability/img/Rollup_DA.png differ diff --git a/docs/settlement_contracts/data_availability/img/custom_da.png b/docs/settlement_contracts/data_availability/img/custom_da.png new file mode 100644 index 000000000..0a17eb662 Binary files /dev/null and b/docs/settlement_contracts/data_availability/img/custom_da.png differ diff --git a/docs/settlement_contracts/data_availability/rollup_da.md b/docs/settlement_contracts/data_availability/rollup_da.md new file mode 100644 index 000000000..901e47148 --- /dev/null +++ b/docs/settlement_contracts/data_availability/rollup_da.md @@ -0,0 +1,80 @@ +# Rollup DA + +[back to readme](../../README.md) + +FIXME: run a spellchecker + +## Prerequisites + +Before reading this document, it is better to understand how [custom DA](./custom_da.md) in general works. + +## EIP4844 support + +EIP-4844, commonly known as Proto-Danksharding, is an upgrade to the ethereum protocol that introduces a new data availability solution embedded in layer 1. More information about it can be found [here](https://ethereum.org/en/roadmap/danksharding/). + +To facilitate EIP4844 blob support, our circuits allow providing two arrays in our public input to the circuit: + +- `blobCommitments` -- this is the commitment that helps to check the correctness of the blob content. The formula on how it is computed will be explained below in the document. +- `blobHash` -- the `keccak256` hash of the inner contents of the blob. + +Note, that our circuits require that each blob contains exactly `4096 * 31` bytes. The maximal number of blobs that are supported by our proving system is 16, but the system contracts support only 6 blobs at most for now. + +When committing a batch, the L1DAValidator is called with the data provided by the operator and it should return the two arrays described above. These arrays be put inside the batch commitment and then the correctness of the commitments will be verified at the proving stage. + +Note, that the `Executor.sol` (and the contract itself) is not responsible for checking that the provided `blobHash` and `blobCommitments` in any way correspond to the pubdata inside the batch as it is the job of the DA Validator pair. + +## Publishing pubdata to L1 + +Let's see an example of how the approach above works in rollup DA validators. + +### RollupL2DAValidator + +![RollupL2DAValidator.png](./img/Rollup_DA.png) + +`RollupL2DAValidator` accepts the preimages for the data to publishes as well as their compressed format. After verifying the compression, it forms the `_totalPubdata` bytes array, which represents the entire blob of data that should be published to L1. + +It calls the `PubdataChunkPublisher` system contract to split this pubdata into multiple "chunks" of size `4096 * 31` bytes and return the `keccak256` hash of those, These will be the `blobHash` of from the section before. + +To give the flexibility of checking different DA, we send the following data to L1: + +- State diff hash. As it will be used on L1 to confirm the correctness of the provided uncompressed storage diifs. +- The hash of the `_totalPubdata`. In case the size of pubdata is small, it will allow the operator also use just standard Ethereum calldata for the DA. +- Send the `blobHash` array. + +### RollupL1DAValidator + +When committing the batch, the operator will provide the preimage of the fields that the RollupL2DAValidator has sent before, and also some `l1DaInput` along with it. This `l1DaInput` will be used to prove that the pubdata was indeed provided in this batch. + +The first byte of the `l1DaInput` denotes which way of pubdata publishing was used: Calldata or Blobs. + +In case it is Calldata it will be just checked that the provided calldata matches the hash of the `_totalPubdata` that was sent by the L2 counterpart. Note, that Calldata may still contain the blob information as we typically start generating proves before we know which way of calldata will be used. Note, that in case the Calldata is used for DA, we do not verify the `blobCommitments` as the presence of the correct pubdata has been verified already. + +In case it is blobs, we need to construct the `blobCommitment`s correctly for each of the blob of data. + +For each of the `blob`s the operator provides so called `_commitment` that consists of the following packed structure: `opening point (16 bytes) || claimed value (32 bytes) || commitment (48 bytes) || proof (48 bytes)`. + +The verification of the `_commitment` can be summarized in the following snippet: + +```solidity +// The opening point is passed as 16 bytes as that is what our circuits expect and use when verifying the new batch commitment +// PUBDATA_COMMITMENT_SIZE = 144 bytes +pubdata_commitments <- [opening point (16 bytes) || claimed value (32 bytes) || commitment (48 bytes) || proof (48 bytes)] from calldata +opening_point = bytes32(pubdata_commitments[:16]) +versioned_hash <- from BLOBHASH opcode + +// Given that we needed to pad the opening point for the precompile, append the data after. +point_eval_input = versioned_hash || opening_point || pubdataCommitments[16: PUBDATA_COMMITMENT_SIZE] + +// this part handles the following: +// verify versioned_hash == hash(commitment) +// verify P(z) = y +res <- point_valuation_precompile(point_eval_input) + +assert uint256(res[32:]) == BLS_MODULUS +``` + +The final `blobCommitment` is calculated as the hash between the `blobVersionedHash`, `opening point` and the `claimed value`. The zero knowledge circuits will verify that the opening point and the claimed value were calculated correctly and correspond to the data that was hashed under the `blobHash`. + +## Structure of the pubdata + +Rollups maintain the same structure of pubdata and apply the same rules for compresison as those that were used in the previous versions of the system. These can be read [here](./state_diff_compression_v1_spec.md). diff --git a/docs/settlement_contracts/data_availability/standard_pubdata_format.md b/docs/settlement_contracts/data_availability/standard_pubdata_format.md new file mode 100644 index 000000000..4db784b2a --- /dev/null +++ b/docs/settlement_contracts/data_availability/standard_pubdata_format.md @@ -0,0 +1,286 @@ +# Standard pubdata format + +[back to readme](../../README.md) + +While with the introduction of [custom DA validators](./custom_da.md), any pubdata logic could be applied for each chain (including calldata-based pubdata), ZK chains are generally optimized for using state-diffs based rollup model. + +This document will describe how the standard pubdata format looks like. This is the format that is enforced for [permanent rollup chains](../../chain_management/admin_role.md#ispermanentrollup-setting). + +Pubdata in ZKsync can be divided up into 4 different categories: + +1. L2 to L1 Logs +2. L2 to L1 Messages +3. Smart Contract Bytecodes +4. Storage writes + +Using data corresponding to these 4 facets, across all executed batches, we’re able to reconstruct the full state of L2. To restore the state we just need to filter all of the transactions to the L1 ZKsync contract for only the `commitBatches` transactions where the proposed block has been referenced by a corresponding `executeBatches` call (the reason for this is that a committed or even proven block can be reverted but an executed one cannot). Once we have all the committed batches that have been executed, we then will pull the transaction input and the relevant fields, applying them in order to reconstruct the current state of L2. + +## L2→L1 communication + +We will implement the calculation of the Merkle root of the L2→L1 messages via a system contract as part of the `L1Messenger`. Basically, whenever a new log emitted by users that needs to be Merklized is created, the `L1Messenger` contract will append it to its rolling hash and then at the end of the batch, during the formation of the blob it will receive the original preimages from the operator, verify their consistency, and send those to the L2DAValidator to facilitate the DA protocol. + +We will now call the logs that are created by users and are Merklized _user_ logs and the logs that are emitted by natively by VM _system_ logs. Here is a short comparison table for better understanding: + +| System logs | User logs | +| --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Emitted by VM via an opcode. | VM knows nothing about them. | +| Consistency and correctness is enforced by the verifier on L1 (i.e. their hash is part of the block commitment. | Consistency and correctness is enforced by the L1Messenger system contract. The correctness of the behavior of the L1Messenger is enforced implicitly by prover in a sense that it proves the correctness of the execution overall. | +| We don’t calculate their Merkle root. | We calculate their Merkle root on the L1Messenger system contract. | +| We have constant small number of those. | We can have as much as possible as long as the commitBatches function on L1 remains executable (it is the job of the operator to ensure that only such transactions are selected) | +| In EIP4844 they will remain part of the calldata. | In EIP4844 they will become part of the blobs. | + +### Backwards-compatibility + +Note, that to maintain a unified interface with the previous version of the protocol, the leaves of the Merkle tree will have to maintain the following structure: + +```solidity +struct L2Log { + uint8 l2ShardId; + bool isService; + uint16 txNumberInBlock; + address sender; + bytes32 key; + bytes32 value; +} +``` + +While the leaf will look the following way: + +```solidity +bytes32 hashedLog = keccak256( + abi.encodePacked(_log.l2ShardId, _log.isService, _log.txNumberInBlock, _log.sender, _log.key, _log.value) +); +``` + +`keccak256` will continue being the function for the merkle tree. + +To put it shortly, the proofs for L2→L1 log inclusion will continue having exactly the same format as they did in the pre-Boojum system, which avoids breaking changes for SDKs and bridges alike. + +### Implementation of `L1Messenger` + +The L1Messenger contract will maintain a rolling hash of all the L2ToL1 logs `chainedLogsHash` as well as the rolling hashes of messages `chainedMessagesHash`. Whenever a contract wants to send an L2→L1 log, the following operation will be [applied](../../../system-contracts/contracts/L1Messenger.sol#L73): + +`chainedLogsHash = keccak256(chainedLogsHash, hashedLog)`. L2→L1 logs have the same 88-byte format as in the current version of ZKsync. + +Note, that the user is charged for necessary future the computation that will be needed to calculate the final merkle root. It is roughly 4x higher than the cost to calculate the hash of the leaf, since the eventual tree might have be 4x times the number nodes. In any case, this will likely be a relatively negligible part compared to the cost of the pubdata. + +At the end of the execution, the bootloader will [provide](../../../system-contracts/bootloader/bootloader.yul#L2676) a list of all the L2ToL1 logs (this will be provided by the operator in the memory of the bootloader). The L1Messenger checks that the rolling hash from the provided logs is the same as in the `chainedLogsHash` and calculate the merkle tree of the provided messages. Right now, we always build the Merkle tree of size `16384`, but we charge the user as if the tree was built dynamically based on the number of leaves in there. The implementation of the dynamic tree has been postponed until the later upgrades. + +> Note, that unlike most other parts of pubdata, the user L2->L1 must always be validated by the trusted `L1Messenger` system contract. If we moved this responsibility to L2DAValidator it would be possible that a malicious operator provided incorrect data and forged transactions out of names of certain users. + +### Long L2→L1 messages & bytecodes + +If the user wants to send an L2→L1 message, its preimage is [appended](../../../system-contracts/contracts/L1Messenger.sol#L126) to the message’s rolling hash too `chainedMessagesHash = keccak256(chainedMessagesHash, keccak256(message))`. + +A very similar approach for bytecodes is used, where their rolling hash is calculated and then the preimages are provided at the end of the batch to form the full pubdata for the batch. + +Note, that in for backward compatibility, just like before any long message or bytecode is accompanied by the corresponding user L2→L1 log. + +### Using system L2→L1 logs vs the user logs + +The content of the L2→L1 logs by the L1Messenger will go to the blob of EIP4844. Meaning, that all the data that belongs to the tree by L1Messenger’s L2→L1 logs should not be needed during block commitment. Also, note that in the future we will remove the calculation of the Merkle root of the built-in L2→L1 messages. + +The only places where the built-in L2→L1 messaging should continue to be used: + +- Logs by SystemContext (they are needed on commit to check the previous block hash). +- Logs by L1Messenger for the merkle root of the L2→L1 tree as well the data needed for L1DAValidator. +- `chainedPriorityTxsHash` and `numberOfLayer1Txs` from the bootloader (read more about it below). + +### Obtaining `txNumberInBlock` + +To have the same log format, the `txNumberInBlock` must be obtained. While it is internally counted in the VM, there is currently no opcode to retrieve this number. We will have a public variable `txNumberInBlock` in the `SystemContext`, which will be incremented with each new transaction and retrieve this variable from there. It is [zeroed out](../../../system-contracts/contracts/SystemContext.sol#L515) at the end of the batch. + +### Bootloader implementation + +The bootloader has a memory segment dedicated to the ABI-encoded data of the L1ToL2Messenger to perform the `publishPubdataAndClearState` call. + +At the end of the execution of the batch, the operator should provide the corresponding data into the bootloader memory, i.e user L2→L1 logs, long messages, bytecodes, etc. After that, the [call](../../../system-contracts/bootloader/bootloader.yul#L2676) is performed to the `L1Messenger` system contract, that would call the L2DAValidator that should check the adherence of the pubdata to the specified format. + +## Bytecode Publishing + +Within pubdata, bytecodes are published in 1 of 2 ways: (1) uncompressed as part of the bytecodes array and (2) compressed via long l2 → l1 messages. + +### Uncompressed Bytecode Publishing + +Uncompressed bytecodes are included within the `totalPubdata` bytes and have the following format: `number of bytecodes || forEachBytecode (length of bytecode(n) || bytecode(n))` . + +### Compressed Bytecode Publishing + +Unlike uncompressed bytecode which are published as part of `factoryDeps`, compressed bytecodes are published as long l2 → l1 messages which can be seen [here](../../../system-contracts/contracts/Compressor.sol#L78). + +#### Bytecode Compression Algorithm — Server Side + +This is the part that is responsible for taking bytecode, that has already been chunked into 8 byte words, performing validation, and compressing it. + +Each 8 byte word from the chunked bytecode is assigned a 2 byte index (constraint on size of dictionary of chunk → index is 2^16 - 1 elements). The length of the dictionary, dictionary entries (index assumed through order), and indexes are all concatenated together to yield the final compressed version. + +For bytecode to be considered valid it must satisfy the following: + +1. Bytecode length must be less than 2097120 ((2^16 - 1) \* 32) bytes. +2. Bytecode length must be a multiple of 32. +3. Number of 32-byte words cannot be even. + +The following is a simplified version of the algorithm: + +```python +statistic: Map[chunk, (count, first_pos)] +dictionary: Map[chunk, index] +encoded_data: List[index] + +for position, chunk in chunked_bytecode: + if chunk is in statistic: + statistic[chunk].count += 1 + else: + statistic[chunk] = (count=1, first_pos=pos) + +# We want the more frequently used bytes to have smaller ids to save on calldata (zero bytes cost less) +statistic.sort(primary=count, secondary=first_pos, order=desc) + +for index, chunk in enumerated(sorted_statistics): + dictionary[chunk] = index + +for chunk in chunked_bytecode: + encoded_data.append(dictionary[chunk]) + +return [len(dictionary), dictionary.keys(order=index asc), encoded_data] +``` + +#### Verification And Publishing — L2 Contract + +The function `publishCompressBytecode` takes in both the original `_bytecode` and the `_rawCompressedData` , the latter of which comes from the output of the server’s compression algorithm. Looping over the encoded data, derived from `_rawCompressedData` , the corresponding chunks are pulled from the dictionary and compared to the original byte code, reverting if there is a mismatch. After the encoded data has been verified, it is published to L1 and marked accordingly within the `KnownCodesStorage` contract. + +Pseudo-code implementation: + +```python +length_of_dict = _rawCompressedData[:2] +dictionary = _rawCompressedData[2:2 + length_of_dict * 8] # need to offset by bytes used to store length (2) and multiply by 8 for chunk size +encoded_data = _rawCompressedData[2 + length_of_dict * 8:] + +assert(len(dictionary) % 8 == 0) # each element should be 8 bytes +assert(num_entries(dictionary) <= 2^16) +assert(len(encoded_data) * 4 == len(_bytecode)) # given that each chunk is 8 bytes and each index is 2 bytes they should differ by a factor of 4 + +for (index, dict_index) in list(enumerate(encoded_data)): + encoded_chunk = dictionary[dict_index] + real_chunk = _bytecode.readUint64(index * 8) # need to pull from index * 8 to account for difference in element size + verify(encoded_chunk == real_chunk) + +# Sending the compressed bytecode to L1 for data availability +sendToL1(_rawCompressedBytecode) +markAsPublished(hash(_bytecode)) +``` + +## Storage diff publishing + +ZKsync is a statediff-based rollup and so publishing the correct state diffs plays an integral role in ensuring data availability. + +### Difference between initial and repeated writes + +ZKsync publishes state changes that happened within the batch instead of transactions themselves. Meaning, that for instance some storage slot `S` under account `A` has changed to value `V`, we could publish a triple of `A,S,V`. Users by observing all the triples could restore the state of ZKsync. However, note that our tree unlike Ethereum’s one is not account based (i.e. there is no first layer of depth 160 of the merkle tree corresponding to accounts and second layer of depth 256 of the merkle tree corresponding to users). Our tree is “flat”, i.e. a slot `S` under account `A` is just stored in the leaf number `H(S,A)`. Our tree is of depth 256 + 8 (the 256 is for these hashed account/key pairs and 8 is for potential shards in the future, we currently have only one shard and it is irrelevant for the rest of the document). + +We call this `H(S,A)` _derived key_, because it is derived from the address and the actual key in the storage of the account. Since our tree is flat, whenever a change happens, we can publish a pair `DK, V`, where `DK=H(S,A)`. + +However, these is an optimization that could be done: + +- Whenever a change to a key is used for the first time, we publish a pair of `DK,V` and we assign some sequential id to this derived key. This is called an _initial write_. It happens for the first time and that’s why we must publish the full key. +- If this storage slot is published in some of the subsequent batches, instead of publishing the whole `DK`, we can use the sequential id instead. This is called a _repeated write_. + +For instance, if the slots `A`,`B` (I’ll use latin letters instead of 32-byte hashes for readability) changed their values to `12`,`13` accordingly, in the batch it happened they will be published in the following format: + +- `(A, 12), (B, 13)`. Let’s say that the last sequential id ever used is 6. Then, `A` will receive the id of `7` and B will receive the id of `8`. + +Let’s say that in the next block, they changes their values to `13`,`14`. Then, their diff will be published in the following format: + +- `(7, 13), (8,14)`. + +The id is permanently assigned to each storage key that was ever published. While in the description above it may not seem like a huge boost, however, each `DK` is 32 bytes long and id is at most 8 bytes long. + +We call this id _enumeration_index_. + +Note, that the enumeration indexes are assigned in the order of sorted array of (address, key), i.e. they are internally sorted. The enumeration indexes are part of the state merkle tree, it is **crucial** that the initial writes are published in the correct order, so that anyone could restore the correct enum indexes for the storage slots. In addition, an enumeration index of `0` indicates that the storage write is an initial write. + +### State diffs structure + +Firstly, let’s define what we mean by _state diffs_. A _state diff_ is an element of the following structure. + +[State diff structure](https://github.com/matter-labs/zksync-protocol/blob/main/crates/circuit_encodings/src/state_diff_record.rs#L8). + +Basically, it contains all the values which might interest us about the state diff: + +- `address` where the storage has been changed. +- `key` (the original key inside the address) +- `derived_key` — `H(key, address)` as described in the previous section. + - Note, the hashing algorithm currently used here is `Blake2s` +- `enumeration_index` — Enumeration index as explained above. It is equal to 0 if the write is initial and contains the non-zero enumeration index if it is the repeated write (indexes are numerated starting from 1). +- `initial_value` — The value that was present in the key at the start of the batch +- `final_value` — The value that the key has changed to by the end of the batch. + +We will consider `stateDiffs` an array of such objects, sorted by (address, key). + +This is the internal structure that is used by the circuits to represent the state diffs. The most basic “compression” algorithm is the one described above: + +- For initial writes, write the pair of (`derived_key`, `final_value`) +- For repeated writes write the pair of (`enumeration_index`, `final_value`). + +Note, that values like `initial_value`, `address` and `key` are not used in the "simplified" algorithm above, but they will be helpful for the more advanced compression algorithms in the future. The [algorithm](#state-diff-compression-format) for Boojum already utilizes the difference between the `initial_value` and `final_value` for saving up on pubdata. + +### How the new pubdata verification works + +#### **L2** + +1. The operator provides both full `stateDiffs` (i.e. the array of the structs above) and the compressed state diffs (i.e. the array which contains the state diffs, compressed by the algorithm explained [below](#state-diff-compression-format)). +2. The L2DAValidator must verify that the compressed version is consistent with the original stateDiffs and send the the _hash_ of the original state diff to its L1 counterpart. It will also include the compressed state diffs into the totalPubdata to be published onto L1. + +#### **L1** + +1. During committing the block, the standard DA protocol follows and the L1DAValidator is responsible to check that the operator has provided the preimage for the `_totalPubdata`. More on how this is checked can be seen [here](./rollup_da.md). +2. The block commitment [includes](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L550) \*the hash of the `stateDiffs`. Thus, during ZKP verification will fail if the provided stateDiff hash is not correct. + +It is a secure construction because the proof can be verified only if both the execution was correct and the hash of the provided hash of the `stateDiffs` is correct. This means that the L2DAValidator indeed received the array of correct `stateDiffs` and, assuming the L2DAValidator is working correctly, double-checked that the compression is of the correct format, while L1 contracts on the commit stage double checked that the operator provided the preimage for the compressed state diffs. + +### State diff compression format + +The following algorithm is used for the state diff compression: + +[State diff compression v1 spec](./state_diff_compression_v1_spec.md) + +## General pubdata format + +The `totalPubdata` has the following structure: + +1. First 4 bytes — the number of user L2→L1 logs in the batch +2. Then, the concatenation of packed L2→L1 user logs. +3. Next, 4 bytes — the number of long L2→L1 messages in the batch. +4. Then, the concatenation of L2→L1 messages, each in the format of `<4 byte length || actual_message>`. +5. Next, 4 bytes — the number of uncompressed bytecodes in the batch. +6. Then, the concatenation of uncompressed bytecodes, each in the format of `<4 byte length || actual_bytecode>`. +7. Next, 4 bytes — the length of the compressed state diffs. +8. Then, state diffs are compressed by the spec [above](#state-diff-compression-format). + +The interface for committing batches is the following one: + +```solidity +/// @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 totalL2ToL1Pubdata Total pubdata committed to as part of bootloader run. Contents are: l2Tol1Logs <> l2Tol1Messages <> publishedBytecodes <> stateDiffs +struct CommitBatchInfo { + uint64 batchNumber; + uint64 timestamp; + uint64 indexRepeatedStorageChanges; + bytes32 newStateRoot; + uint256 numberOfLayer1Txs; + bytes32 priorityOperationsHash; + bytes32 bootloaderHeapInitialContentsHash; + bytes32 eventsQueueStateHash; + bytes systemLogs; + bytes totalL2ToL1Pubdata; +} +``` diff --git a/docs/settlement_contracts/data_availability/state_diff_compression_v1_spec.md b/docs/settlement_contracts/data_availability/state_diff_compression_v1_spec.md new file mode 100644 index 000000000..5fae9cedf --- /dev/null +++ b/docs/settlement_contracts/data_availability/state_diff_compression_v1_spec.md @@ -0,0 +1,89 @@ +# State diff compression v1 spec + +[back to readme](../../README.md) + +The most basic strategy to publish state diffs is to publish those in either of the following two forms: + +- When a key is updated for the first time — ``, where key is 32-byte derived key and the value is new 32-byte value of the slot. +- When a key is updated for the second time and more — ``, where the `enumeration_index` is an 8-byte id of the slot and the value is the new 32-byte value of the slot. + +This compression strategy will utilize a similar idea for treating keys and values separately and it will be focused on the efficient compression of keys and values separately. + +## Keys + +Keys will be packed in the same way as they were before. The only change is that we’ll avoid using the 8-byte enumeration index and will pack it to the minimal necessary number of bytes. This number will be part of the pubdata. Once a key has been used, it can already use the 4 or 5 byte enumeration index and it is very hard to have something cheaper for keys that has been used already. The opportunity comes when remembering the ids for accounts to spare some bytes on nonce/balance key, but ultimately the complexity may not be worth it. + +There is some room for optimization of the keys that are being written for the first time, however, optimizing those is more complex and achieves only a one-time effect (when the key is published for the first time), so they may be in scope of the future upgrades. + +## Values + +Values are much easier to compress since they usually contain only zeroes. Also, we can leverage the nature of how those values are changed. For instance, if nonce has been increased only by 1, we do not need to write the entire 32-byte new value, we can just tell that the slot has been _increased_ and then supply only the 1-byte value by which it was increased. This way instead of 32 bytes we need to publish only 2 bytes: first byte to denote which operation has been applied and the second by to denote the number by which the addition has been made. + +We have the following 4 types of changes: `Add`, `Sub,` `Transform`, `NoCompression` where: + +- `NoCompression` denotes that the whole 32 byte will be provided. +- `Add` denotes that the value has been increased. (modulo 2^256) +- `Sub` denotes that the value has been decreased. (modulo 2^256) +- `Transform` denotes the value just has been changed (i.e. we disregard any potential relation between the previous and the new value, though the new value might be small enough to save up on the number of bytes). + +Where the byte size of the output can be anywhere from 0 to 31 (also 0 makes sense for `Transform`, since it denotes that it has been zeroed out). For `NoCompression` the whole 32 byte value is used. + +So the format of the pubdata is the following: + +**Part 1. Header.** + +- `` — this will enable easier automated unpacking in the future. Currently, it will be only equal to `1`. +- `` — we need only 3 bytes to describe the total length of the L2→L1 logs. +- ``. It should be equal to the minimal required bytes to represent the enum indexes for repeated writes. + +**Part 2. Initial writes.** + +- `` - the number of initial writes. Since each initial write publishes at least 32 bytes for key, then `2^16 * 32 = 2097152` will be enough for a lot of time (right now with the limit of 120kb it will take more than 15 L1 txs to use up all the space there). +- Then for each `` pair for each initial write: + - print key as 32-byte derived key. + - packing type as a 1 byte value, which consists of 5 bits to denote the length of the packing and 3 bits to denote the type of the packing (either `Add`, `Sub`, `Transform` or `NoCompression`). + - The packed value itself. + +**Part 3. Repeated writes.** + +Note, that there is no need to write the number of repeated writes, since we know that until the end of the pubdata, all the writes will be repeated ones. + +- For each `` pair for each repeated write: + - print key as derived key by using the number of bytes provided in the header. + - packing type as a 1 byte value, which consists of 5 bits to denote the length of the packing and 3 bits to denote the type of the packing (either `Add`, `Sub`, `Transform` or `NoCompression`). + - The packed value itself. + +## Impact + +This setup allows us to achieve nearly 75% packing for values, and 50% gains overall in terms of the storage logs based on historical data. + +## Encoding of packing type + +Since we have `32 * 3 + 1` ways to pack a state diff, we need at least 7 bits to present the packing type. To make parsing easier, we will use 8 bits, i.e. 1 byte. + +We will use the first 5 bits to represent the length of the bytes (from 0 to 31 inclusive) to be used. The other 3 bits will be used to represent the type of the packing: `Add`, `Sub` , `Transform`, `NoCompression`. + +## Worst case scenario + +The worst case scenario for such packing is when we have to pack a completely random new value, i.e. it will take us 32 bytes to pack + 1 byte to denote which type it is. However, for such a write the user will anyway pay at least for 32 bytes. Adding an additional byte is roughly 3% increase, which will likely be barely felt by users, most of which use storage slots for balances, etc, which will consume only 7-9 bytes for packed value. + +## Why do we need to repeat the same packing method id + +You might have noticed that for each pair `` to describe value we always first write the packing type and then write the packed value. However, the reader might ask, it is more efficient to just supply the packing id once and then list all the pairs `` which use such packing. + +I.e. instead of listing + +(key = 0, type = 1, value = 1), (key = 1, type = 1, value = 3), (key = 2, type = 1, value = 4), … + +Just write: + +type = 1, (key = 0, value = 1), (key = 1, value = 3), (key = 2, value = 4), … + +There are two reasons for it: + +- A minor reason: sometimes it is less efficient in case the packing is used for very few slots (since for correct unpacking we need to provide the number of slots for each packing type). +- A fundamental reason: currently enum indices are stored directly in the merkle tree & have very strict order of incrementing enforced by the circuits and (they are given in order by pairs `(address, key)`), which are generally not accessible from pubdata. + +All this means that we are not allowed to change the order of “first writes” above, so indexes for them are directly recoverable from their order, and so we can not permute them. If we were to reorder keys without supplying the new enumeration indices for them, the state would be unrecoverable. Always supplying the new enum index may add additional 5 bytes for each key, which might negate the compression benefits in a lot of cases. Even if the compression will still be beneficial, the added complexity may not be worth it. + +That being said, we _could_ rearange those for _repeated_ writes, but for now we stick to the same value compression format for simplicity. diff --git a/docs/settlement_contracts/img/Diamond-scheme.png b/docs/settlement_contracts/img/Diamond-scheme.png new file mode 100644 index 000000000..eac56be5a Binary files /dev/null and b/docs/settlement_contracts/img/Diamond-scheme.png differ diff --git a/docs/gateway/PQ1.png b/docs/settlement_contracts/priority_queue/img/PQ1.png similarity index 100% rename from docs/gateway/PQ1.png rename to docs/settlement_contracts/priority_queue/img/PQ1.png diff --git a/docs/gateway/PQ2.png b/docs/settlement_contracts/priority_queue/img/PQ2.png similarity index 100% rename from docs/gateway/PQ2.png rename to docs/settlement_contracts/priority_queue/img/PQ2.png diff --git a/docs/gateway/PQ3.png b/docs/settlement_contracts/priority_queue/img/PQ3.png similarity index 100% rename from docs/gateway/PQ3.png rename to docs/settlement_contracts/priority_queue/img/PQ3.png diff --git a/docs/gateway/priority-merkle-tree.md b/docs/settlement_contracts/priority_queue/priority-queue.md similarity index 96% rename from docs/gateway/priority-merkle-tree.md rename to docs/settlement_contracts/priority_queue/priority-queue.md index ffd52237d..59384bb0a 100644 --- a/docs/gateway/priority-merkle-tree.md +++ b/docs/settlement_contracts/priority_queue/priority-queue.md @@ -1,4 +1,6 @@ -# Migrating Priority Queue to Merkle Tree +# Priority Queue to Merkle Tree + +[back to readme](../../README.md) ## Overview of the current implementation @@ -21,7 +23,7 @@ of which we only care about the canonical hash. ### Inserting new operations -The queue is implemented as a [library](https://github.com/matter-labs/era-contracts/blob/f3630fcb01ad8b6e2e423a6f313abefe8502c3a2/l1-contracts/contracts/zksync/libraries/PriorityQueue.sol#L20). +The queue is implemented as a [library](../../../l1-contracts/contracts/state-transition/libraries/PriorityQueue.sol#L22). For each incoming priority operation, we simply `pushBack` its hash, expiration and layer2Tip. ### Checking validity @@ -108,11 +110,11 @@ corresponding to the already executed operations. We will only cache some prefix of the tree, meaning nodes in the interval [0; N) where N is the number of executed priority operations. The cache will store the rightmost cached left-child node on each level of the tree (see diagrams). -![Untitled](./PQ1.png) +![Untitled](./img/PQ1.png) -![Untitled](./PQ2.png) +![Untitled](./img/PQ2.png) -![Untitled](./PQ3.png) +![Untitled](./img/PQ3.png) This means that we will not be able to generate merkle proofs for the cached nodes (and since they are already executed, we don't need to). This structure allows us to save a lot of space, since it only takes up `O(height)` space instead of linear space for all executed operations. This is a big optimization since there are currently 3.2M total operations but <10 non-executed operations in the mainnet priority queue, which means most of the tree will be cached. diff --git a/docs/settlement_contracts/priority_queue/processing_of_l1->l2_txs.md b/docs/settlement_contracts/priority_queue/processing_of_l1->l2_txs.md new file mode 100644 index 000000000..c6af14c61 --- /dev/null +++ b/docs/settlement_contracts/priority_queue/processing_of_l1->l2_txs.md @@ -0,0 +1,98 @@ +# Handling L1→L2 ops on ZKsync + +[back to readme](../../README.md) + +The transactions on ZKsync can be initiated not only on L2, but also on L1. There are two types of transactions that can be initiated on L1: + +- Priority operations. These are the kind of operations that any user can create. +- Upgrade transactions. These can be created only during upgrades. + +## Prerequisites + +Please read the full [article](../../l2_system_contracts/system_contracts_bootloader_description.md) on the general system contracts / bootloader structure as well as the pubdata structure to understand [the difference](../data_availability/standard_pubdata_format.md) between system and user logs. + +## Priority operations + +### Initiation + +A new priority operation can be appended by calling the `requestL2TransactionDirect` or `requestL2TransactionTwoBridges` methods on `BridgeHub` smart contract. `BridgeHub` will ensure that the base token is deposited via `L1AssetRouter` and send transaction request to the specified state transition contract (selected by the chainID). State transition contract will perform several checks for the transaction, making sure that it is processable and provides enough fee to compensate the operator for this transaction. Then, this transaction will be [appended](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Mailbox.sol#569) to the priority tree (and optionally to the legacy priority queue). + +> In the previous system, priority operations were structured in a queue. However, now they will be stored in an incremental merkle tree. The motivation for the tree structure can be read [here](./priority-queue.md). + +The difference between `requestL2TransactionDirect` and `requestL2TransactionTwoBridges` is that the `msg.sender` on the L2 Transaction is the second bridge in the `requestL2TransactionTwoBridges` case, while it is the `msg.sender` of the `requestL2TransactionDirect` in the first case. For more details read the [bridgehub documentation](../../bridging/bridgehub/overview.md) + +### Bootloader + +Whenever an operator sees a priority operation, it can include the transaction into the batch. While for normal L2 transaction the account abstraction protocol will ensure that the `msg.sender` has indeed agreed to start a transaction out of this name, for L1→L2 transactions there is no signature verification. In order to verify that the operator includes only transactions that were indeed requested on L1, the bootloader maintains](../../system-contracts/bootloader/bootloader.yul#L1052-L1053) two variables: + +- `numberOfPriorityTransactions` (maintained at `PRIORITY_TXS_L1_DATA_BEGIN_BYTE` of bootloader memory) +- `priorityOperationsRollingHash` (maintained at `PRIORITY_TXS_L1_DATA_BEGIN_BYTE + 32` of the bootloader memory) + +Whenever a priority transaction is processed, the `numberOfPriorityTransactions` gets incremented by 1, while `priorityOperationsRollingHash` is assigned to `keccak256(priorityOperationsRollingHash, processedPriorityOpHash)`, where `processedPriorityOpHash` is the hash of the priority operations that has been just processed. + +Also, for each priority transaction, we [emit](../../../system-contracts/bootloader/bootloader.yul#L1046) a user L2→L1 log with its hash and result, which basically means that it will get Merklized and users will be able to prove on L1 that a certain priority transaction has succeeded or failed (which can be helpful to reclaim your funds from bridges if the L2 part of the deposit has failed). + +Then, at the end of the batch, we [submit](../../../system-contracts/bootloader/bootloader.yul#L4117-L4118) 2 L2→L1 log system log with these values. + +### Batch commit + +During batch commit, the contract will remember those values, but not validate them in any way. + +### Batch execution + +During batch execution, the will check that the `priorityOperationsRollingHash` rolling hash provided before was correct. There are two ways to do it: + +- [Legacy one that uses priority queue](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L397). We will pop `numberOfPriorityTransactions` from the top of priority queue and verify that the hashes match. +- [The new one that uses priority tree](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L397). The operator would have to provide the hashes of these priority operations in an array, as well as proof that this entire segment belongs to the merkle tree. After it is verified that this array of leaves is correct, it will be checked whether the rolling hash of those is equal to the `priorityOperationsRollingHash`. + +## Upgrade transactions + +### Initiation + +Upgrade transactions can only be created during a system upgrade. It is done if the `DiamondProxy` delegatecalls to the implementation that manually puts this transaction into the storage of the DiamondProxy, this could happen on calling `upgradeChainFromVersion` function in `Admin.sol` on the State Transition contract. Note, that since it happens during the upgrade, there is no “real” checks on the structure of this transaction. We do have [some validation](../../../l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol#L193), but it is purely on the side of the implementation which the `DiamondProxy` delegatecalls to and so may be lifted if the implementation is changed. + +The hash of the currently required upgrade transaction is stored under `l2SystemContractsUpgradeTxHash` variable. + +We will also track the batch where the upgrade has been committed in the `l2SystemContractsUpgradeBatchNumber` variable. + +We can not support multiple upgrades in parallel, i.e. the next upgrade should start only after the previous one has been complete. + +### Bootloader + +The upgrade transactions are processed just like with priority transactions, with only the following differences: + +- We can have only one upgrade transaction per batch & this transaction must be the first transaction in the batch. +- The system contracts upgrade transaction is not appended to `priorityOperationsRollingHash` and doesn’t increment `numberOfPriorityTransactions`. Instead, its hash is calculated via a system L2→L1 log _before_ it gets executed. Note, that it is an important property. More on it [below](#security-considerations). + +### Commit + +After an upgrade has been initiated, it will be required that the next commit batches operation already contains the system upgrade transaction. It is [checked](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L223) by verifying the corresponding L2→L1 log. + +We also remember that the upgrade transaction has been processed in this batch (by amending the `l2SystemContractsUpgradeBatchNumber` variable). + +### Revert + +In a very rare event when the team needs to revert the batch with the upgrade on ZKsync, the `l2SystemContractsUpgradeBatchNumber` is reset. + +Note, however, that we do not “remember” that certain batches had a version before the upgrade, i.e. if the reverted batches will have to be reexecuted, the upgrade transaction must still be present there, even if some of the deleted batches were committed before the upgrade and thus didn’t contain the transaction. + +### Execute + +Once batch with the upgrade transaction has been executed, we [delete](../../../l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol#L486) them from storage for efficiency to signify that the upgrade has been fully processed and that a new upgrade can be initiated. + +### Security considerations + +Since the operator can put any data into the bootloader memory and for L1→L2 transactions the bootloader has to blindly trust it and rely on L1 contracts to validate it, it may be a very powerful tool for a malicious operator. Note, that while the governance mechanism is trusted, we try to limit our trust for the operator as much as possible, since in the future anyone would be able to become an operator. + +Some time ago, we _used to_ have a system where the upgrades could be done via L1→L2 transactions, i.e. the implementation of the `DiamondProxy` upgrade would include a priority transaction (with `from` equal to for instance `FORCE_DEPLOYER`) with all the upgrade params. + +In the current system though having such logic would be dangerous and would allow for the following attack: + +- Let’s say that we have at least 1 priority operations in the priority queue. This can be any operation, initiated by anyone. +- The operator puts a malicious priority operation with an upgrade into the bootloader memory. This operation was never included in the priority operations queue / and it is not an upgrade transaction. However, as already mentioned above the bootloader has no idea what priority / upgrade transactions are correct and so this transaction will be processed. + +The most important caveat of this malicious upgrade is that it may change implementation of the `Keccak256` precompile to return any values that the operator needs. + +- When the`priorityOperationsRollingHash` will be updated, instead of the “correct” rolling hash of the priority transactions, the one which would appear with the correct topmost priority operation is returned. The operator can’t amend the behaviour of `numberOfPriorityTransactions`, but it won’t help much, since the the `priorityOperationsRollingHash` will match on L1 on the execution step. + +That’s why the concept of the upgrade transaction is needed: this is the only transaction that can initiate transactions out of the kernel space and thus change bytecodes of system contracts. That’s why it must be the first one and that’s why bootloader [emits](../../../system-contracts/bootloader/bootloader.yul#L603) its hash via a system L2→L1 log before actually processing it. diff --git a/docs/settlement_contracts/zkchain_basics.md b/docs/settlement_contracts/zkchain_basics.md new file mode 100644 index 000000000..1d6c7bfb9 --- /dev/null +++ b/docs/settlement_contracts/zkchain_basics.md @@ -0,0 +1,172 @@ +# L1 smart contract of an individual chain + +[back to readme](../README.md) + +## Diamond (also mentioned as State Transition contract) + +Technically, this L1 smart contract acts as a connector between Ethereum (L1) and hyperchain (L2). It checks the +validity proof and data availability, handles L2 <-> L1 communication, finalizes L2 state transition, and more. + +There are also important contracts deployed on the L2 that can also execute logic called _system contracts_. Using L2 +<-> L1 communication can affect both the L1 and the L2. + +![diamondProxy.png](./img/Diamond-scheme.png) + +### DiamondProxy + +The main contract uses [EIP-2535](https://eips.ethereum.org/EIPS/eip-2535) diamond proxy pattern. It is an in-house +implementation that is inspired by the [mudgen reference implementation](https://github.com/mudgen/Diamond). It has no +external functions, only the fallback that delegates a call to one of the facets (target/implementation contract). So +even an upgrade system is a separate facet that can be replaced. + +One of the differences from the reference implementation is access freezability. Each of the facets has an associated +parameter that indicates if it is possible to freeze access to the facet. Privileged actors can freeze the **diamond** +(not a specific facet!) and all facets with the marker `isFreezable` should be inaccessible until the governor or admin +unfreezes the diamond. Note that it is a very dangerous thing since the diamond proxy can freeze the upgrade system and then +the diamond will be frozen forever. + +The diamond proxy pattern is very flexible and extendable. For now, it allows splitting implementation contracts by their logical meaning, removes the limit of bytecode size per contract and implements security features such as freezing. In the future, it can also be viewed as [EIP-6900](https://eips.ethereum.org/EIPS/eip-6900) for [zkStack](https://blog.matter-labs.io/introducing-the-zk-stack-c24240c2532a), where each hyperchain can implement a sub-set of allowed implementation contracts. + +### GettersFacet + +Separate facet, whose only function is providing `view` and `pure` methods. It also implements +[diamond loupe](https://eips.ethereum.org/EIPS/eip-2535#diamond-loupe) which makes managing facets easier. +This contract must never be frozen. + +### AdminFacet + +This facet responsible for the configuration setup and upgradability, handling tasks such as: + +- Privileged Address Management: Updating key roles, including the governor and validators. +- System Parameter Configuration: Adjusting critical system settings, such as the L2 bootloader bytecode hash, verifier address, changing DA layer or fee configurations. +- Freezability: Executing the freezing/unfreezing of facets within the diamond proxy to safeguard the ecosystem during upgrades or in response to detected vulnerabilities. + +Control over the AdminFacet is divided between two main entities: + +- CTM (Chain Type Manager, formerly known as `StateTransitionManager`) - Separate smart contract that can perform critical changes to the system as protocol upgrades. For more detailed information on its function and design, refer to [this document](../chain_management/chain_type_manager.md). Although currently only one version of the CTM exists, the architecture allows for future versions to be introduced via subsequent upgrades. The owner of the CTM is the [decentralized governance](https://blog.zknation.io/introducing-zk-nation/), while for non-critical an Admin entity is used (see details below). +- Chain Admin - Multisig smart contract managed by each individual chain that can perform non-critical changes to the system such as granting validator permissions. + +### MailboxFacet + +The facet that handles L2 <-> L1 communication. + +The Mailbox performs three functions: + +- L1 ↔ L2 Communication: Enables data and transaction requests to be sent from L1 to L2 and vice versa, supporting the implementation of multi-layer protocols. +- Bridging Native Tokens: Allows the bridging of either ether or ERC20 tokens to L2, enabling users to use these assets within the L2 ecosystem. +- Censorship Resistance Mechanism: Currently in the research stage. + +L1 -> L2 communication is implemented as requesting an L2 transaction on L1 and executing it on L2. This means a user +can call the function on the L1 contract to save the data about the transaction in some queue. Later on, a validator can +process it on L2 and mark it as processed on the L1 priority queue. Currently, it is used for sending information from +L1 to L2 or implementing multi-layer protocols. Users pays for the transaction execution in the native token when requests L1 -> L2 transaction. + +_NOTE_: While user requests the transaction from L1, the initiated transaction on L2 will have such a `msg.sender`: + +```solidity + address sender = msg.sender; + if (sender != tx.origin) { + sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender); + } +``` + +where + +```solidity +uint160 constant offset = uint160(0x1111000000000000000000000000000000001111); + +function applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) { + unchecked { + l2Address = address(uint160(l1Address) + offset); + } +} +``` + +For most of the rollups the address aliasing needs to prevent cross-chain exploits that would otherwise be possible if +we simply reused the same L1 addresses as the L2 sender. In ZKsync Era address derivation rule is different from the +Ethereum, so cross-chain exploits are already impossible. However, ZKsync Era may add full EVM support in the future, so +applying address aliasing leaves room for future EVM compatibility. + +The L1 -> L2 communication is also used for bridging **base tokens**. If base token is ether (the case for ZKsync Era) - user should include a `msg.value` when initiating a +transaction request on the L1 contract, if base token is an ERC20 then contract will spend users allowance. Before executing a transaction on L2, the specified address will be credited +with the funds. To withdraw funds user should call `withdraw` function on the `L2BaseToken` system contracts. This will +burn the funds on L2, allowing the user to reclaim them through the `finalizeWithdrawal` function on the +`SharedBridge` (more in hyperchain section). + +More about L1->L2 operations can be found [here](./priority_queue/processing_of_l1->l2_txs.md). + +L2 -> L1 communication, in contrast to L1 -> L2 communication, is based only on transferring the information, and not on +the transaction execution on L1. The full description of the mechanism for sending information from L2 to L1 can be found [here](./data_availability/standard_pubdata_format.md). + +The Mailbox facet also facilitates L1<>L3 communications for those chains that settle on top of Gateway. The user interfaces for those are identical to the L1<>L2 communication described above. To learn more about L1<>L3 communication works, check out [this document](../gateway/messaging_via_gateway.md) and [this one](../gateway/nested_l3_l1_messaging.md). + +### ExecutorFacet + +A contract that accepts L2 batches, enforces data availability via DA validators and checks the validity of zk-proofs. You can read more about DA validators [in this document](../settlement_contracts/data_availability/custom_da.md). + +The state transition is divided into three stages: + +- `commitBatches` - check L2 batch timestamp, process the L2 logs, save data for a batch, and prepare data for zk-proof. +- `proveBatches` - validate zk-proof. +- `executeBatches` - finalize the state, marking L1 -> L2 communication processing, and saving Merkle tree with L2 logs. + +Each L2 -> L1 system log will have a key that is part of the following: + +```solidity +enum SystemLogKey { + L2_TO_L1_LOGS_TREE_ROOT_KEY, + PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, + CHAINED_PRIORITY_TXN_HASH_KEY, + NUMBER_OF_LAYER_1_TXS_KEY, + PREV_BATCH_HASH_KEY, + L2_DA_VALIDATOR_OUTPUT_HASH_KEY, + USED_L2_DA_VALIDATOR_ADDRESS_KEY, + EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY +} +``` + +When a batch is committed, we process L2 -> L1 system logs. Here are the invariants that are expected there: + +- In a given batch there will be either 7 or 8 system logs. The 8th log is only required for a protocol upgrade. +- There will be a single log for each key that is contained within `SystemLogKey` +- Three logs from the `L2_TO_L1_MESSENGER` with keys: +- `L2_TO_L1_LOGS_TREE_ROOT_KEY` +- `L2_DA_VALIDATOR_OUTPUT_HASH_KEY` +- `USED_L2_DA_VALIDATOR_ADDRESS_KEY` +- Two logs from `L2_SYSTEM_CONTEXT_SYSTEM_CONTRACT_ADDR` with keys: + - `PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY` + - `PREV_BATCH_HASH_KEY` +- Two or three logs from `L2_BOOTLOADER_ADDRESS` with keys: + - `CHAINED_PRIORITY_TXN_HASH_KEY` + - `NUMBER_OF_LAYER_1_TXS_KEY` + - `EXPECTED_SYSTEM_CONTRACT_UPGRADE_TX_HASH_KEY` +- None logs from other addresses (may be changed in the future). + +### DiamondInit + +It is a one-function contract that implements the logic of initializing a diamond proxy. It is called only once on the +diamond constructor and is not saved in the diamond as a facet. + +Implementation detail - function returns a magic value just like it is designed in +[EIP-1271](https://eips.ethereum.org/EIPS/eip-1271), but the magic value is 32 bytes in size. + +## ValidatorTimelock + +An intermediate smart contract between the validator EOA account and the ZK chain diamond contract. Its primary purpose is +to provide a trustless means of delaying batch execution without modifying the main ZKsync contract. ZKsync actively +monitors the chain activity and reacts to any suspicious activity by freezing the chain. This allows time for +investigation and mitigation before resuming normal operations. + +It is a temporary solution to prevent any significant impact of the validator hot key leakage, while the network is in +the Alpha stage. + +This contract consists of four main functions `commitBatches`, `proveBatches`, `executeBatches`, and `revertBatches`, which can be called only by the validator. + +When the validator calls `commitBatches`, the same calldata will be propagated to the ZKsync contract (`DiamondProxy` through +`call` where it invokes the `ExecutorFacet` through `delegatecall`), and also a timestamp is assigned to these batches to track +the time these batches are committed by the validator to enforce a delay between committing and execution of batches. Then, the +validator can prove the already committed batches regardless of the mentioned timestamp, and again the same calldata (related +to the `proveBatches` function) will be propagated to the ZKsync contract. After the `delay` is elapsed, the validator +is allowed to call `executeBatches` to propagate the same calldata to ZKsync contract. + +The owner of the ValidatorTimelock contract is the decentralized governance. Note, that all the chains share the same ValidatorTimelock for simplicity. diff --git a/docs/upgrade_history/gateway_upgrade/gateway_diff_review.md b/docs/upgrade_history/gateway_upgrade/gateway_diff_review.md new file mode 100644 index 000000000..a1518242f --- /dev/null +++ b/docs/upgrade_history/gateway_upgrade/gateway_diff_review.md @@ -0,0 +1,100 @@ +# Gateway upgrade changes + +## Introduction & prerequisites + +[back to readme](../../README.md) + +This document assumes that the reader has general knowledge of how ZKsync Era works and how our ecosystem used to be like at the moment of shared bridge in general. + +To read the documentation about the current system, you can read [here](../../README.md). + +For more info about the previous one, you can reach out to the following documentation: + +[Code4rena Documentation Smart contract Section](https://github.com/code-423n4/2024-03-zksync/tree/main/docs/Smart%20contract%20Section) + +## Changes from the shared bridge design + +This section contains some of the important changes that happened since the shared bridge release in June. This section may not be fully complete and additional information will be provided in the sections that cover specific topics. + +### Bridgehub now has chainId → address mapping + +Before, Bridgehub contained a mapping from `chainId => stateTransitionManager`. The further resolution of the mapping should happen at the CTM level. +For more intuitive management of the chains, a new mapping `chainId => hyperchainAddress` was added. This is considered more intuitive since “bridgehub is the owner of all the chains” mentality is more applicable with this new design. + +The upside of the previous approach was potentially easier migration within the same CTM. However, in the end it was decided that the new approach is better. + +#### Migration + +This new mapping will have to be filled up after upgrading the bridgehub. It is done by repeatedly calling the `setLegacyChainAddress` for each of the deployed chains. It is assumed that their number is relatively low. Also, this function is permissionless and so can be called by anyone after the upgrade is complete. This function will call the old CTM and ask for the implementation of the chainId. + +Until the migration is done, all transactions with the old chains will not be working, but it is a short period of time. + +### baseTokenAssetId is used as a base token for the chains + +In order to facilitate future support of any type of asset a base token, including assets minted on L2, now chains will provide the `assetId` for their base token instead. The derivation & definition of the `assetId` is expanded in the CAB section of the doc. + +#### Migration & compatibility + +Today, there are some mappings of sort `chainId => baseTokenAddress`. These will no longer be filled for new chains. Instead, only assetId will be provided in a new `chainId => baseTokenAssetId` mapping. + +To initialize the new `baseTokenAssetId` mapping the following function should be called for each chain: `setLegacyBaseTokenAssetId`. It will encode each token as the assetId of an L1 token of the Native Token Vault. This method is permissionless. + +For the old tooling that may rely on getters of sort `getBaseTokenAddress(chainId)` working, we provide a getter method, but its exact behavior depends on the asset handler of the `setLegacyBaseTokenAssetId`, i.e. it is even possible that the method will revert for an incompatible assetId. + +### L2 Shared bridge (not L2AssetRouter) is deployed everywhere at the same address + +Before, for each new chain, we would have to initialize the mapping in the L1SharedBridge to remember the address of the l2 shared bridge on the corresponding L2 chain. + +Now, however, the L2AssetRouter is set on the same constant on all chains. + +#### L2SharedBridgeLegacy + +Note, that for the chains that contained the `L2SharedBridge` before the upgrade, it will be upgraded to the `L2SharedBridgeLegacy` code. The `L2AssetRouter` will have the same address on all chains, including old ones. + +### StateTransitionManager was renamed to ChainTypeManager + +CTM was renamed to CTM (ChainTypeManager). This was done to use more intuitive naming as the chains of the same “type” share the same CTM. + +### Hyperchains were renamed to ZK chains + +For consistency with the naming inside the blogs, the term “hyperchain” has been changed to “ZK chain”. + +## Changes in the structure of contracts + +While fully reusing contracts on both L1 and L2 is not always possible, it was done to a very high degree as now all bridging-related contracts are located inside the `l1-contracts` folder. + +## Priority tree + +[Migrating Priority Queue to Merkle Tree](../../settlement_contracts/priority_queue/priority-queue.md) + +In the currently deployed system, L1→L2 transactions are added as a part of a priority queue, i.e. all of them are stored 1-by-1 on L1 in a queue-like structure. + +Note, that the complexity of chain migrations in either of the directions depends on the size of the priority queue. However, the number of unprocessed priority transactions is potentially out of hands of both the operator of the chain and the chain admin as the users are free to add priority transactions in case there is no `transactionFilterer` contract, which is the case for any permissionless system, such as ZKsync Era. + +If someone tries to DDoS the priority queue, the chain can be blocked from migration. Even worse, for GW→L1 migrations, inability to finalize the migration can lead to a complete loss of chain. + +To combat all the issues above, it was decided to move from the priority queue to a priority tree, i.e. only the incremental merkle tree is stored on L1, while at the end of the batch the operator will provide a merkle proof for the inclusion of the priority transactions that were present in the batch. It does not impact the bootloader, but rather only how the L1 checks that the priority transactions did indeed belong to the chain + +## Custom DA layers + +Custom DA layer support was added. + +### Major changes + +In order to achieve CAB, we separated the liquidity managing logic from the Shared Bridge to `Asset Handlers`. The basic cases will be handled by `Native Token Vaults`, which are handling all of the standard `ERC20 tokens`, as well as `ETH`. + +## L1<>L2 token bridging considerations + +- We have the L2SharedBridgeLegacy on chains that are live before the upgrade. This contract will keep on working, and where it exists it will also be used to: + - deploy bridged tokens. This is so that the l2TokenAddress keeps working on the L1, and so that we have a predictable address for these tokens. + - send messages to L1. On the L1 finalizeWithdrawal does not specify the l2Sender. Legacy withdrawals will use the legacy bridge as their sender, while new withdrawals would use the L2_ASSET_ROUTER_ADDR. In the future we will add the sender to the L1 finalizeWithdrawal interface. Until the current method is deprecated we use the l2SharedBridgeAddress even for new withdrawals on legacy chains. + This also means that on the L1 side we set the L2AR address when calling the function via the legacy interface even if it is a baseToken withdrawal. Later when we learn if it baseToken or not, we override the value. +- We have the finalizeWithdrawal function on L1 AR, which uses the finalizeDeposit in the background. +- L1→L2 deposits need to use the legacy encoding for SDK compatibility. + - This means the legacy finalizeDeposit with tokenAddress which calls the new finalizeDeposit with assetId. + - On the other hand, new assets will use the new finalizeDeposit directly +- The originChainId will be tracked for each assetId in the NTVs. This will be the chain where the token is originally native to. This is needed to accurately track chainBalance (especially for l2 native tokens bridged to other chains via L1), and to verify the assetId is indeed an NTV asset id (i.e. has the L2_NATIVE_TOKEN_VAULT_ADDR as deployment tracker). + +## Upgrade process in detail + +You can read more about the upgrade process itself [here](./upgrade_process.md). diff --git a/docs/upgrade_history/gateway_upgrade/upgrade_process.md b/docs/upgrade_history/gateway_upgrade/upgrade_process.md new file mode 100644 index 000000000..8a36cc4e5 --- /dev/null +++ b/docs/upgrade_history/gateway_upgrade/upgrade_process.md @@ -0,0 +1,216 @@ +# The upgrade process to the new version + +[back to readme](../../README.md) + +Gateway system introduces a lot of new contracts and so conducting so to provide the best experience for ZK chains the multistage upgrade will be provided. The upgrade will require some auxiliary contracts that will exist only for the purpose of this upgrade. + +## Previous version + +The previous version can be found [here](https://github.com/matter-labs/era-contracts/tree/release-v25-protocol-defense). + +The documentation for the previous version can be found [here](https://github.com/code-423n4/2024-03-zksync). + +However, deep knowledge of the previous version should not be required for understanding. But this document _does_ require understanding of the new system, so it should be the last document for you to read. + +## Overall design motivation + +During design of this upgrade we followed two principles: + +- Trust minimization. I.e. once the voting has started, no party can do damage to the upgrade or change its course. For instance, no one should be able to prevent a usable chain from conducting the upgrade to the gateway. +- Minimal required preparation for chains. All of the required contracts for the upgrade (e.g. rollup L2DA validator, etc) will be deployed during the upgrade automatically. This allows to minimize risks of mistakes for each individual chain. + +There are four roles that will be mentioned within this document: + +- “Governance” — trusted entity that embodies the whole [decentralized voting process for ZK chain ecosystem](https://blog.zknation.io/introducing-zk-nation/). +- “Ecosystem admin” — relatively trusted role for non-critical operation. It will be typically implemented as a multisig, that is approved by the governance and can only do limited operations to facilitate the upgrade. It can not alter the content of the upgrade nor it should be able to somehow harm chains by weaponizing the upgrade. +- “Chain admin” — an admin of a ZK chain. An entity with limited ability to govern their own chain (they can choose who are the validators of the chain, but can not change the general behavior of the their chain). +- “Deployer”. This role may not be mentioned, but it is implicitly present during the preparation stage. This is a hot wallet that is responsible for deploying the implementation of new contracts, etc. The governance should validate all its actions at the start of the voting process and so no trust is assumed from this wallet. + +## Ecosystem preparation stage + +This stage involves everything that is done before the voting starts. At this stage, all the details of the upgrade must be fixed, including the chain id of the gateway. + +More precisely, the implementations for the contracts will have to be deployed. Also, all of the new contracts will have to be deployed along with their proxies, e.g. `CTMDeploymentTracker`, `L1AssetRouter`, etc. + +Also, at this stage the bytecodes all L2 contracts have to be fixed, this includes bytecode for the things like `L2DAValidators`, `GatewayCTMDeployer`, etc. + +### Ensuring Governance ownership + +Some of the new contracts (e.g. `CTMDeploymentTracker` ) have two sorts of admins: the admin of the their proxy as well the `owner` role inside the contract. Both should belong to governance (the former is indirectly controlled by governance via a `ProxyAdmin` contract). + +The governance needs to know that it will definitely retain the ownership of these contracts regardless of the actions of their deployer. This are multiple ways this is ensured: + +- For `TransparentUpgradaeableProxy` this is simple: we can just transfer the ownership in one step to the `ProxyAdmin` that is under control of the governance. +- For contracts that are deployed as standalone contracts (not proxies), then if we possible we provide the address of the owner of in the constructor. +- For proxies and for contracts for which transferring inside the constructor is not option, we would transfer the ownership to a `TransitionaryOwner` contract. This is a contract that is responsible for being a temporary owner until the voting ends and it can do only two things: accept ownership for a contract and atomically transfer it to the governance. This is a workaround we have to use since most of our contracts implement `Ownable2Step` and so it is not possible to transfer ownership in one go. + +PS: It may be possible that for more contracts, e.g. some of the proxies we could’ve avoided the `TransitionaryOwner` approach by e.g. providing the governance address inside of an initializer. But we anyway need the `TransitionaryOwner` for `ValidatorTimelock`, so we decided to use it in most places to keep the code simpler. + +### L2SharedBridge and L2WETH migration + +In the current system (i.e. before the gateway upgrade), the trusted admin of the L1SharedBridge is responsible for [setting the correct L2SharedBridge address for chains](https://github.com/matter-labs/era-contracts/blob/aafee035db892689df3f7afe4b89fd6467a39313/l1-contracts/contracts/bridge/L1SharedBridge.sol#L249) (note that the links points to the old code and not the one in the scope of the contest). This is done with no additional validation. The system is generally designed to protect chains in case when a malicious admin tries to attack a chain. There are two measures to do that: + +- The general assumption is that the L2 shared bridge is set for a chain as soon as possible. It is a realistic assumption, since without it no bridging of any funds except for the base token is possible. So if at an early stage the admin would put a malicious l2 shared bridge for a chain, it would lose its trust from the community and the chain should be discarded. +- Admin can not retroactively change L2 shared bridge for any chains. So once the correct L2 shared bridge is set, there is no way a bad admin can harm the chain. + +The mapping for L2SharedBridge will be used as a source for the address of `L2SharedBridgeLegacy` contract address during the migration. + +To correctly initialize the `L2NativeTokenVault` inside the gateway upgrade, we will need the address of the L2 Wrapped Base Token contract [as well](https://github.com/matter-labs/era-contracts/blob/main/l2-contracts/contracts/bridge/L2WrappedBaseToken.sol) (note that the link is intentionally for the current codebase to show that these are deployed even before the upgrade). + +The data to execute the upgrade with is gathered on L1, so we need to create a mapping on L1 from `chainId => l2WrappedBaseToken`. This is what the `L2WrappedBaseTokenStore` contract for. + +Some chains already have `L2WrappedBaseToken` implementation deployed. It will be the job of the admin of the contract to prepopulate the contract with the correct addresses of those. The governance will have to double check that for the existing chains this mapping has been populated correctly before proceeding with the upgrade. + +Since we do not want to stop new chain creation while the voting is in progress, the admin needs to have the ability to add both new `L2SharedBridges` and the new `L2WrappedBaseToken` addresses to the mappings above. The following protections are put in place: + +- In case the trusted admin maliciously populated the addresses for any chains that were created before the voting started, the governance should just reject the voting +- In case the trusted admin maliciously populated the addresses for a chain after the voting has ended, the same assumptions as the ones described for L2SharedBridge apply, i.e. the chain should have its `L2SharedBridge` and `L2WrappedBaseToken` deployed asap after the creation of the chain, in case the admin did something malicious, they should immediately discard the chain to prevent loss of value. + +### Publishing bytecodes for everyone + +Before a contract can be deployed with a bytecode, it must be marked as “known”. This includes system contracts. This caused some inconveniences during previous upgrades: + +- For each chain we would have to publish all factory dependencies for the upgrade separately, making it expensive and risk-prone process. +- If a chain forgets to publish bytecodes for a chain before it executes an upgrade, there is little way to recover without intervention from the Governance. + +This upgrade the different approach is used to ensure safe and riskless preparation for the upgrade: + +- All bytecodes that are needed for this upgrade must be published to the `BytecodesSupplier` contract. +- The protocol upgrade transaction will have all the required dependencies in its factory deps. During the upgrade they will be marked as known automatically by the system. The operator of a chain needs to grab the preimages for those from events emitted by the `BytecodesSupplier`. +- It will be the job of the governance to verify that all the bytecodes were published to this contract. + +## Voting stage + +### Things to validate by the governance + +- The L1/L2 bytecodes are correct and the calldata is correct. +- That the correct L2SharedBridge are populated in L1SharedBridge (note that it is a legacy contract from the current system that becomes L1Nullifer in the new upgrade) and that L2WrappedBaseTokenStore has been populated correctly. +- [That the ownership is correctly transferred to governance.](#ensuring-governance-ownership) +- That the bytecodes were published correctly to the `BytecodeSupplier` contract. + +### Things to sign by the governance + +The governance should sign all operations that will happen in all of the consecutive stages at this time. There will be no other voting. Unless stated otherwise, all the governance operations in this document are listed as dependencies for one another, i.e. must be executed in strictly sequential order. + +Note, that to support “Stage 3” it would also need to finalize all the details for Gateway, including its chain id, chain admin, etc. + +## Stage 1. Publishing of the new protocol upgrade + +### Txs by governance (in one multicall) + +1. The governance accepts ownership for all the contracts that used `TransitionaryOwner`. +2. The governance publishes the new version by calling `function setNewVersionUpgrade`. +3. The governance calls `setChainCreationParams` and sets temporary incorrect values there that use a contract that always reverts as the `genesisUpgrade`, ensuring that no new chains can be created until Stage 2. +4. The governance should call the `GovernanceUpgradeTimer.startTimer()` to ensure that the timer for the upgrade starts. + +### Impact + +The chains will get the ability to upgrade to the new protocol version. They will be advised to do so before the deadline for upgrade runs out. + +Also, new chains wont be deployable during this stage due to step (3). + +Chains, whether upgraded or not, should work as usual as the new L2 bridging ecosystem is fully compatible with the old L1SharedBridge. + +Chains that upgrade need to carefully coordinate this upgrade on the server side, since validator timelock changes and also there is a need to keep track of the number of already existing priority ops that were not included into the priority tree. + +## Chain Upgrade flow + +Let’s take a deeper look at how upgrading of an individual chain would look like. + +### Actions by Chain Admins + +As usual, the ChainAdmin should call `upgradeChainFromVersion`. What is unusual however: + +- ValidatorTimelock changes and so the admin should call the new ValidatorTimelock to set the old validators there. +- The new DA validation mechanism is there and so the ChainAdmin should set the new DA validator pair. +- If a chain should be a permanent rollup, the ChainAdmin should call the `makePermanentRollup()` function. + +It is preferable that all the steps above are executed in a multicall for greater convenience, though it is not mandatory. + +This upgrade adds a lot of new chain parameters and so these [should be managed carefully](../../chain_management/admin_role.md). + +### Upgrade flow in contracts + +Usually, we would perform an upgrade by simply doing a list of force deployments: basically providing an array of the contracts to deploy for the system. This array would be constant for all chains and it would work fine. + +However in this upgrade we have an issue that some of the constructor parameters (e.g. the address of the `L2SharedBridgeLegacy`) are specific to each chain. Thus, besides the standard parts of the upgrades each chain also has `ZKChainSpecificForceDeploymentsData` populated. Some of the params to conduct those actions are constant and so populate the `FixedForceDeploymentsData` struct. + +If the above could be composed on L1 to still reuse the old list of `(address, bytecodeHash, constructorData)` list, there are also other rather complex actions such as upgrading the L2SharedBridge to the L2SharedBridgeLegacy implementation that require rather complex logic. + +Due to the complexity of the actions above, it was decided to put all those into the [L2GatewayUpgrade](../../../system-contracts/contracts/L2GatewayUpgrade.sol) contract. It is supposed to be force-deployed with the constructor parameters containing the `ZKChainSpecificForceDeploymentsData` as well as `FixedForceDeploymentsData`. It will be forcedeployed to the ComplexUpgrader’s address to get the kernel space rights. + +So most of the system contracts will be deployed the old way (via force deployment), but for more complex thing the `L2GatewayUpgrade` will be temporarily put onto `ComplexUpgrader` address and initialize additional contracts inside the constructor. Then the correct will be put back there. + +So entire flow can be summarized by the following: + +1. On L1, when `AdminFacet.upgradeChainFromVersion` is called by the Chain Admin, the contract delegatecalls to the [GatewayUpgrade](../../../l1-contracts/contracts/upgrades/GatewayUpgrade.sol) contract. +2. The `GatewayUpgrade` gathers all the needed data to compose the `ZKChainSpecificForceDeploymentsData`, while the `FixedForceDeploymentsData` is part is hardcoded inside the upgrade transaction. +3. The combined upgrade transaction consists of many forced deployments (basically tuples of `(address, bytecodeHash, constructorInput)`) and one of these that is responsible for the temporary `L2GatewayUpgrade` gets its `constructorInput` set to contain the `ZKChainSpecificForceDeploymentsData` / `FixedForceDeploymentsData`. +4. When the upgrade is executed on L2, it iterates over the forced deployments, deploys most of the contracts and then executes the `L2GatewayUpgrade`. +5. `L2GatewayUpgrade` will deploy the L2 Bridgehub, MessageRoot, L2NativeTokenVault, L2AssetRouters. It will also deploy l2WrappedBaseToken if missing. It will also upgrade the implementations the L2SharedBridge as well as the UpgradaeableBeacon for these tokens. + +## Stage 2. Finalization of the upgrade + +### Txs by governance (in one multicall) + +- call the `GovernanceUpgradeTimer` to check whether the deadline has passed as only after that the upgrade can be finalized. +- set the protocol version deadline for the old version to 0, i.e. ensuring that all the contracts with the old version wont be able to commit any new batches. +- upgrade the old contracts to the new implementation. +- set the correct new chain creation params, upgrade the old contracts to the new one + +### Txs by anyone + +After the governance has finalized the upgrade above, anyone can do the following transactions to finalize the upgrade: + +For each chainId: + +- `Bridgehub.setLegacyBaseTokenAssetId` +- `Bridgehub.setLegacyChainAddress` + +For each token: + +- register token inside the L1NTV + +For each chain/token pair: + +- update chain balances from shared bridge for L1NTV + +The exact way these functions will be executed is out of scope of this document. It can be done via a trivial multicall. + +### Impact + +The ecosystem has been fully transformed to the new version. However, the gateway chain is not yet ready. + +All the chains should start returning the address of the `L1AssetRouter` as the address of the L1SharedBridge in the API. + +## Stage 3. Deploying of Gateway + +### Txs by governance (sequentially, potentially different txs) + +1. Call `Bridgehub.createNewChain` with the data for gateway. +2. It will have to register it via `bridgehub.registerSettlementLayer` +3. It will have to do the L1→L2 transactions to register the CTM on Gateway as the valid CTM inside the L2Bridgehub as well as to set the CTM inside Gateway as the asset handler for the chains. + +Note, that steps (2) and (3) can be executed before this CTM has been ever deployed. These are expected to be deployed via [c](../../../l1-contracts/contracts/state-transition/chain-deps/GatewayCTMDeployer.sol) that itself should be deployed deployed via Create2Factory. So the address of the CTM can be precomputed. + +In case anyone will try to migrate their chain on top of gateway while CTM is not yet deployed, the migration will fail due to the calls to this CTM failing (standard Solidity checks for non-empty code size when doing high level calls). + +### Txs by anyone + +Anyone with funds on Gateway can deploy the `GatewayCTMDeployer` and it will deploy inside its constructor the CTM described from above. + +It can not be done as part of the governance transactions from above since it requires pre-publishing CTM-specific bytecodes. + +## Security notes + +### Importance of preventing new batches being committed with the old version + +The new `L1AssetRouter` is not compatible with chains that do not support the new protocol version as they do not have `L2AssetRouter` deployed. Doing bridging to such new chains will lead to funds being lost without recovery (since formally the L1->L2 transaction won't fail as it is just a call to an empty address). + +This is why it is crucial that on step (2) we revoke the ability for outdated chains to push new batches as those might've been spawned using the `L1AssetRouter`. + +### Impact of malicious ecosystem admin + +In theory, the ecosystem admin can front-run this deployment and set potentially bad values for the Gateway chain. It will just mean that the first transaction will fail. Due to sequential dependencies between txs, the rest won’t be executed and so the malicious chain wont be whitelisted as the settlement layer. + +While unlikely, in this case the Governance will have to re-do the voting for the gateway chain, including voting to remove the admin rights from the malicious admin. diff --git a/l1-contracts/.env b/l1-contracts/.env index 0cbe2dbd1..4f40c9e49 100644 --- a/l1-contracts/.env +++ b/l1-contracts/.env @@ -39,8 +39,12 @@ ETH_SENDER_SENDER_OPERATOR_BLOBS_ETH_ADDR=0x000000000000000000000000000000000000 CONTRACTS_SHARED_BRIDGE_UPGRADE_STORAGE_SWITCH=0 CONTRACTS_MAX_NUMBER_OF_ZK_CHAINS=100 L1_CONFIG=/script-config/config-deploy-l1.toml +L2_CONFIG=/script-config/config-deploy-l2-contracts.toml L1_OUTPUT=/script-out/output-deploy-l1.toml +L2_CONFIG=/script-config/config-deploy-l2-contracts.toml TOKENS_CONFIG=/script-config/config-deploy-erc20.toml +ZK_TOKEN_CONFIG=/script-config/config-deploy-zk.toml +ZK_TOKEN_OUTPUT=/script-out/output-deploy-zk-token.toml ZK_CHAIN_CONFIG=/script-config/register-zk-chain.toml ZK_CHAIN_OUTPUT=/script-out/output-deploy-zk-chain-era.toml FORCE_DEPLOYMENTS_CONFIG=/script-config/generate-force-deployments-data.toml diff --git a/l1-contracts/contracts/bridge/BridgeHelper.sol b/l1-contracts/contracts/bridge/BridgeHelper.sol index bcc59327f..b989084a9 100644 --- a/l1-contracts/contracts/bridge/BridgeHelper.sol +++ b/l1-contracts/contracts/bridge/BridgeHelper.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors - import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; import {ETH_TOKEN_ADDRESS} from "../common/Config.sol"; import {DataEncoding} from "../common/libraries/DataEncoding.sol"; @@ -11,7 +9,7 @@ import {DataEncoding} from "../common/libraries/DataEncoding.sol"; /** * @author Matter Labs * @custom:security-contact security@matterlabs.dev - * @notice Helper library for working with L2 contracts on L1. + * @notice Helper library for working with native tokens on both L1 and L2. */ library BridgeHelper { /// @dev Receives and parses (name, symbol, decimals) from the token contract diff --git a/l1-contracts/contracts/bridge/BridgedStandardERC20.sol b/l1-contracts/contracts/bridge/BridgedStandardERC20.sol index d848dcbac..4d5a82566 100644 --- a/l1-contracts/contracts/bridge/BridgedStandardERC20.sol +++ b/l1-contracts/contracts/bridge/BridgedStandardERC20.sol @@ -86,11 +86,7 @@ contract BridgedStandardERC20 is ERC20PermitUpgradeable, IBridgedStandardToken, /// @param _originToken Address of the origin token that can be deposited to mint this bridged token /// @param _data The additional data that the L1 bridge provide for initialization. /// In this case, it is packed `name`/`symbol`/`decimals` of the L1 token. - function bridgeInitialize( - bytes32 _assetId, - address _originToken, - bytes calldata _data - ) external initializer returns (uint256) { + function bridgeInitialize(bytes32 _assetId, address _originToken, bytes calldata _data) external initializer { if (_originToken == address(0)) { revert ZeroAddress(); } @@ -99,9 +95,12 @@ contract BridgedStandardERC20 is ERC20PermitUpgradeable, IBridgedStandardToken, nativeTokenVault = msg.sender; + bytes memory nameBytes; + bytes memory symbolBytes; + bytes memory decimalsBytes; // We parse the data exactly as they were created on the L1 bridge - (uint256 chainId, bytes memory nameBytes, bytes memory symbolBytes, bytes memory decimalsBytes) = DataEncoding - .decodeTokenData(_data); + // slither-disable-next-line unused-return + (, nameBytes, symbolBytes, decimalsBytes) = DataEncoding.decodeTokenData(_data); ERC20Getters memory getters; string memory decodedName; @@ -143,7 +142,6 @@ contract BridgedStandardERC20 is ERC20PermitUpgradeable, IBridgedStandardToken, availableGetters = getters; emit BridgeInitialize(_originToken, decodedName, decodedSymbol, decimals_); - return chainId; } /// @notice A method to be called by the governor to update the token's metadata. diff --git a/l1-contracts/contracts/bridge/L1BridgeContractErrors.sol b/l1-contracts/contracts/bridge/L1BridgeContractErrors.sol new file mode 100644 index 000000000..d72cf85a2 --- /dev/null +++ b/l1-contracts/contracts/bridge/L1BridgeContractErrors.sol @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.21; + +// 0x6d963f88 +error EthTransferFailed(); + +// 0x1c55230b +error NativeTokenVaultAlreadySet(); + +// 0x61cdb17e +error WrongMsgLength(uint256 expected, uint256 length); + +// 0xe4742c42 +error ZeroAmountToTransfer(); + +// 0xfeda3bf8 +error WrongAmountTransferred(uint256 balance, uint256 nullifierChainBalance); + +// 0x066f53b1 +error EmptyToken(); + +// 0x0fef9068 +error ClaimFailedDepositFailed(); + +// 0x636c90db +error WrongL2Sender(address providedL2Sender); + +// 0xb4aeddbc +error WrongCounterpart(); diff --git a/l1-contracts/contracts/bridge/L1ERC20Bridge.sol b/l1-contracts/contracts/bridge/L1ERC20Bridge.sol index 0cd72ccc7..190c086b4 100644 --- a/l1-contracts/contracts/bridge/L1ERC20Bridge.sol +++ b/l1-contracts/contracts/bridge/L1ERC20Bridge.sol @@ -13,7 +13,7 @@ import {IL1AssetRouter} from "./asset-router/IL1AssetRouter.sol"; import {L2ContractHelper} from "../common/libraries/L2ContractHelper.sol"; import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; -import {EmptyDeposit, WithdrawalAlreadyFinalized, TokensWithFeesNotSupported, ETHDepositNotSupported} from "../common/L1ContractErrors.sol"; +import {EmptyDeposit, WithdrawalAlreadyFinalized, TokensWithFeesNotSupported, ETHDepositNotSupported, ApprovalFailed} from "../common/L1ContractErrors.sol"; import {ETH_TOKEN_ADDRESS} from "../common/Config.sol"; /// @author Matter Labs @@ -188,7 +188,7 @@ contract L1ERC20Bridge is IL1ERC20Bridge, ReentrancyGuard { if (_l1Token == ETH_TOKEN_ADDRESS) { revert ETHDepositNotSupported(); } - uint256 amount = _depositFundsToAssetRouter(msg.sender, IERC20(_l1Token), _amount); + uint256 amount = _approveFundsToAssetRouter(msg.sender, IERC20(_l1Token), _amount); if (amount != _amount) { // The token has non-standard transfer logic revert TokensWithFeesNotSupported(); @@ -203,6 +203,11 @@ contract L1ERC20Bridge is IL1ERC20Bridge, ReentrancyGuard { _l2TxGasPerPubdataByte: _l2TxGasPerPubdataByte, _refundRecipient: _refundRecipient }); + // clearing approval + bool success = IERC20(_l1Token).approve(address(L1_ASSET_ROUTER), 0); + if (!success) { + revert ApprovalFailed(); + } depositAmount[msg.sender][_l1Token][l2TxHash] = _amount; emit DepositInitiated({ l2DepositTxHash: l2TxHash, @@ -219,10 +224,14 @@ contract L1ERC20Bridge is IL1ERC20Bridge, ReentrancyGuard { /// @dev Transfers tokens from the depositor address to the native token vault address. /// @return The difference between the contract balance before and after the transferring of funds. - function _depositFundsToAssetRouter(address _from, IERC20 _token, uint256 _amount) internal returns (uint256) { - uint256 balanceBefore = _token.balanceOf(address(L1_ASSET_ROUTER)); - _token.safeTransferFrom(_from, address(L1_ASSET_ROUTER), _amount); - uint256 balanceAfter = _token.balanceOf(address(L1_ASSET_ROUTER)); + function _approveFundsToAssetRouter(address _from, IERC20 _token, uint256 _amount) internal returns (uint256) { + uint256 balanceBefore = _token.balanceOf(address(this)); + _token.safeTransferFrom(_from, address(this), _amount); + bool success = _token.approve(address(L1_ASSET_ROUTER), _amount); + if (!success) { + revert ApprovalFailed(); + } + uint256 balanceAfter = _token.balanceOf(address(this)); return balanceAfter - balanceBefore; } diff --git a/l1-contracts/contracts/bridge/L1Nullifier.sol b/l1-contracts/contracts/bridge/L1Nullifier.sol index 6e624d723..7be97e544 100644 --- a/l1-contracts/contracts/bridge/L1Nullifier.sol +++ b/l1-contracts/contracts/bridge/L1Nullifier.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/security/PausableUpgradeable.sol"; @@ -31,6 +29,7 @@ import {IBridgehub} from "../bridgehub/IBridgehub.sol"; import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR} from "../common/L2ContractAddresses.sol"; import {DataEncoding} from "../common/libraries/DataEncoding.sol"; import {Unauthorized, SharedBridgeKey, DepositExists, AddressAlreadySet, InvalidProof, DepositDoesNotExist, SharedBridgeValueNotSet, WithdrawalAlreadyFinalized, L2WithdrawalMessageWrongLength, InvalidSelector, SharedBridgeValueNotSet, ZeroAddress} from "../common/L1ContractErrors.sol"; +import {WrongL2Sender, NativeTokenVaultAlreadySet, EthTransferFailed, WrongMsgLength} from "./L1BridgeContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -127,14 +126,6 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, _; } - /// @notice Checks that the message sender is the bridgehub or ZKsync Era Diamond Proxy. - modifier onlyBridgehubOrEra(uint256 _chainId) { - if (msg.sender != address(BRIDGE_HUB) && (_chainId != ERA_CHAIN_ID || msg.sender != ERA_DIAMOND_PROXY)) { - revert Unauthorized(msg.sender); - } - _; - } - /// @notice Checks that the message sender is the legacy bridge. modifier onlyLegacyBridge() { if (msg.sender != address(legacyBridge)) { @@ -143,14 +134,6 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, _; } - /// @notice Checks that the message sender is the legacy bridge. - modifier onlyAssetRouterOrErc20Bridge() { - if (msg.sender != address(l1AssetRouter) && msg.sender != address(legacyBridge)) { - revert Unauthorized(msg.sender); - } - _; - } - /// @dev Contract is expected to be used as proxy implementation. /// @dev Initialize the implementation to prevent Parity hack. constructor(IBridgehub _bridgehub, uint256 _eraChainId, address _eraDiamondProxy) reentrancyGuardInitializer { @@ -199,7 +182,9 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, assembly { callSuccess := call(gas(), ntvAddress, amount, 0, 0, 0, 0) } - require(callSuccess, "L1N: eth transfer failed"); + if (!callSuccess) { + revert EthTransferFailed(); + } } else { IERC20(_token).safeTransfer(ntvAddress, IERC20(_token).balanceOf(address(this))); } @@ -209,8 +194,7 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, /// @dev This function is part of the upgrade process used to nullify chain balances once they are credited to NTV. /// @param _chainId The ID of the ZK chain. /// @param _token The address of the token which was previously deposit to shared bridge. - function nullifyChainBalanceByNTV(uint256 _chainId, address _token) external { - require(msg.sender == address(l1NativeTokenVault), "L1N: not NTV"); + function nullifyChainBalanceByNTV(uint256 _chainId, address _token) external onlyL1NTV { __DEPRECATED_chainBalance[_chainId][_token] = 0; } @@ -248,8 +232,12 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, /// @dev Should be called only once by the owner. /// @param _l1NativeTokenVault The address of the native token vault. function setL1NativeTokenVault(IL1NativeTokenVault _l1NativeTokenVault) external onlyOwner { - require(address(l1NativeTokenVault) == address(0), "L1N: native token vault already set"); - require(address(_l1NativeTokenVault) != address(0), "L1N: native token vault 0"); + if (address(l1NativeTokenVault) != address(0)) { + revert NativeTokenVaultAlreadySet(); + } + if (address(_l1NativeTokenVault) == address(0)) { + revert ZeroAddress(); + } l1NativeTokenVault = _l1NativeTokenVault; } @@ -260,7 +248,9 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, if (address(l1AssetRouter) != address(0)) { revert AddressAlreadySet(address(_l1AssetRouter)); } - require(_l1AssetRouter != address(0), "ShB: nullifier 0"); + if (_l1AssetRouter == address(0)) { + revert ZeroAddress(); + } l1AssetRouter = IL1AssetRouter(_l1AssetRouter); } @@ -281,7 +271,7 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, emit BridgehubDepositFinalized(_chainId, _txDataHash, _txHash); } - /// @dev Calls the internal `_encodeTxDataHash`. Used as a wrapped for try / catch case. + /// @dev Calls the library `encodeTxDataHash`. Used as a wrapped for try / catch case. /// @dev Encodes the transaction data hash using either the latest encoding standard or the legacy standard. /// @param _encodingVersion EncodingVersion. /// @param _originalCaller The address of the entity that initiated the deposit. @@ -405,14 +395,14 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, /// @param _finalizeWithdrawalParams The structure that holds all necessary data to finalize withdrawal /// @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(FinalizeL1DepositParams calldata _finalizeWithdrawalParams) external { + function finalizeDeposit(FinalizeL1DepositParams memory _finalizeWithdrawalParams) public { _finalizeDeposit(_finalizeWithdrawalParams); } /// @notice Internal function that handles the logic for finalizing withdrawals, supporting both the current bridge system and the legacy ERC20 bridge. /// @param _finalizeWithdrawalParams The structure that holds all necessary data to finalize withdrawal function _finalizeDeposit( - FinalizeL1DepositParams calldata _finalizeWithdrawalParams + FinalizeL1DepositParams memory _finalizeWithdrawalParams ) internal nonReentrant whenNotPaused { uint256 chainId = _finalizeWithdrawalParams.chainId; uint256 l2BatchNumber = _finalizeWithdrawalParams.l2BatchNumber; @@ -422,17 +412,20 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, } isWithdrawalFinalized[chainId][l2BatchNumber][l2MessageIndex] = true; - // Handling special case for withdrawal from ZKsync Era initiated before Shared Bridge. (bytes32 assetId, bytes memory transferData) = _verifyWithdrawal(_finalizeWithdrawalParams); - // Handling special case for withdrawal from zkSync Era initiated before Shared Bridge. + // Handling special case for withdrawal from ZKsync Era initiated before Shared Bridge. if (_isPreSharedBridgeEraEthWithdrawal(chainId, l2BatchNumber)) { // Checks that the withdrawal wasn't finalized already. bool alreadyFinalized = IGetters(ERA_DIAMOND_PROXY).isEthWithdrawalFinalized(l2BatchNumber, l2MessageIndex); - require(!alreadyFinalized, "L1N: Withdrawal is already finalized 2"); + if (alreadyFinalized) { + revert WithdrawalAlreadyFinalized(); + } } if (_isPreSharedBridgeEraTokenWithdrawal(chainId, l2BatchNumber)) { - require(!legacyBridge.isWithdrawalFinalized(l2BatchNumber, l2MessageIndex), "L1N: legacy withdrawal"); + if (legacyBridge.isWithdrawalFinalized(l2BatchNumber, l2MessageIndex)) { + revert WithdrawalAlreadyFinalized(); + } } l1AssetRouter.finalizeDeposit(chainId, assetId, transferData); @@ -509,7 +502,7 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, /// @return assetId The ID of the bridged asset. /// @return transferData The transfer data used to finalize withdawal. function _verifyWithdrawal( - FinalizeL1DepositParams calldata _finalizeWithdrawalParams + FinalizeL1DepositParams memory _finalizeWithdrawalParams ) internal returns (bytes32 assetId, bytes memory transferData) { (assetId, transferData) = _parseL2WithdrawalMessage( _finalizeWithdrawalParams.chainId, @@ -519,15 +512,13 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, { address l2Sender = _finalizeWithdrawalParams.l2Sender; bool baseTokenWithdrawal = (assetId == BRIDGE_HUB.baseTokenAssetId(_finalizeWithdrawalParams.chainId)); - require( - /// @dev for legacy function calls we hardcode the sender as the L2AssetRouter as we don't know if it is - /// a base token or erc20 token withdrawal beforehand, - /// so we have to allow that option even if we override it. - l2Sender == L2_ASSET_ROUTER_ADDR || - l2Sender == L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR || - l2Sender == __DEPRECATED_l2BridgeAddress[_finalizeWithdrawalParams.chainId], - "L1N: wrong l2 sender" - ); + + bool isL2SenderCorrect = l2Sender == L2_ASSET_ROUTER_ADDR || + l2Sender == L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR || + l2Sender == __DEPRECATED_l2BridgeAddress[_finalizeWithdrawalParams.chainId]; + if (!isL2SenderCorrect) { + revert WrongL2Sender(l2Sender); + } l2ToL1Message = L2Message({ txNumberInBatch: _finalizeWithdrawalParams.l2TxNumberInBatch, @@ -582,8 +573,8 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, address baseToken = BRIDGE_HUB.baseToken(_chainId); transferData = DataEncoding.encodeBridgeMintData({ _originalCaller: address(0), - _l2Receiver: l1Receiver, - _l1Token: baseToken, + _remoteReceiver: l1Receiver, + _originToken: baseToken, _amount: amount, _erc20Metadata: new bytes(0) }); @@ -607,14 +598,16 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, assetId = DataEncoding.encodeNTVAssetId(block.chainid, l1Token); transferData = DataEncoding.encodeBridgeMintData({ _originalCaller: address(0), - _l2Receiver: l1Receiver, - _l1Token: l1Token, + _remoteReceiver: l1Receiver, + _originToken: l1Token, _amount: amount, _erc20Metadata: new bytes(0) }); } else if (bytes4(functionSignature) == IAssetRouterBase.finalizeDeposit.selector) { // The data is expected to be at least 36 bytes long to contain assetId. - require(_l2ToL1message.length >= 36, "L1N: wrong msg len"); // wrong message length + if (_l2ToL1message.length < 36) { + revert WrongMsgLength(36, _l2ToL1message.length); + } // slither-disable-next-line unused-return (, offset) = UnsafeBytes.readUint256(_l2ToL1message, offset); // originChainId, not used for L2->L1 txs (assetId, offset) = UnsafeBytes.readBytes32(_l2ToL1message, offset); @@ -741,4 +734,42 @@ contract L1Nullifier is IL1Nullifier, ReentrancyGuard, Ownable2StepUpgradeable, function unpause() external onlyOwner { _unpause(); } + + /*////////////////////////////////////////////////////////////// + LEGACY INTERFACE + //////////////////////////////////////////////////////////////*/ + + /// @notice Legacy function to finalize withdrawal via the same + /// interface as the old L1SharedBridge. + /// @dev Note, that we need to keep this interface, since the `L2AssetRouter` + /// will continue returning the previous address as the `l1SharedBridge`. The value + /// returned by it is used in the SDK for finalizing withdrawals. + /// @param _chainId The chain ID of the transaction to check + /// @param _l2BatchNumber The L2 batch number where the withdrawal was processed + /// @param _l2MessageIndex The position in the L2 logs Merkle tree of the l2Log that was sent with the message + /// @param _l2TxNumberInBatch The L2 transaction number in the batch, in which the log was sent + /// @param _message The L2 withdraw data, stored in an L2 -> L1 message + /// @param _merkleProof The Merkle proof of the inclusion L2 -> L1 message about withdrawal initialization + function finalizeWithdrawal( + uint256 _chainId, + uint256 _l2BatchNumber, + uint256 _l2MessageIndex, + uint16 _l2TxNumberInBatch, + bytes calldata _message, + bytes32[] calldata _merkleProof + ) external override { + /// @dev We use a deprecated field to support L2->L1 legacy withdrawals, which were started + /// by the legacy bridge. + address legacyL2Bridge = __DEPRECATED_l2BridgeAddress[_chainId]; + FinalizeL1DepositParams memory finalizeWithdrawalParams = FinalizeL1DepositParams({ + chainId: _chainId, + l2BatchNumber: _l2BatchNumber, + l2MessageIndex: _l2MessageIndex, + l2Sender: legacyL2Bridge == address(0) ? L2_ASSET_ROUTER_ADDR : legacyL2Bridge, + l2TxNumberInBatch: _l2TxNumberInBatch, + message: _message, + merkleProof: _merkleProof + }); + finalizeDeposit(finalizeWithdrawalParams); + } } diff --git a/l1-contracts/contracts/bridge/L2SharedBridgeLegacy.sol b/l1-contracts/contracts/bridge/L2SharedBridgeLegacy.sol index 4ae901593..b7c762b71 100644 --- a/l1-contracts/contracts/bridge/L2SharedBridgeLegacy.sol +++ b/l1-contracts/contracts/bridge/L2SharedBridgeLegacy.sol @@ -7,7 +7,7 @@ import {UpgradeableBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/Upgrade import {BridgedStandardERC20} from "./BridgedStandardERC20.sol"; -import {DEPLOYER_SYSTEM_CONTRACT, L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR} from "../common/L2ContractAddresses.sol"; +import {L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR} from "../common/L2ContractAddresses.sol"; import {SystemContractsCaller} from "../common/libraries/SystemContractsCaller.sol"; import {L2ContractHelper, IContractDeployer} from "../common/libraries/L2ContractHelper.sol"; import {AddressAliasHelper} from "../vendor/AddressAliasHelper.sol"; @@ -175,7 +175,7 @@ contract L2SharedBridgeLegacy is IL2SharedBridgeLegacy, Initializable { function deployBeaconProxy(bytes32 salt) external onlyNTV returns (address proxy) { (bool success, bytes memory returndata) = SystemContractsCaller.systemCallWithReturndata( uint32(gasleft()), - DEPLOYER_SYSTEM_CONTRACT, + L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, 0, abi.encodeCall( IContractDeployer.create2, diff --git a/l1-contracts/contracts/bridge/L2WrappedBaseToken.sol b/l1-contracts/contracts/bridge/L2WrappedBaseToken.sol index 1c430cacd..7af311edf 100644 --- a/l1-contracts/contracts/bridge/L2WrappedBaseToken.sol +++ b/l1-contracts/contracts/bridge/L2WrappedBaseToken.sol @@ -62,13 +62,13 @@ contract L2WrappedBaseToken is ERC20PermitUpgradeable, IL2WrappedBaseToken, IBri /// @param _l2Bridge Address of the L2 bridge /// @param _l1Address Address of the L1 token that can be deposited to mint this L2 WETH. /// Note: The decimals are hardcoded to 18, the same as on Ether. - function initializeV2( + function initializeV3( string calldata name_, string calldata symbol_, address _l2Bridge, address _l1Address, bytes32 _baseTokenAssetId - ) external reinitializer(2) { + ) external reinitializer(3) { if (_l2Bridge == address(0)) { revert ZeroAddress(); } diff --git a/l1-contracts/contracts/bridge/L2WrappedBaseTokenStore.sol b/l1-contracts/contracts/bridge/L2WrappedBaseTokenStore.sol new file mode 100644 index 000000000..06e7a9769 --- /dev/null +++ b/l1-contracts/contracts/bridge/L2WrappedBaseTokenStore.sol @@ -0,0 +1,126 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import {Ownable2Step} from "@openzeppelin/contracts-v4/access/Ownable2Step.sol"; + +import {ZeroAddress, Unauthorized} from "../common/L1ContractErrors.sol"; + +/// @title L2WrappedBaseTokenStore +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice This contract is used as a store for L2 deployments of L2WrappedBaseToken for chains that have it. +/// These values will be stored in the corresponding chain's L2NativeTokenVault upon migration to the new version, +/// so these values being correct is crucial. The following upgrade process is expected for this contract: +/// - It will be populated for the existing chains before the governance reviews the values. +/// - Each new chain (before the new protocol version is available) will have to double check that the admin +/// has set the correct value in this contract. If the admin did not set a correct value, the chain should be discarded. +/// - Once the upgrade is done, this contract will no longer be needed. Even though it is unlikely for a chain to be corrupted, +/// the governance can fix any corrupted chains in the next upgrade. +/// @dev This contract is not expected to be deployed as a proxy, but rather a standalone contract. +/// @dev The `admin` of this contract is expected to be some cold wallet, trusted to provide correct values. However, +/// due to process above, even its malicious behavior should not impact security of the ecosystem. +/// @dev The `owner` of this contract is trusted decentralized governance. +contract L2WrappedBaseTokenStore is Ownable2Step { + /// @notice Mapping from chain ID to L2 wrapped base token address. + mapping(uint256 chainId => address l2WBaseTokenAddress) public l2WBaseTokenAddress; + + /// @notice Admin address who has the right to register weth token deployment for a chain. + address public admin; + + /// @notice used to accept the admin role + address public pendingAdmin; + + /// @notice Admin changed + event NewAdmin(address indexed oldAdmin, address indexed newAdmin); + + /// @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 Emitted when the L2 wrapped base token address is set for a chain + /// @param chainId The id of the chain. + /// @param l2WBaseTokenAddress The L2 wrapped base token address. + event NewWBaseTokenAddress(uint256 indexed chainId, address indexed l2WBaseTokenAddress); + + /// @notice Sets the initial owner and admin. + /// @param _initialOwner The initial owner. + /// @param _admin The address of the admin. + constructor(address _initialOwner, address _admin) { + if (_admin == address(0) || _initialOwner == address(0)) { + revert ZeroAddress(); + } + admin = _admin; + _transferOwnership(_initialOwner); + } + + /// @notice Throws if called by any account other than the owner or admin. + modifier onlyOwnerOrAdmin() { + if (msg.sender != owner() && msg.sender != admin) { + revert Unauthorized(msg.sender); + } + _; + } + + /// @notice Initializes the L2 WBaseToken address for a specific chain ID. + /// @dev Can be called by the owner or the admin. + /// @param _chainId The ID of the blockchain network. + /// @param _l2WBaseToken The address of the L2 WBaseToken token. + function initializeChain(uint256 _chainId, address _l2WBaseToken) external onlyOwnerOrAdmin { + if (_l2WBaseToken == address(0)) { + revert ZeroAddress(); + } + _setWBaseTokenAddress(_chainId, _l2WBaseToken); + } + + /// @notice Reinitializes the L2 WBaseToken address for a specific chain ID. + /// @dev Can only be called by the owner. It can not be called by the admin second time + /// to prevent retroactively damaging existing chains. + /// @param _chainId The ID of the blockchain network. + /// @param _l2WBaseToken The new address of the L2 WBaseToken token. + function reinitializeChain(uint256 _chainId, address _l2WBaseToken) external onlyOwner { + if (_l2WBaseToken == address(0)) { + revert ZeroAddress(); + } + _setWBaseTokenAddress(_chainId, _l2WBaseToken); + } + + /// @notice Sets the address of the L2 wrapped base token deployment for a chain. + /// @param _chainId The ID of the blockchain network. + /// @param _l2WBaseToken The new address of the L2 WBaseToken token. + function _setWBaseTokenAddress(uint256 _chainId, address _l2WBaseToken) internal { + l2WBaseTokenAddress[_chainId] = _l2WBaseToken; + emit NewWBaseTokenAddress(_chainId, _l2WBaseToken); + } + + /// @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 + /// @dev Please note, if the owner wants to enforce the admin change it must execute both `setPendingAdmin` and + /// `acceptAdmin` atomically. Otherwise `admin` can set different pending admin and so fail to accept the admin rights. + function setPendingAdmin(address _newPendingAdmin) external onlyOwnerOrAdmin { + if (_newPendingAdmin == address(0)) { + revert ZeroAddress(); + } + // Save previous value into the stack to put it into the event later + address oldPendingAdmin = pendingAdmin; + // Change pending admin + pendingAdmin = _newPendingAdmin; + emit NewPendingAdmin(oldPendingAdmin, _newPendingAdmin); + } + + /// @notice Accepts transfer of admin rights. Only pending admin can accept the role. + function acceptAdmin() external { + address currentPendingAdmin = pendingAdmin; + // Only proposed by current admin address can claim the admin rights + if (msg.sender != currentPendingAdmin) { + revert Unauthorized(msg.sender); + } + + address previousAdmin = admin; + admin = currentPendingAdmin; + delete pendingAdmin; + + emit NewPendingAdmin(currentPendingAdmin, address(0)); + emit NewAdmin(previousAdmin, currentPendingAdmin); + } +} diff --git a/l1-contracts/contracts/bridge/asset-router/AssetRouterBase.sol b/l1-contracts/contracts/bridge/asset-router/AssetRouterBase.sol index d6ca41bdf..b315a3c64 100644 --- a/l1-contracts/contracts/bridge/asset-router/AssetRouterBase.sol +++ b/l1-contracts/contracts/bridge/asset-router/AssetRouterBase.sol @@ -109,7 +109,7 @@ abstract contract AssetRouterBase is IAssetRouterBase, Ownable2StepUpgradeable, IAssetHandler(assetHandler).bridgeMint(_chainId, _assetId, _transferData); } else { assetHandlerAddress[_assetId] = _nativeTokenVault; - IAssetHandler(_nativeTokenVault).bridgeMint(_chainId, _assetId, _transferData); // ToDo: Maybe it's better to receive amount and receiver here? transferData may have different encoding + IAssetHandler(_nativeTokenVault).bridgeMint(_chainId, _assetId, _transferData); } } diff --git a/l1-contracts/contracts/bridge/asset-router/IAssetRouterBase.sol b/l1-contracts/contracts/bridge/asset-router/IAssetRouterBase.sol index a307ba526..2f5ba8954 100644 --- a/l1-contracts/contracts/bridge/asset-router/IAssetRouterBase.sol +++ b/l1-contracts/contracts/bridge/asset-router/IAssetRouterBase.sol @@ -32,13 +32,6 @@ interface IAssetRouterBase { bytes bridgeMintCalldata ); - event BridgehubWithdrawalInitiated( - uint256 chainId, - address indexed sender, - bytes32 indexed assetId, - bytes32 assetDataHash // Todo: What's the point of emitting hash? - ); - event AssetHandlerRegisteredInitial( bytes32 indexed assetId, address indexed assetHandlerAddress, diff --git a/l1-contracts/contracts/bridge/asset-router/IL2AssetRouter.sol b/l1-contracts/contracts/bridge/asset-router/IL2AssetRouter.sol index 81b1bc995..32f93070b 100644 --- a/l1-contracts/contracts/bridge/asset-router/IL2AssetRouter.sol +++ b/l1-contracts/contracts/bridge/asset-router/IL2AssetRouter.sol @@ -16,7 +16,7 @@ interface IL2AssetRouter is IAssetRouterBase { function withdraw(bytes32 _assetId, bytes calldata _transferData) external returns (bytes32); - function l1AssetRouter() external view returns (address); + function L1_ASSET_ROUTER() external view returns (address); function withdrawLegacyBridge(address _l1Receiver, address _l2Token, uint256 _amount, address _sender) external; @@ -28,7 +28,7 @@ interface IL2AssetRouter is IAssetRouterBase { bytes calldata _data ) external; - /// @dev Used to set the assedAddress for a given assetId. + /// @dev Used to set the assetHandlerAddress for a given assetId. /// @dev Will be used by ZK Gateway function setAssetHandlerAddress(uint256 _originChainId, bytes32 _assetId, address _assetAddress) external; } diff --git a/l1-contracts/contracts/bridge/asset-router/L1AssetRouter.sol b/l1-contracts/contracts/bridge/asset-router/L1AssetRouter.sol index ff94d0db5..cf2ab966c 100644 --- a/l1-contracts/contracts/bridge/asset-router/L1AssetRouter.sol +++ b/l1-contracts/contracts/bridge/asset-router/L1AssetRouter.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {IERC20} from "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol"; @@ -15,7 +13,7 @@ import {AssetRouterBase} from "./AssetRouterBase.sol"; import {IL1AssetHandler} from "../interfaces/IL1AssetHandler.sol"; import {IL1ERC20Bridge} from "../interfaces/IL1ERC20Bridge.sol"; import {IAssetHandler} from "../interfaces/IAssetHandler.sol"; -import {IL1Nullifier, FinalizeL1DepositParams} from "../interfaces/IL1Nullifier.sol"; +import {IL1Nullifier} from "../interfaces/IL1Nullifier.sol"; import {INativeTokenVault} from "../ntv/INativeTokenVault.sol"; import {IL2SharedBridgeLegacyFunctions} from "../interfaces/IL2SharedBridgeLegacyFunctions.sol"; @@ -24,6 +22,7 @@ import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; import {AddressAliasHelper} from "../../vendor/AddressAliasHelper.sol"; import {TWO_BRIDGES_MAGIC_VALUE, ETH_TOKEN_ADDRESS} from "../../common/Config.sol"; import {UnsupportedEncodingVersion, AssetIdNotSupported, AssetHandlerDoesNotExist, Unauthorized, ZeroAddress, TokenNotSupported, AddressAlreadyUsed} from "../../common/L1ContractErrors.sol"; +import {NativeTokenVaultAlreadySet} from "../L1BridgeContractErrors.sol"; import {L2_ASSET_ROUTER_ADDR} from "../../common/L2ContractAddresses.sol"; import {IBridgehub, L2TransactionRequestTwoBridgesInner, L2TransactionRequestDirect} from "../../bridgehub/IBridgehub.sol"; @@ -110,12 +109,16 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { _transferOwnership(_owner); } - /// @notice Sets the L1ERC20Bridge contract address. + /// @notice Sets the NativeTokenVault contract address. /// @dev Should be called only once by the owner. /// @param _nativeTokenVault The address of the native token vault. function setNativeTokenVault(INativeTokenVault _nativeTokenVault) external onlyOwner { - require(address(nativeTokenVault) == address(0), "AR: native token v already set"); - require(address(_nativeTokenVault) != address(0), "AR: native token vault 0"); + if (address(nativeTokenVault) != address(0)) { + revert NativeTokenVaultAlreadySet(); + } + if (address(_nativeTokenVault) == address(0)) { + revert ZeroAddress(); + } nativeTokenVault = _nativeTokenVault; bytes32 ethAssetId = DataEncoding.encodeNTVAssetId(block.chainid, ETH_TOKEN_ADDRESS); assetHandlerAddress[ethAssetId] = address(nativeTokenVault); @@ -141,9 +144,7 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { bytes32 _assetRegistrationData, address _assetDeploymentTracker ) external onlyOwner { - bytes32 assetId = keccak256( - abi.encode(uint256(block.chainid), _assetDeploymentTracker, _assetRegistrationData) - ); + bytes32 assetId = keccak256(abi.encode(block.chainid, _assetDeploymentTracker, _assetRegistrationData)); assetDeploymentTracker[assetId] = _assetDeploymentTracker; emit AssetDeploymentTrackerSet(assetId, _assetDeploymentTracker, _assetRegistrationData); } @@ -157,7 +158,6 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { } /// @notice Used to set the asset handler address for a given asset ID on a remote ZK chain - /// @dev No access control on the caller, as msg.sender is encoded in the assetId. /// @param _chainId The ZK chain ID. /// @param _originalCaller The `msg.sender` address from the external call that initiated current one. /// @param _assetId The encoding of asset ID. @@ -404,10 +404,17 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { // Do the transfer if allowance to Shared bridge is bigger than amount // And if there is not enough allowance for the NTV - if ( + bool weCanTransfer = false; + if (l1Token.allowance(address(legacyBridge), address(this)) >= _amount) { + _originalCaller = address(legacyBridge); + weCanTransfer = true; + } else if ( l1Token.allowance(_originalCaller, address(this)) >= _amount && l1Token.allowance(_originalCaller, address(nativeTokenVault)) < _amount ) { + weCanTransfer = true; + } + if (weCanTransfer) { // slither-disable-next-line arbitrary-send-erc20 l1Token.safeTransferFrom(_originalCaller, address(nativeTokenVault), _amount); return true; @@ -542,7 +549,7 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { // Save the deposited amount to claim funds on L1 if the deposit failed on L2 L1_NULLIFIER.bridgehubConfirmL2TransactionForwarded( ERA_CHAIN_ID, - keccak256(abi.encode(_originalCaller, _l1Token, _amount)), + DataEncoding.encodeLegacyTxDataHash(_originalCaller, _l1Token, _amount), txHash ); @@ -565,19 +572,14 @@ contract L1AssetRouter is AssetRouterBase, IL1AssetRouter, ReentrancyGuard { bytes calldata _message, bytes32[] calldata _merkleProof ) external override { - /// @dev We use a deprecated field to support L2->L1 legacy withdrawals, which were started - /// by the legacy bridge. - address legacyL2Bridge = L1_NULLIFIER.l2BridgeAddress(_chainId); - FinalizeL1DepositParams memory finalizeWithdrawalParams = FinalizeL1DepositParams({ - chainId: _chainId, - l2BatchNumber: _l2BatchNumber, - l2MessageIndex: _l2MessageIndex, - l2Sender: legacyL2Bridge == address(0) ? L2_ASSET_ROUTER_ADDR : legacyL2Bridge, - l2TxNumberInBatch: _l2TxNumberInBatch, - message: _message, - merkleProof: _merkleProof + L1_NULLIFIER.finalizeWithdrawal({ + _chainId: _chainId, + _l2BatchNumber: _l2BatchNumber, + _l2MessageIndex: _l2MessageIndex, + _l2TxNumberInBatch: _l2TxNumberInBatch, + _message: _message, + _merkleProof: _merkleProof }); - L1_NULLIFIER.finalizeDeposit(finalizeWithdrawalParams); } /// @dev Withdraw funds from the initiated deposit, that failed when finalizing on L2. diff --git a/l1-contracts/contracts/bridge/asset-router/L2AssetRouter.sol b/l1-contracts/contracts/bridge/asset-router/L2AssetRouter.sol index 0a10822f4..04d92e3ac 100644 --- a/l1-contracts/contracts/bridge/asset-router/L2AssetRouter.sol +++ b/l1-contracts/contracts/bridge/asset-router/L2AssetRouter.sol @@ -33,13 +33,13 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { bytes32 public immutable BASE_TOKEN_ASSET_ID; /// @dev The address of the L1 asset router counterpart. - address public override l1AssetRouter; + address public immutable override L1_ASSET_ROUTER; /// @notice Checks that the message sender is the L1 Asset Router. modifier onlyAssetRouterCounterpart(uint256 _originChainId) { if (_originChainId == L1_CHAIN_ID) { // Only the L1 Asset Router counterpart can initiate and finalize the deposit. - if (AddressAliasHelper.undoL1ToL2Alias(msg.sender) != l1AssetRouter) { + if (AddressAliasHelper.undoL1ToL2Alias(msg.sender) != L1_ASSET_ROUTER) { revert InvalidCaller(msg.sender); } } else { @@ -52,9 +52,11 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { modifier onlyAssetRouterCounterpartOrSelf(uint256 _originChainId) { if (_originChainId == L1_CHAIN_ID) { // Only the L1 Asset Router counterpart can initiate and finalize the deposit. - if ((AddressAliasHelper.undoL1ToL2Alias(msg.sender) != l1AssetRouter) && (msg.sender != address(this))) { + if ((AddressAliasHelper.undoL1ToL2Alias(msg.sender) != L1_ASSET_ROUTER) && (msg.sender != address(this))) { revert InvalidCaller(msg.sender); } + } else { + revert InvalidCaller(msg.sender); // xL2 messaging not supported for now } _; } @@ -68,6 +70,7 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { } /// @dev Disable the initialization to prevent Parity hack. + /// @dev this contract is deployed in the L2GenesisUpgrade, and is meant as direct deployment without a proxy. /// @param _l1AssetRouter The address of the L1 Bridge contract. constructor( uint256 _l1ChainId, @@ -81,7 +84,7 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { if (_l1AssetRouter == address(0)) { revert EmptyAddress(); } - l1AssetRouter = _l1AssetRouter; + L1_ASSET_ROUTER = _l1AssetRouter; assetHandlerAddress[_baseTokenAssetId] = L2_NATIVE_TOKEN_VAULT_ADDR; BASE_TOKEN_ASSET_ID = _baseTokenAssetId; _disableInitializers(); @@ -92,10 +95,10 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { function setAssetHandlerAddress( uint256 _originChainId, bytes32 _assetId, - address _assetAddress + address _assetHandlerAddress ) external override onlyAssetRouterCounterpart(_originChainId) { - assetHandlerAddress[_assetId] = _assetAddress; - emit AssetHandlerRegistered(_assetId, _assetAddress); + assetHandlerAddress[_assetId] = _assetHandlerAddress; + emit AssetHandlerRegistered(_assetId, _assetHandlerAddress); } /// @inheritdoc IAssetRouterBase @@ -127,16 +130,6 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { emit DepositFinalizedAssetRouter(L1_CHAIN_ID, _assetId, _transferData); } - /*////////////////////////////////////////////////////////////// - Internal & Helpers - //////////////////////////////////////////////////////////////*/ - - /// @inheritdoc AssetRouterBase - function _ensureTokenRegisteredWithNTV(address _token) internal override returns (bytes32 assetId) { - IL2NativeTokenVault nativeTokenVault = IL2NativeTokenVault(L2_NATIVE_TOKEN_VAULT_ADDR); - nativeTokenVault.ensureTokenIsRegistered(_token); - } - /*////////////////////////////////////////////////////////////// LEGACY FUNCTIONS //////////////////////////////////////////////////////////////*/ @@ -160,6 +153,19 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { return _withdrawSender(assetId, _assetData, msg.sender, true); } + /*////////////////////////////////////////////////////////////// + Internal & Helpers + //////////////////////////////////////////////////////////////*/ + + /// @notice Ensures that token is registered with native token vault. + /// @dev Only used when deposit is made with legacy data encoding format. + /// @param _token The L2 token address which should be registered with native token vault. + /// @return assetId The asset ID of the token provided. + function _ensureTokenRegisteredWithNTV(address _token) internal override returns (bytes32 assetId) { + IL2NativeTokenVault nativeTokenVault = IL2NativeTokenVault(L2_NATIVE_TOKEN_VAULT_ADDR); + nativeTokenVault.ensureTokenIsRegistered(_token); + } + /// @notice Initiates a withdrawal by burning funds on the contract and sending the message to L1 /// where tokens would be unlocked /// @param _assetId The asset id of the withdrawn asset @@ -222,6 +228,10 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { return abi.encodePacked(IL1ERC20Bridge.finalizeWithdrawal.selector, _l1Receiver, _l1Token, _amount); } + /*////////////////////////////////////////////////////////////// + LEGACY FUNCTIONS + //////////////////////////////////////////////////////////////*/ + /// @notice Legacy finalizeDeposit. /// @dev Finalizes the deposit and mint funds. /// @param _l1Sender The address of token sender on L1. @@ -337,6 +347,6 @@ contract L2AssetRouter is AssetRouterBase, IL2AssetRouter { /// @notice Returns the address of the L1 asset router. /// @dev The old name is kept for backward compatibility. function l1Bridge() external view returns (address) { - return l1AssetRouter; + return L1_ASSET_ROUTER; } } diff --git a/l1-contracts/contracts/bridge/interfaces/IAssetHandler.sol b/l1-contracts/contracts/bridge/interfaces/IAssetHandler.sol index 57f58eb59..bcb60a2ab 100644 --- a/l1-contracts/contracts/bridge/interfaces/IAssetHandler.sol +++ b/l1-contracts/contracts/bridge/interfaces/IAssetHandler.sol @@ -7,9 +7,6 @@ pragma solidity 0.8.24; /// @custom:security-contact security@matterlabs.dev /// @notice Used for any asset handler and called by the AssetRouter interface IAssetHandler { - /// @dev Emitted when a new token is initialized - event BridgeInitialize(address indexed token, string name, string symbol, uint8 decimals); - /// @dev Emitted when a token is minted event BridgeMint(uint256 indexed chainId, bytes32 indexed assetId, address receiver, uint256 amount); @@ -27,7 +24,7 @@ interface IAssetHandler { /// @param _data the actual data specified for the function function bridgeMint(uint256 _chainId, bytes32 _assetId, bytes calldata _data) external payable; - /// @notice Burns bridged tokens and returns the calldata for L2 -> L1 message. + /// @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. diff --git a/l1-contracts/contracts/bridge/interfaces/IL1Nullifier.sol b/l1-contracts/contracts/bridge/interfaces/IL1Nullifier.sol index 61bf38516..baf2b41e7 100644 --- a/l1-contracts/contracts/bridge/interfaces/IL1Nullifier.sol +++ b/l1-contracts/contracts/bridge/interfaces/IL1Nullifier.sol @@ -86,6 +86,15 @@ interface IL1Nullifier { function nullifyChainBalanceByNTV(uint256 _chainId, address _token) external; + function finalizeWithdrawal( + uint256 _chainId, + uint256 _l2BatchNumber, + uint256 _l2MessageIndex, + uint16 _l2TxNumberInBatch, + bytes calldata _message, + bytes32[] calldata _merkleProof + ) external; + /// @dev Withdraw funds from the initiated deposit, that failed when finalizing on L2. /// @param _chainId The ZK chain id to which deposit was initiated. /// @param _depositSender The address of the entity that initiated the deposit. diff --git a/l1-contracts/contracts/bridge/interfaces/IL2Bridge.sol b/l1-contracts/contracts/bridge/interfaces/IL2Bridge.sol deleted file mode 100644 index 7fe7b7a97..000000000 --- a/l1-contracts/contracts/bridge/interfaces/IL2Bridge.sol +++ /dev/null @@ -1,15 +0,0 @@ -// 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 security@matterlabs.dev -interface IL2Bridge { - function withdraw(bytes32 _assetId, bytes memory _assetData) external; - - function finalizeDeposit(bytes32 _assetId, bytes calldata _transferData) external; - - function l1Bridge() external view returns (address); - - function setAssetHandlerAddress(bytes32 _assetId, address _assetAddress) external; -} diff --git a/l1-contracts/contracts/bridge/ntv/L1NativeTokenVault.sol b/l1-contracts/contracts/bridge/ntv/L1NativeTokenVault.sol index d5b059ae6..a36007fe7 100644 --- a/l1-contracts/contracts/bridge/ntv/L1NativeTokenVault.sol +++ b/l1-contracts/contracts/bridge/ntv/L1NativeTokenVault.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; import {IBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/IBeacon.sol"; import {Create2} from "@openzeppelin/contracts-v4/utils/Create2.sol"; @@ -24,7 +22,8 @@ import {ETH_TOKEN_ADDRESS} from "../../common/Config.sol"; import {L2_NATIVE_TOKEN_VAULT_ADDR} from "../../common/L2ContractAddresses.sol"; import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; -import {Unauthorized, ZeroAddress, NoFundsTransferred, InsufficientChainBalance, WithdrawFailed, OriginChainIdNotFound} from "../../common/L1ContractErrors.sol"; +import {OriginChainIdNotFound, Unauthorized, ZeroAddress, NoFundsTransferred, InsufficientChainBalance, WithdrawFailed} from "../../common/L1ContractErrors.sol"; +import {ClaimFailedDepositFailed, ZeroAmountToTransfer, WrongAmountTransferred, WrongCounterpart} from "../L1BridgeContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -36,9 +35,6 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken /// @dev L1 nullifier contract that handles legacy functions & finalize withdrawal, confirm l2 tx mappings IL1Nullifier public immutable override L1_NULLIFIER; - /// @dev Era's chainID - uint256 public immutable ERA_CHAIN_ID; - /// @dev Maps token balances for each chain to prevent unauthorized spending across ZK chains. /// This serves as a security measure until hyperbridging is implemented. /// NOTE: this function may be removed in the future, don't rely on it! @@ -48,12 +44,10 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken /// @dev Initialize the implementation to prevent Parity hack. /// @param _l1WethAddress Address of WETH on deployed chain /// @param _l1AssetRouter Address of Asset Router on L1. - /// @param _eraChainId ID of Era. /// @param _l1Nullifier Address of the nullifier contract, which handles transaction progress between L1 and ZK chains. constructor( address _l1WethAddress, address _l1AssetRouter, - uint256 _eraChainId, IL1Nullifier _l1Nullifier ) NativeTokenVault( @@ -63,7 +57,6 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken block.chainid ) { - ERA_CHAIN_ID = _eraChainId; L1_NULLIFIER = _l1Nullifier; } @@ -107,10 +100,14 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken } else { uint256 balanceBefore = IERC20(_token).balanceOf(address(this)); uint256 nullifierChainBalance = IERC20(_token).balanceOf(address(L1_NULLIFIER)); - require(nullifierChainBalance > 0, "NTV: 0 amount to transfer"); + if (nullifierChainBalance == 0) { + revert ZeroAmountToTransfer(); + } L1_NULLIFIER.transferTokenToNTV(_token); uint256 balanceAfter = IERC20(_token).balanceOf(address(this)); - require(balanceAfter - balanceBefore >= nullifierChainBalance, "NTV: wrong amount transferred"); + if (balanceAfter - balanceBefore < nullifierChainBalance) { + revert WrongAmountTransferred(balanceAfter - balanceBefore, nullifierChainBalance); + } } } @@ -134,7 +131,9 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken address, address _assetHandlerAddressOnCounterpart ) external view override onlyAssetRouter { - require(_assetHandlerAddressOnCounterpart == L2_NATIVE_TOKEN_VAULT_ADDR, "NTV: wrong counterpart"); + if (_assetHandlerAddressOnCounterpart != L2_NATIVE_TOKEN_VAULT_ADDR) { + revert WrongCounterpart(); + } } function _getOriginChainId(bytes32 _assetId) internal view returns (uint256) { @@ -208,7 +207,9 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken assembly { callSuccess := call(gas(), _depositSender, _amount, 0, 0, 0, 0) } - require(callSuccess, "NTV: claimFailedDeposit failed, no funds or cannot transfer to receiver"); + if (!callSuccess) { + revert ClaimFailedDepositFailed(); + } } else { uint256 originChainId = _getOriginChainId(_assetId); if (originChainId == block.chainid) { @@ -230,9 +231,9 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken // get the computed address before the contract DeployWithCreate2 deployed using Bytecode of contract DeployWithCreate2 and salt specified by the sender function calculateCreate2TokenAddress( uint256 _originChainId, - address _l1Token + address _nonNativeToken ) public view override(INativeTokenVault, NativeTokenVault) returns (address) { - bytes32 salt = _getCreate2Salt(_originChainId, _l1Token); + bytes32 salt = _getCreate2Salt(_originChainId, _nonNativeToken); return Create2.computeAddress( salt, @@ -273,7 +274,7 @@ contract L1NativeTokenVault is IL1NativeTokenVault, IL1AssetHandler, NativeToken } } - function _deployBeaconProxy(bytes32 _salt) internal override returns (BeaconProxy proxy) { + function _deployBeaconProxy(bytes32 _salt, uint256) internal override returns (BeaconProxy proxy) { // Use CREATE2 to deploy the BeaconProxy address proxyAddress = Create2.deploy( 0, diff --git a/l1-contracts/contracts/bridge/ntv/L2NativeTokenVault.sol b/l1-contracts/contracts/bridge/ntv/L2NativeTokenVault.sol index 4b83037a7..af66345dc 100644 --- a/l1-contracts/contracts/bridge/ntv/L2NativeTokenVault.sol +++ b/l1-contracts/contracts/bridge/ntv/L2NativeTokenVault.sol @@ -16,13 +16,13 @@ import {NativeTokenVault} from "./NativeTokenVault.sol"; import {IL2SharedBridgeLegacy} from "../interfaces/IL2SharedBridgeLegacy.sol"; import {BridgedStandardERC20} from "../BridgedStandardERC20.sol"; -import {DEPLOYER_SYSTEM_CONTRACT, L2_ASSET_ROUTER_ADDR} from "../../common/L2ContractAddresses.sol"; +import {L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR} from "../../common/L2ContractAddresses.sol"; import {L2ContractHelper, IContractDeployer} from "../../common/libraries/L2ContractHelper.sol"; import {SystemContractsCaller} from "../../common/libraries/SystemContractsCaller.sol"; import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; -import {EmptyAddress, EmptyBytes32, AddressMismatch, DeployFailed, AssetIdNotSupported} from "../../common/L1ContractErrors.sol"; +import {EmptyAddress, EmptyBytes32, AddressMismatch, DeployFailed, AssetIdNotSupported, ZeroAddress} from "../../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -34,9 +34,10 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { IL2SharedBridgeLegacy public immutable L2_LEGACY_SHARED_BRIDGE; /// @dev Bytecode hash of the proxy for tokens deployed by the bridge. - bytes32 internal l2TokenProxyBytecodeHash; + bytes32 internal immutable L2_TOKEN_PROXY_BYTECODE_HASH; /// @notice Initializes the bridge contract for later use. + /// @dev this contract is deployed in the L2GenesisUpgrade, and is meant as direct deployment without a proxy. /// @param _l1ChainId The L1 chain id differs between mainnet and testnets. /// @param _l2TokenProxyBytecodeHash The bytecode hash of the proxy for tokens deployed by the bridge. /// @param _aliasedOwner The address of the governor contract. @@ -63,7 +64,7 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { revert EmptyAddress(); } - l2TokenProxyBytecodeHash = _l2TokenProxyBytecodeHash; + L2_TOKEN_PROXY_BYTECODE_HASH = _l2TokenProxyBytecodeHash; _transferOwnership(_aliasedOwner); if (_contractsDeployedAlready) { @@ -85,6 +86,9 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { /// @notice Sets the legacy token asset ID for the given L2 token address. function setLegacyTokenAssetId(address _l2TokenAddress) public { address l1TokenAddress = L2_LEGACY_SHARED_BRIDGE.l1TokenAddress(_l2TokenAddress); + if (l1TokenAddress == address(0)) { + revert ZeroAddress(); + } bytes32 newAssetId = DataEncoding.encodeNTVAssetId(L1_CHAIN_ID, l1TokenAddress); tokenAddress[newAssetId] = _l2TokenAddress; assetId[_l2TokenAddress] = newAssetId; @@ -92,33 +96,32 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { } /// @notice Ensures that the token is deployed. - /// @param _originChainId The chain ID of the origin chain. /// @param _assetId The asset ID. /// @param _originToken The origin token address. /// @param _erc20Data The ERC20 data. /// @return expectedToken The token address. - function _ensureTokenDeployed( - uint256 _originChainId, + function _ensureAndSaveTokenDeployed( bytes32 _assetId, address _originToken, bytes memory _erc20Data ) internal override returns (address expectedToken) { - expectedToken = _assetIdCheck(_originChainId, _assetId, _originToken); + uint256 tokenOriginChainId; + (expectedToken, tokenOriginChainId) = _calculateExpectedTokenAddress(_originToken, _erc20Data); address l1LegacyToken; if (address(L2_LEGACY_SHARED_BRIDGE) != address(0)) { l1LegacyToken = L2_LEGACY_SHARED_BRIDGE.l1TokenAddress(expectedToken); } if (l1LegacyToken != address(0)) { - /// token is a legacy token, no need to deploy - if (l1LegacyToken != _originToken) { - revert AddressMismatch(_originToken, l1LegacyToken); - } - tokenAddress[_assetId] = expectedToken; - assetId[expectedToken] = _assetId; + _ensureAndSaveTokenDeployedInnerLegacyToken({ + _assetId: _assetId, + _originToken: _originToken, + _expectedToken: expectedToken, + _l1LegacyToken: l1LegacyToken + }); } else { - super._ensureTokenDeployedInner({ - _originChainId: _originChainId, + super._ensureAndSaveTokenDeployedInner({ + _tokenOriginChainId: tokenOriginChainId, _assetId: _assetId, _originToken: _originToken, _erc20Data: _erc20Data, @@ -127,22 +130,44 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { } } + /// @notice Ensures that the token is deployed inner for legacy tokens. + function _ensureAndSaveTokenDeployedInnerLegacyToken( + bytes32 _assetId, + address _originToken, + address _expectedToken, + address _l1LegacyToken + ) internal { + _assetIdCheck(L1_CHAIN_ID, _assetId, _originToken); + + /// token is a legacy token, no need to deploy + if (_l1LegacyToken != _originToken) { + revert AddressMismatch(_originToken, _l1LegacyToken); + } + + tokenAddress[_assetId] = _expectedToken; + assetId[_expectedToken] = _assetId; + } + /// @notice Deploys the beacon proxy for the L2 token, while using ContractDeployer system contract. - /// @dev This function uses raw call to ContractDeployer to make sure that exactly `l2TokenProxyBytecodeHash` is used + /// @dev This function uses raw call to ContractDeployer to make sure that exactly `L2_TOKEN_PROXY_BYTECODE_HASH` is used /// for the code of the proxy. /// @param _salt The salt used for beacon proxy deployment of L2 bridged token. + /// @param _tokenOriginChainId The origin chain id of the token. /// @return proxy The beacon proxy, i.e. L2 bridged token. - function _deployBeaconProxy(bytes32 _salt) internal virtual override returns (BeaconProxy proxy) { - if (address(L2_LEGACY_SHARED_BRIDGE) == address(0)) { + function _deployBeaconProxy( + bytes32 _salt, + uint256 _tokenOriginChainId + ) internal virtual override returns (BeaconProxy proxy) { + if (address(L2_LEGACY_SHARED_BRIDGE) == address(0) || _tokenOriginChainId != L1_CHAIN_ID) { // Deploy the beacon proxy for the L2 token (bool success, bytes memory returndata) = SystemContractsCaller.systemCallWithReturndata( uint32(gasleft()), - DEPLOYER_SYSTEM_CONTRACT, + L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, 0, abi.encodeCall( IContractDeployer.create2, - (_salt, l2TokenProxyBytecodeHash, abi.encode(address(bridgedTokenBeacon), "")) + (_salt, L2_TOKEN_PROXY_BYTECODE_HASH, abi.encode(address(bridgedTokenBeacon), "")) ) ); @@ -172,32 +197,36 @@ contract L2NativeTokenVault is IL2NativeTokenVault, NativeTokenVault { //////////////////////////////////////////////////////////////*/ /// @notice Calculates L2 wrapped token address given the currently stored beacon proxy bytecode hash and beacon address. - /// @param _l1Token The address of token on L1. + /// @param _originChainId The chain id of the origin token. + /// @param _nonNativeToken The address of token on its origin chain.. /// @return Address of an L2 token counterpart. function calculateCreate2TokenAddress( uint256 _originChainId, - address _l1Token + address _nonNativeToken ) public view virtual override(INativeTokenVault, NativeTokenVault) returns (address) { - bytes32 constructorInputHash = keccak256(abi.encode(address(bridgedTokenBeacon), "")); - bytes32 salt = _getCreate2Salt(_originChainId, _l1Token); if (address(L2_LEGACY_SHARED_BRIDGE) != address(0)) { - return L2_LEGACY_SHARED_BRIDGE.l2TokenAddress(_l1Token); + return L2_LEGACY_SHARED_BRIDGE.l2TokenAddress(_nonNativeToken); } else { + bytes32 constructorInputHash = keccak256(abi.encode(address(bridgedTokenBeacon), "")); + bytes32 salt = _getCreate2Salt(_originChainId, _nonNativeToken); return L2ContractHelper.computeCreate2Address( address(this), salt, - l2TokenProxyBytecodeHash, + L2_TOKEN_PROXY_BYTECODE_HASH, constructorInputHash ); } } /// @notice Calculates the salt for the Create2 deployment of the L2 token. - function _getCreate2Salt(uint256 _originChainId, address _l1Token) internal view override returns (bytes32 salt) { - salt = _originChainId == L1_CHAIN_ID + function _getCreate2Salt( + uint256 _tokenOriginChainId, + address _l1Token + ) internal view override returns (bytes32 salt) { + salt = _tokenOriginChainId == L1_CHAIN_ID ? bytes32(uint256(uint160(_l1Token))) - : keccak256(abi.encode(_originChainId, _l1Token)); + : keccak256(abi.encode(_tokenOriginChainId, _l1Token)); } function _handleChainBalanceIncrease( diff --git a/l1-contracts/contracts/bridge/ntv/NativeTokenVault.sol b/l1-contracts/contracts/bridge/ntv/NativeTokenVault.sol index c4d11e827..1ee41fdf6 100644 --- a/l1-contracts/contracts/bridge/ntv/NativeTokenVault.sol +++ b/l1-contracts/contracts/bridge/ntv/NativeTokenVault.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/security/PausableUpgradeable.sol"; import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; @@ -21,7 +19,8 @@ import {DataEncoding} from "../../common/libraries/DataEncoding.sol"; import {BridgedStandardERC20} from "../BridgedStandardERC20.sol"; import {BridgeHelper} from "../BridgeHelper.sol"; -import {EmptyDeposit, Unauthorized, TokensWithFeesNotSupported, TokenNotSupported, NonEmptyMsgValue, ValueMismatch, AddressMismatch, AssetIdMismatch, AmountMustBeGreaterThanZero, ZeroAddress, L1TokenDeploymentWithZeroChainId, DeployingBridgedTokenForNativeToken} from "../../common/L1ContractErrors.sol"; +import {AssetIdAlreadyRegistered, DeployingBridgedTokenForNativeToken, EmptyDeposit, Unauthorized, TokensWithFeesNotSupported, TokenNotSupported, NonEmptyMsgValue, ValueMismatch, AddressMismatch, AssetIdMismatch, AmountMustBeGreaterThanZero, ZeroAddress} from "../../common/L1ContractErrors.sol"; +import {EmptyToken} from "../L1BridgeContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -46,8 +45,8 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 /// @dev For more details see https://docs.openzeppelin.com/contracts/3.x/api/proxy#UpgradeableBeacon. IBeacon public bridgedTokenBeacon; - /// @dev A mapping assetId => tokenAddress - mapping(bytes32 assetId => uint256 chainId) public originChainId; + /// @dev A mapping assetId => originChainId + mapping(bytes32 assetId => uint256 originChainId) public originChainId; /// @dev A mapping assetId => tokenAddress mapping(bytes32 assetId => address tokenAddress) public tokenAddress; @@ -91,7 +90,12 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 if (_nativeToken == WETH_TOKEN) { revert TokenNotSupported(WETH_TOKEN); } - require(_nativeToken.code.length > 0, "NTV: empty token"); + if (_nativeToken.code.length == 0) { + revert EmptyToken(); + } + if (assetId[_nativeToken] != bytes32(0)) { + revert AssetIdAlreadyRegistered(); + } _unsafeRegisterNativeToken(_nativeToken); } @@ -142,7 +146,7 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 (, receiver, originToken, amount, erc20Data) = DataEncoding.decodeBridgeMintData(_data); if (token == address(0)) { - token = _ensureTokenDeployed(_originChainId, _assetId, originToken, erc20Data); + token = _ensureAndSaveTokenDeployed(_assetId, originToken, erc20Data); } _handleChainBalanceDecrease(_originChainId, _assetId, amount, false); IBridgedStandardToken(token).bridgeMint(receiver, amount); @@ -206,6 +210,7 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 address bridgedToken = tokenAddress[_assetId]; IBridgedStandardToken(bridgedToken).bridgeBurn(_originalCaller, _amount); + _handleChainBalanceIncrease(_chainId, _assetId, _amount, false); emit BridgeBurn({ chainId: _chainId, @@ -234,8 +239,8 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 _bridgeMintData = DataEncoding.encodeBridgeMintData({ _originalCaller: _originalCaller, - _l2Receiver: _receiver, - _l1Token: originToken, + _remoteReceiver: _receiver, + _originToken: originToken, _amount: _amount, _erc20Metadata: erc20Metadata }); @@ -290,8 +295,8 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 } _bridgeMintData = DataEncoding.encodeBridgeMintData({ _originalCaller: _originalCaller, - _l2Receiver: _receiver, - _l1Token: nativeToken, + _remoteReceiver: _receiver, + _originToken: nativeToken, _amount: amount, _erc20Metadata: erc20Metadata }); @@ -334,10 +339,10 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 /// @param _nativeToken The address of the token to be registered. function _unsafeRegisterNativeToken(address _nativeToken) internal { bytes32 newAssetId = DataEncoding.encodeNTVAssetId(block.chainid, _nativeToken); - ASSET_ROUTER.setAssetHandlerAddressThisChain(bytes32(uint256(uint160(_nativeToken))), address(this)); tokenAddress[newAssetId] = _nativeToken; assetId[_nativeToken] = newAssetId; originChainId[newAssetId] = block.chainid; + ASSET_ROUTER.setAssetHandlerAddressThisChain(bytes32(uint256(uint160(_nativeToken))), address(this)); } function _handleChainBalanceIncrease( @@ -358,15 +363,15 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 TOKEN DEPLOYER FUNCTIONS //////////////////////////////////////////////////////////////*/ - function _ensureTokenDeployed( - uint256 _originChainId, + function _ensureAndSaveTokenDeployed( bytes32 _assetId, address _originToken, bytes memory _erc20Data ) internal virtual returns (address expectedToken) { - expectedToken = _assetIdCheck(_originChainId, _assetId, _originToken); - _ensureTokenDeployedInner({ - _originChainId: _originChainId, + uint256 tokenOriginChainId; + (expectedToken, tokenOriginChainId) = _calculateExpectedTokenAddress(_originToken, _erc20Data); + _ensureAndSaveTokenDeployedInner({ + _tokenOriginChainId: tokenOriginChainId, _assetId: _assetId, _originToken: _originToken, _erc20Data: _erc20Data, @@ -374,27 +379,44 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 }); } - function _assetIdCheck( - uint256 _originChainId, - bytes32 _assetId, - address _originToken - ) internal view returns (address expectedToken) { - expectedToken = calculateCreate2TokenAddress(_originChainId, _originToken); - bytes32 expectedAssetId = DataEncoding.encodeNTVAssetId(_originChainId, _originToken); + /// @notice Calculates the bridged token address corresponding to native token counterpart. + function _calculateExpectedTokenAddress( + address _originToken, + bytes memory _erc20Data + ) internal view returns (address expectedToken, uint256 tokenOriginChainId) { + /// @dev calling externally to convert from memory to calldata + tokenOriginChainId = this.tokenDataOriginChainId(_erc20Data); + expectedToken = calculateCreate2TokenAddress(tokenOriginChainId, _originToken); + } + + /// @notice Returns the origin chain id from the token data. + function tokenDataOriginChainId(bytes calldata _erc20Data) public view returns (uint256 tokenOriginChainId) { + // slither-disable-next-line unused-return + (tokenOriginChainId, , , ) = DataEncoding.decodeTokenData(_erc20Data); + if (tokenOriginChainId == 0) { + tokenOriginChainId = L1_CHAIN_ID; + } + } + + /// @notice Checks that the assetId is correct for the origin token and chain. + function _assetIdCheck(uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken) internal view { + bytes32 expectedAssetId = DataEncoding.encodeNTVAssetId(_tokenOriginChainId, _originToken); if (_assetId != expectedAssetId) { // Make sure that a NativeTokenVault sent the message revert AssetIdMismatch(_assetId, expectedAssetId); } } - function _ensureTokenDeployedInner( - uint256 _originChainId, + function _ensureAndSaveTokenDeployedInner( + uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken, bytes memory _erc20Data, address _expectedToken ) internal { - address deployedToken = _deployBridgedToken(_originChainId, _assetId, _originToken, _erc20Data); + _assetIdCheck(_tokenOriginChainId, _assetId, _originToken); + + address deployedToken = _deployBridgedToken(_tokenOriginChainId, _assetId, _originToken, _erc20Data); if (deployedToken != _expectedToken) { revert AddressMismatch(_expectedToken, deployedToken); } @@ -404,40 +426,34 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 } /// @notice Calculates the bridged token address corresponding to native token counterpart. + /// @param _tokenOriginChainId The chain id of the origin token. /// @param _bridgeToken The address of native token. /// @return The address of bridged token. function calculateCreate2TokenAddress( - uint256 _originChainId, + uint256 _tokenOriginChainId, address _bridgeToken ) public view virtual override returns (address); /// @notice Deploys and initializes the bridged token for the native counterpart. + /// @param _tokenOriginChainId The chain id of the origin token. /// @param _originToken The address of origin token. /// @param _erc20Data The ERC20 metadata of the token deployed. /// @return The address of the beacon proxy (bridged token). function _deployBridgedToken( - uint256 _originChainId, + uint256 _tokenOriginChainId, bytes32 _assetId, address _originToken, bytes memory _erc20Data ) internal returns (address) { - bytes32 salt = _getCreate2Salt(_originChainId, _originToken); - - BeaconProxy l2Token = _deployBeaconProxy(salt); - uint256 tokenOriginChainId = BridgedStandardERC20(address(l2Token)).bridgeInitialize( - _assetId, - _originToken, - _erc20Data - ); - // an extra check for legacy tokens on L1, they might not be registered i.e. - if (block.chainid == L1_CHAIN_ID && tokenOriginChainId == 0) { - revert L1TokenDeploymentWithZeroChainId(_assetId); - } - tokenOriginChainId = tokenOriginChainId == 0 ? L1_CHAIN_ID : tokenOriginChainId; - if (tokenOriginChainId == block.chainid) { + if (_tokenOriginChainId == block.chainid) { revert DeployingBridgedTokenForNativeToken(); } - originChainId[DataEncoding.encodeNTVAssetId(tokenOriginChainId, _originToken)] = tokenOriginChainId; + bytes32 salt = _getCreate2Salt(_tokenOriginChainId, _originToken); + + BeaconProxy l2Token = _deployBeaconProxy(salt, _tokenOriginChainId); + BridgedStandardERC20(address(l2Token)).bridgeInitialize(_assetId, _originToken, _erc20Data); + + originChainId[_assetId] = _tokenOriginChainId; return address(l2Token); } @@ -453,7 +469,10 @@ abstract contract NativeTokenVault is INativeTokenVault, IAssetHandler, Ownable2 /// for the code of the proxy. /// @param _salt The salt used for beacon proxy deployment of the bridged token (we pass the native token address). /// @return proxy The beacon proxy, i.e. bridged token. - function _deployBeaconProxy(bytes32 _salt) internal virtual returns (BeaconProxy proxy); + function _deployBeaconProxy( + bytes32 _salt, + uint256 _tokenOriginChainId + ) internal virtual returns (BeaconProxy proxy); /*////////////////////////////////////////////////////////////// PAUSE diff --git a/l1-contracts/contracts/bridgehub/Bridgehub.sol b/l1-contracts/contracts/bridgehub/Bridgehub.sol index e084bc3d1..40e92f324 100644 --- a/l1-contracts/contracts/bridgehub/Bridgehub.sol +++ b/l1-contracts/contracts/bridgehub/Bridgehub.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {EnumerableMap} from "@openzeppelin/contracts-v4/utils/structs/EnumerableMap.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; @@ -23,11 +21,12 @@ import {BridgehubL2TransactionRequest, L2Message, L2Log, TxStatus} from "../comm import {AddressAliasHelper} from "../vendor/AddressAliasHelper.sol"; import {IMessageRoot} from "./IMessageRoot.sol"; import {ICTMDeploymentTracker} from "./ICTMDeploymentTracker.sol"; -import {MigrationPaused, AssetIdAlreadyRegistered, ChainAlreadyLive, ChainNotLegacy, CTMNotRegistered, ChainIdNotRegistered, AssetHandlerNotRegistered, ZKChainLimitReached, CTMAlreadyRegistered, CTMNotRegistered, ZeroChainId, ChainIdTooBig, BridgeHubAlreadyRegistered, AddressTooLow, MsgValueMismatch, ZeroAddress, Unauthorized, SharedBridgeNotSet, WrongMagicValue, ChainIdAlreadyExists, ChainIdMismatch, ChainIdCantBeCurrentChain, EmptyAssetId, AssetIdNotSupported, IncorrectBridgeHubAddress} from "../common/L1ContractErrors.sol"; +import {NotL1, NotRelayedSender, NotAssetRouter, TokenNotSet, ChainIdAlreadyPresent, ChainNotPresentInCTM, SecondBridgeAddressTooLow, NotInGatewayMode, SLNotWhitelisted, IncorrectChainAssetId, NotCurrentSL, HyperchainNotRegistered, IncorrectSender, AlreadyCurrentSL, ChainNotLegacy} from "./L1BridgehubErrors.sol"; +import {NoCTMForAssetId, MigrationPaused, AssetIdAlreadyRegistered, CTMNotRegistered, ChainIdNotRegistered, ZKChainLimitReached, CTMAlreadyRegistered, CTMNotRegistered, ZeroChainId, ChainIdTooBig, BridgeHubAlreadyRegistered, MsgValueMismatch, ZeroAddress, Unauthorized, SharedBridgeNotSet, WrongMagicValue, ChainIdAlreadyExists, ChainIdMismatch, ChainIdCantBeCurrentChain, EmptyAssetId, AssetIdNotSupported, IncorrectBridgeHubAddress, AssetHandlerNotRegistered} from "../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev -/// @dev The Bridgehub contract serves as the primary entry point for L1<->L2 communication, +/// @dev The Bridgehub contract serves as the primary entry point for L1->L2 communication, /// facilitating interactions between end user and bridges. /// It also manages state transition managers, base tokens, and chain registrations. /// Bridgehub is also an IL1AssetHandler for the chains themselves, which is used to migrate the chains @@ -46,7 +45,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus /// This is the temporary security measure. uint256 public immutable MAX_NUMBER_OF_ZK_CHAINS; - /// @notice all the ether and ERC20 tokens are held by NativeVaultToken managed by this shared Bridge. + /// @notice all the ether and ERC20 tokens are held by NativeVaultToken managed by the asset router. address public assetRouter; /// @notice ChainTypeManagers that are registered, and ZKchains that use these CTMs can use this bridgehub as settlement layer. @@ -110,16 +109,9 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus _; } - modifier onlyChainCTM(uint256 _chainId) { - if (msg.sender != chainTypeManager[_chainId]) { - revert Unauthorized(msg.sender); - } - _; - } - modifier onlyL1() { if (L1_CHAIN_ID != block.chainid) { - revert Unauthorized(msg.sender); + revert NotL1(L1_CHAIN_ID, block.chainid); } _; } @@ -127,14 +119,14 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus modifier onlySettlementLayerRelayedSender() { /// There is no sender for the wrapping, we use a virtual address. if (msg.sender != SETTLEMENT_LAYER_RELAY_SENDER) { - revert Unauthorized(msg.sender); + revert NotRelayedSender(msg.sender, SETTLEMENT_LAYER_RELAY_SENDER); } _; } modifier onlyAssetRouter() { if (msg.sender != assetRouter) { - revert Unauthorized(msg.sender); + revert NotAssetRouter(msg.sender, assetRouter); } _; } @@ -229,11 +221,13 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus /// @notice Used for the upgrade to set the baseTokenAssetId previously stored as baseToken. /// @param _chainId the chainId of the chain. function setLegacyBaseTokenAssetId(uint256 _chainId) external override { - if (baseTokenAssetId[_chainId] == bytes32(0)) { + if (baseTokenAssetId[_chainId] != bytes32(0)) { return; } address token = __DEPRECATED_baseToken[_chainId]; - require(token != address(0), "BH: token not set"); + if (token == address(0)) { + revert TokenNotSet(); + } baseTokenAssetId[_chainId] = DataEncoding.encodeNTVAssetId(block.chainid, token); } @@ -245,18 +239,18 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus revert ChainNotLegacy(); } if (zkChainMap.contains(_chainId)) { - revert ChainAlreadyLive(); + revert ChainIdAlreadyPresent(); } address chainAddress = IChainTypeManager(ctm).getZKChainLegacy(_chainId); if (chainAddress == address(0)) { - revert ChainNotLegacy(); + revert ChainNotPresentInCTM(); } - _registerNewZKChain(_chainId, chainAddress); + _registerNewZKChain(_chainId, chainAddress, false); } //// Registry - /// @notice State Transition can be any contract with the appropriate interface/functionality + /// @notice Chain Type Manager can be any contract with the appropriate interface/functionality /// @param _chainTypeManager the state transition manager address to be added function addChainTypeManager(address _chainTypeManager) external onlyOwner { if (_chainTypeManager == address(0)) { @@ -270,8 +264,8 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus emit ChainTypeManagerAdded(_chainTypeManager); } - /// @notice State Transition can be any contract with the appropriate interface/functionality - /// @notice this stops new Chains from using the STF, old chains are not affected + /// @notice Chain Type Manager can be any contract with the appropriate interface/functionality + /// @notice this stops new Chains from using the CTM, old chains are not affected /// @param _chainTypeManager the state transition manager address to be removed function removeChainTypeManager(address _chainTypeManager) external onlyOwner { if (_chainTypeManager == address(0)) { @@ -310,7 +304,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus /// @dev Used to set the assetAddress for a given assetInfo. /// @param _additionalData the additional data to identify the asset /// @param _assetAddress the asset handler address - function setAssetHandlerAddress(bytes32 _additionalData, address _assetAddress) external { + function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress) external { // It is a simplified version of the logic used by the AssetRouter to manage asset handlers. // CTM's assetId is `keccak256(abi.encode(L1_CHAIN_ID, l1CtmDeployer, ctmAddress))`. // And the l1CtmDeployer is considered the deployment tracker for the CTM asset. @@ -331,10 +325,10 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus revert CTMNotRegistered(); } - bytes32 assetInfo = keccak256(abi.encode(L1_CHAIN_ID, sender, _additionalData)); - ctmAssetIdToAddress[assetInfo] = _assetAddress; - ctmAssetIdFromAddress[_assetAddress] = assetInfo; - emit AssetRegistered(assetInfo, _assetAddress, _additionalData, msg.sender); + bytes32 ctmAssetId = keccak256(abi.encode(L1_CHAIN_ID, sender, _additionalData)); + ctmAssetIdToAddress[ctmAssetId] = _assetAddress; + ctmAssetIdFromAddress[_assetAddress] = ctmAssetId; + emit AssetRegistered(ctmAssetId, _assetAddress, _additionalData, msg.sender); } /*////////////////////////////////////////////////////////////// @@ -374,18 +368,26 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus _initData: _initData, _factoryDeps: _factoryDeps }); - _registerNewZKChain(_chainId, chainAddress); + _registerNewZKChain(_chainId, chainAddress, true); messageRoot.addNewChain(_chainId); emit NewChain(_chainId, _chainTypeManager, _admin); return _chainId; } - /// @dev This internal function is used to register a new zkChain in the system. - function _registerNewZKChain(uint256 _chainId, address _zkChain) internal { + /// @notice This internal function is used to register a new zkChain in the system. + /// @param _chainId The chain ID of the ZK chain + /// @param _zkChain The address of the ZK chain's DiamondProxy contract. + /// @param _checkMaxNumberOfZKChains Whether to check that the limit for the number + /// of chains has not been crossed. + /// @dev Providing `_checkMaxNumberOfZKChains = false` may be preferable in cases + /// where we want to guarantee that a chain can be added. These include: + /// - Migration of a chain from the mapping in the old CTM + /// - Migration of a chain to a new settlement layer + function _registerNewZKChain(uint256 _chainId, address _zkChain, bool _checkMaxNumberOfZKChains) internal { // slither-disable-next-line unused-return zkChainMap.set(_chainId, _zkChain); - if (zkChainMap.length() > MAX_NUMBER_OF_ZK_CHAINS) { + if (_checkMaxNumberOfZKChains && zkChainMap.length() > MAX_NUMBER_OF_ZK_CHAINS) { revert ZKChainLimitReached(); } } @@ -435,11 +437,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus if (ctmAddress == address(0)) { revert ChainIdNotRegistered(_chainId); } - return ctmAssetIdFromAddress[chainTypeManager[_chainId]]; - } - - function calculateCtmAssetId(address _ctmAddress) internal view returns (bytes32) { - return keccak256(abi.encode(L1_CHAIN_ID, address(l1CtmDeployer), bytes32(uint256(uint160(_ctmAddress))))); + return ctmAssetIdFromAddress[ctmAddress]; } /*////////////////////////////////////////////////////////////// @@ -450,7 +448,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus /// this assumes that either ether is the base token or /// the msg.sender has approved mintValue allowance for the nativeTokenVault. /// This means this is not ideal for contract calls, as the contract would have to handle token allowance of the base Token. - /// In case allowance is provided to the Shared Bridge, then it will be transferred to NTV. + /// In case allowance is provided to the Asset Router, then it will be transferred to NTV. function requestL2TransactionDirect( L2TransactionRequestDirect calldata _request ) external payable override nonReentrant whenNotPaused onlyL1 returns (bytes32 canonicalTxHash) { @@ -509,7 +507,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus L2TransactionRequestTwoBridgesOuter calldata _request ) external payable override nonReentrant whenNotPaused onlyL1 returns (bytes32 canonicalTxHash) { if (_request.secondBridgeAddress <= BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS) { - revert AddressTooLow(_request.secondBridgeAddress); + revert SecondBridgeAddressTooLow(_request.secondBridgeAddress, BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS); } { @@ -598,7 +596,9 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus bytes32 _canonicalTxHash, uint64 _expirationTimestamp ) external override onlySettlementLayerRelayedSender { - require(L1_CHAIN_ID != block.chainid, "BH: not in sync layer mode"); + if (L1_CHAIN_ID == block.chainid) { + revert NotInGatewayMode(); + } address zkChain = zkChainMap.get(_chainId); IZKChain(zkChain).bridgehubRequestL2TransactionOnGateway(_canonicalTxHash, _expirationTimestamp); } @@ -697,16 +697,26 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus address _originalCaller, bytes calldata _data ) external payable override onlyAssetRouter whenMigrationsNotPaused returns (bytes memory bridgehubMintData) { - require(whitelistedSettlementLayers[_settlementChainId], "BH: SL not whitelisted"); + if (!whitelistedSettlementLayers[_settlementChainId]) { + revert SLNotWhitelisted(); + } BridgehubBurnCTMAssetData memory bridgehubData = abi.decode(_data, (BridgehubBurnCTMAssetData)); - require(_assetId == ctmAssetIdFromChainId(bridgehubData.chainId), "BH: assetInfo 1"); - require(settlementLayer[bridgehubData.chainId] == block.chainid, "BH: not current SL"); + if (_assetId != ctmAssetIdFromChainId(bridgehubData.chainId)) { + revert IncorrectChainAssetId(_assetId, ctmAssetIdFromChainId(bridgehubData.chainId)); + } + if (settlementLayer[bridgehubData.chainId] != block.chainid) { + revert NotCurrentSL(settlementLayer[bridgehubData.chainId], block.chainid); + } settlementLayer[bridgehubData.chainId] = _settlementChainId; address zkChain = zkChainMap.get(bridgehubData.chainId); - require(zkChain != address(0), "BH: zkChain not registered"); - require(_originalCaller == IZKChain(zkChain).getAdmin(), "BH: incorrect sender"); + if (zkChain == address(0)) { + revert HyperchainNotRegistered(); + } + if (_originalCaller != IZKChain(zkChain).getAdmin()) { + revert IncorrectSender(_originalCaller, IZKChain(zkChain).getAdmin()); + } bytes memory ctmMintData = IChainTypeManager(chainTypeManager[bridgehubData.chainId]).forwardedBridgeBurn( bridgehubData.chainId, @@ -731,7 +741,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus } /// @dev IL1AssetHandler interface, used to receive a chain on the settlement layer. - /// @param _assetId the assetId of the chain's STM + /// @param _assetId the assetId of the chain's CTM /// @param _bridgehubMintData the data for the mint function bridgeMint( uint256, // originChainId @@ -741,8 +751,12 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus BridgehubMintCTMAssetData memory bridgehubData = abi.decode(_bridgehubMintData, (BridgehubMintCTMAssetData)); address ctm = ctmAssetIdToAddress[_assetId]; - require(ctm != address(0), "BH: assetInfo 2"); - require(settlementLayer[bridgehubData.chainId] != block.chainid, "BH: already current SL"); + if (ctm == address(0)) { + revert NoCTMForAssetId(_assetId); + } + if (settlementLayer[bridgehubData.chainId] == block.chainid) { + revert AlreadyCurrentSL(block.chainid); + } settlementLayer[bridgehubData.chainId] = block.chainid; chainTypeManager[bridgehubData.chainId] = ctm; @@ -755,8 +769,11 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus bool contractAlreadyDeployed = zkChain != address(0); if (!contractAlreadyDeployed) { zkChain = IChainTypeManager(ctm).forwardedBridgeMint(bridgehubData.chainId, bridgehubData.ctmData); - require(zkChain != address(0), "BH: chain not registered"); - _registerNewZKChain(bridgehubData.chainId, zkChain); + if (zkChain == address(0)) { + revert ChainIdNotRegistered(bridgehubData.chainId); + } + // We want to allow any chain to be migrated, + _registerNewZKChain(bridgehubData.chainId, zkChain, false); messageRoot.addNewChain(bridgehubData.chainId); } @@ -777,7 +794,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus ) external payable override onlyAssetRouter onlyL1 { BridgehubBurnCTMAssetData memory bridgehubData = abi.decode(_data, (BridgehubBurnCTMAssetData)); - delete settlementLayer[bridgehubData.chainId]; + settlementLayer[bridgehubData.chainId] = block.chainid; IChainTypeManager(chainTypeManager[bridgehubData.chainId]).forwardedBridgeRecoverFailedTransfer({ _chainId: bridgehubData.chainId, @@ -824,7 +841,7 @@ contract Bridgehub is IBridgehub, ReentrancyGuard, Ownable2StepUpgradeable, Paus baseTokenAssetId[_chainId] = chainBaseTokenAssetId; settlementLayer[_chainId] = block.chainid; - _registerNewZKChain(_chainId, _zkChain); + _registerNewZKChain(_chainId, _zkChain, true); messageRoot.addNewChain(_chainId); emit NewChain(_chainId, ctm, chainAdmin); diff --git a/l1-contracts/contracts/bridgehub/CTMDeploymentTracker.sol b/l1-contracts/contracts/bridgehub/CTMDeploymentTracker.sol index b82ad213b..856fe6e8b 100644 --- a/l1-contracts/contracts/bridgehub/CTMDeploymentTracker.sol +++ b/l1-contracts/contracts/bridgehub/CTMDeploymentTracker.sol @@ -2,10 +2,7 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; -import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/security/PausableUpgradeable.sol"; import {IBridgehub, L2TransactionRequestTwoBridgesInner} from "./IBridgehub.sol"; import {ICTMDeploymentTracker} from "./ICTMDeploymentTracker.sol"; @@ -14,6 +11,8 @@ import {IAssetRouterBase} from "../bridge/asset-router/IAssetRouterBase.sol"; import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; import {TWO_BRIDGES_MAGIC_VALUE} from "../common/Config.sol"; import {L2_BRIDGEHUB_ADDR} from "../common/L2ContractAddresses.sol"; +import {OnlyBridgehub, CTMNotRegistered, NotOwnerViaRouter, NoEthAllowed, NotOwner, WrongCounterPart} from "./L1BridgehubErrors.sol"; +import {UnsupportedEncodingVersion} from "../common/L1ContractErrors.sol"; /// @dev The encoding version of the data. bytes1 constant CTM_DEPLOYMENT_TRACKER_ENCODING_VERSION = 0x01; @@ -21,33 +20,35 @@ bytes1 constant CTM_DEPLOYMENT_TRACKER_ENCODING_VERSION = 0x01; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev /// @dev Contract to be deployed on L1, can link together other contracts based on AssetInfo. -contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable2StepUpgradeable, PausableUpgradeable { +contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable2StepUpgradeable { /// @dev Bridgehub smart contract that is used to operate with L2 via asynchronous L2 <-> L1 communication. IBridgehub public immutable override BRIDGE_HUB; - /// @dev Bridgehub smart contract that is used to operate with L2 via asynchronous L2 <-> L1 communication. + /// @dev L1AssetRouter smart contract that is used to bridge assets (including chains) between L1 and L2. IAssetRouterBase public immutable override L1_ASSET_ROUTER; /// @notice Checks that the message sender is the bridgehub. modifier onlyBridgehub() { - // solhint-disable-next-line gas-custom-errors - require(msg.sender == address(BRIDGE_HUB), "CTM DT: not BH"); + if (msg.sender != address(BRIDGE_HUB)) { + revert OnlyBridgehub(msg.sender, address(BRIDGE_HUB)); + } _; } /// @notice Checks that the message sender is the bridgehub. modifier onlyOwnerViaRouter(address _originalCaller) { - // solhint-disable-next-line gas-custom-errors - require(msg.sender == address(L1_ASSET_ROUTER) && _originalCaller == owner(), "CTM DT: not owner via router"); + if (msg.sender != address(L1_ASSET_ROUTER) || _originalCaller != owner()) { + revert NotOwnerViaRouter(msg.sender, _originalCaller); + } _; } /// @dev Contract is expected to be used as proxy implementation on L1. /// @dev Initialize the implementation to prevent Parity hack. - constructor(IBridgehub _bridgehub, IAssetRouterBase _sharedBridge) reentrancyGuardInitializer { + constructor(IBridgehub _bridgehub, IAssetRouterBase _l1AssetRouter) reentrancyGuardInitializer { _disableInitializers(); BRIDGE_HUB = _bridgehub; - L1_ASSET_ROUTER = _sharedBridge; + L1_ASSET_ROUTER = _l1AssetRouter; } /// @notice used to initialize the contract @@ -59,11 +60,11 @@ contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable /// @notice Used to register the ctm asset in L1 contracts, AssetRouter and Bridgehub. /// @param _ctmAddress the address of the ctm asset function registerCTMAssetOnL1(address _ctmAddress) external onlyOwner { - // solhint-disable-next-line gas-custom-errors - - require(BRIDGE_HUB.chainTypeManagerIsRegistered(_ctmAddress), "CTMDT: ctm not registered"); + if (!BRIDGE_HUB.chainTypeManagerIsRegistered(_ctmAddress)) { + revert CTMNotRegistered(); + } L1_ASSET_ROUTER.setAssetHandlerAddressThisChain(bytes32(uint256(uint160(_ctmAddress))), address(BRIDGE_HUB)); - BRIDGE_HUB.setAssetHandlerAddress(bytes32(uint256(uint160(_ctmAddress))), _ctmAddress); + BRIDGE_HUB.setCTMAssetAddress(bytes32(uint256(uint160(_ctmAddress))), _ctmAddress); } /// @notice The function responsible for registering the L2 counterpart of an CTM asset on the L2 Bridgehub. @@ -86,14 +87,17 @@ contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable uint256, bytes calldata _data ) external payable onlyBridgehub returns (L2TransactionRequestTwoBridgesInner memory request) { - // solhint-disable-next-line gas-custom-errors - - require(msg.value == 0, "CTMDT: no eth allowed"); - // solhint-disable-next-line gas-custom-errors + if (msg.value != 0) { + revert NoEthAllowed(); + } - require(_originalCaller == owner(), "CTMDT: not owner"); + if (_originalCaller != owner()) { + revert NotOwner(_originalCaller, owner()); + } bytes1 encodingVersion = _data[0]; - require(encodingVersion == CTM_DEPLOYMENT_TRACKER_ENCODING_VERSION, "CTMDT: wrong encoding version"); + if (encodingVersion != CTM_DEPLOYMENT_TRACKER_ENCODING_VERSION) { + revert UnsupportedEncodingVersion(); + } (address _ctmL1Address, address _ctmL2Address) = abi.decode(_data[1:], (address, address)); request = _registerCTMAssetOnL2Bridgehub(_chainId, _ctmL1Address, _ctmL2Address); @@ -112,7 +116,9 @@ contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable address _originalCaller, address _assetHandlerAddressOnCounterpart ) external view override onlyOwnerViaRouter(_originalCaller) { - require(_assetHandlerAddressOnCounterpart == L2_BRIDGEHUB_ADDR, "CTMDT: wrong counter part"); + if (_assetHandlerAddressOnCounterpart != L2_BRIDGEHUB_ADDR) { + revert WrongCounterPart(_assetHandlerAddressOnCounterpart, L2_BRIDGEHUB_ADDR); + } } function calculateAssetId(address _l1CTM) public view override returns (bytes32) { @@ -128,7 +134,7 @@ contract CTMDeploymentTracker is ICTMDeploymentTracker, ReentrancyGuard, Ownable address _ctmL2Address ) internal pure returns (L2TransactionRequestTwoBridgesInner memory request) { bytes memory l2TxCalldata = abi.encodeCall( - IBridgehub.setAssetHandlerAddress, + IBridgehub.setCTMAssetAddress, (bytes32(uint256(uint160(_ctmL1Address))), _ctmL2Address) ); diff --git a/l1-contracts/contracts/bridgehub/IBridgehub.sol b/l1-contracts/contracts/bridgehub/IBridgehub.sol index 3f05bba35..75e24f413 100644 --- a/l1-contracts/contracts/bridgehub/IBridgehub.sol +++ b/l1-contracts/contracts/bridgehub/IBridgehub.sol @@ -118,6 +118,8 @@ interface IBridgehub is IAssetHandler, IL1AssetHandler { function admin() external view returns (address); + function assetRouter() external view returns (address); + /// Mailbox forwarder function proveL2MessageInclusion( @@ -223,7 +225,7 @@ interface IBridgehub is IAssetHandler, IL1AssetHandler { function ctmAssetIdToAddress(bytes32 _assetInfo) external view returns (address); - function setAssetHandlerAddress(bytes32 _additionalData, address _assetAddress) external; + function setCTMAssetAddress(bytes32 _additionalData, address _assetAddress) external; function L1_CHAIN_ID() external view returns (uint256); diff --git a/l1-contracts/contracts/bridgehub/IMessageRoot.sol b/l1-contracts/contracts/bridgehub/IMessageRoot.sol index 2e15e6f63..d4a3c7d7b 100644 --- a/l1-contracts/contracts/bridgehub/IMessageRoot.sol +++ b/l1-contracts/contracts/bridgehub/IMessageRoot.sol @@ -4,8 +4,11 @@ pragma solidity 0.8.24; import {IBridgehub} from "./IBridgehub.sol"; -/// @author Matter Labs -/// @custom:security-contact security@matterlabs.dev +/** + * @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 security@matterlabs.dev + */ interface IMessageRoot { function BRIDGE_HUB() external view returns (IBridgehub); diff --git a/l1-contracts/contracts/bridgehub/L1BridgehubErrors.sol b/l1-contracts/contracts/bridgehub/L1BridgehubErrors.sol new file mode 100644 index 000000000..56b0cb75b --- /dev/null +++ b/l1-contracts/contracts/bridgehub/L1BridgehubErrors.sol @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.21; + +// 0xa2ac02a0 +error NotRelayedSender(address msgSender, address settlementLayerRelaySender); + +// 0xf306a770 +error NotAssetRouter(address msgSender, address sharedBridge); + +// 0x4b62f013 +error TokenNotSet(); + +// 0xff514c10 +error ChainIdAlreadyPresent(); + +// 0x4bd4ae07 +error ChainNotPresentInCTM(); + +// 0xfe919e28 +error AssetIdAlreadyRegistered(); + +// 0xc630ef3c +error CTMNotRegistered(); + +// 0x4c0f5001 +error ChainIdNotRegistered(); + +// 0xb78dbaa7 +error SecondBridgeAddressTooLow(address secondBridgeAddress, address minSecondBridgeAddress); + +// 0x472477e2 +error NotInGatewayMode(); + +// 0x90c7cbf1 +error SLNotWhitelisted(); + +// 0x48857c1d +error IncorrectChainAssetId(bytes32 assetId, bytes32 assetIdFromChainId); + +// 0xc0ca9182 +error NotCurrentSL(uint256 settlementLayerChainId, uint256 blockChainId); + +// 0xeab895aa +error HyperchainNotRegistered(); + +// 0xf5e39c1f +error IncorrectSender(address prevMsgSender, address chainAdmin); + +// 0x587df426 +error AlreadyCurrentSL(uint256 blockChainId); + +// 0x65e8a019 +error ChainExists(); + +// 0x913183d8 +error MessageRootNotRegistered(); + +// 0x8b7d939c +error TooManyChains(uint256 cachedChainCount, uint256 maxNumberOfChains); + +// 0x7f4316f3 +error NoEthAllowed(); + +// 0x23295f0e +error NotOwner(address sender, address owner); + +// 0x92626457 +error WrongCounterPart(address addressOnCounterPart, address l2BridgehubAddress); + +// 0xecb34449 +error NotL1(uint256 l1ChainId, uint256 blockChainId); + +// 0x527b87c7 +error OnlyBridgehub(address msgSender, address bridgehub); + +// 0x73fe6c1b +error OnlyChain(address msgSender, address zkChainAddress); + +// 0x693cd3dc +error NotOwnerViaRouter(address msgSender, address originalCaller); + +// 0x5de72107 +error ChainNotLegacy(); diff --git a/l1-contracts/contracts/bridgehub/MessageRoot.sol b/l1-contracts/contracts/bridgehub/MessageRoot.sol index 3d81b990f..62303b8dc 100644 --- a/l1-contracts/contracts/bridgehub/MessageRoot.sol +++ b/l1-contracts/contracts/bridgehub/MessageRoot.sol @@ -2,14 +2,12 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {DynamicIncrementalMerkle} from "../common/libraries/DynamicIncrementalMerkle.sol"; import {IBridgehub} from "./IBridgehub.sol"; import {IMessageRoot} from "./IMessageRoot.sol"; import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; - +import {OnlyBridgehub, OnlyChain, ChainExists, MessageRootNotRegistered, TooManyChains} from "./L1BridgehubErrors.sol"; import {FullMerkle} from "../common/libraries/FullMerkle.sol"; import {MessageHashing} from "../common/libraries/MessageHashing.sol"; @@ -21,7 +19,7 @@ bytes32 constant CHAIN_TREE_EMPTY_ENTRY_HASH = bytes32( 0x46700b4d40ac5c35af2c22dda2787a91eb567b06c924a8fb8ae9a05b20c08c21 ); -// Chain tree consists of batch commitments as their leaves. We use hash of "new bytes(96)" as the hash of an empty leaf. +// The single shared tree consists of the roots of chain trees as its leaves. We use hash of "new bytes(96)" as the hash of an empty leaf. bytes32 constant SHARED_ROOT_TREE_EMPTY_HASH = bytes32( 0x46700b4d40ac5c35af2c22dda2787a91eb567b06c924a8fb8ae9a05b20c08c21 ); @@ -59,14 +57,18 @@ contract MessageRoot is IMessageRoot, ReentrancyGuard { /// @notice only the bridgehub can call modifier onlyBridgehub() { - require(msg.sender == address(BRIDGE_HUB), "MR: only bridgehub"); + if (msg.sender != address(BRIDGE_HUB)) { + revert OnlyBridgehub(msg.sender, address(BRIDGE_HUB)); + } _; } /// @notice only the bridgehub can call /// @param _chainId the chainId of the chain modifier onlyChain(uint256 _chainId) { - require(msg.sender == BRIDGE_HUB.getZKChain(_chainId), "MR: only chain"); + if (msg.sender != BRIDGE_HUB.getZKChain(_chainId)) { + revert OnlyChain(msg.sender, BRIDGE_HUB.getZKChain(_chainId)); + } _; } @@ -84,7 +86,9 @@ contract MessageRoot is IMessageRoot, ReentrancyGuard { } function addNewChain(uint256 _chainId) external onlyBridgehub { - require(!chainRegistered(_chainId), "MR: chain exists"); + if (chainRegistered(_chainId)) { + revert ChainExists(); + } _addNewChain(_chainId); } @@ -98,7 +102,9 @@ contract MessageRoot is IMessageRoot, ReentrancyGuard { uint256 _batchNumber, bytes32 _chainBatchRoot ) external onlyChain(_chainId) { - require(chainRegistered(_chainId), "MR: not registered"); + if (!chainRegistered(_chainId)) { + revert MessageRootNotRegistered(); + } bytes32 chainRoot; // slither-disable-next-line unused-return (, chainRoot) = chainTree[_chainId].push(MessageHashing.batchLeafHash(_chainBatchRoot, _batchNumber)); @@ -145,7 +151,9 @@ contract MessageRoot is IMessageRoot, ReentrancyGuard { /// @param _chainId the chainId of the chain function _addNewChain(uint256 _chainId) internal { uint256 cachedChainCount = chainCount; - require(cachedChainCount < MAX_NUMBER_OF_ZK_CHAINS, "MR: too many chains"); + if (cachedChainCount >= MAX_NUMBER_OF_ZK_CHAINS) { + revert TooManyChains(cachedChainCount, MAX_NUMBER_OF_ZK_CHAINS); + } ++chainCount; chainIndex[_chainId] = cachedChainCount; diff --git a/l1-contracts/contracts/common/Config.sol b/l1-contracts/contracts/common/Config.sol index a1e58f464..da2aa92fd 100644 --- a/l1-contracts/contracts/common/Config.sol +++ b/l1-contracts/contracts/common/Config.sol @@ -18,7 +18,6 @@ uint256 constant MAX_L2_TO_L1_LOGS_COMMITMENT_BYTES = 4 + L2_TO_L1_LOG_SERIALIZE /// @dev Actually equal to the `keccak256(new bytes(L2_TO_L1_LOG_SERIALIZE_SIZE))` bytes32 constant L2_L1_LOGS_TREE_DEFAULT_LEAF_HASH = 0x72abee45b59e344af8a6e520241c4744aff26ed411f4c4b00f8af09adada43ba; -// TODO: change constant to the real root hash of empty Merkle tree (SMA-184) bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = bytes32(0); /// @dev Denotes the type of the ZKsync transaction that came from L1. @@ -73,7 +72,7 @@ uint256 constant L1_TX_DELTA_FACTORY_DEPS_L2_GAS = 2473; 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 = 32; +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; @@ -112,6 +111,10 @@ bytes32 constant TWO_BRIDGES_MAGIC_VALUE = bytes32(uint256(keccak256("TWO_BRIDGE 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. @@ -155,4 +158,6 @@ struct ZKChainCommitment { bytes32[] batchHashes; /// @notice Commitment to the priority merkle tree. PriorityTreeCommitment priorityTree; + /// @notice Whether a chain is a permanent rollup. + bool isPermanentRollup; } diff --git a/l1-contracts/contracts/common/L1ContractErrors.sol b/l1-contracts/contracts/common/L1ContractErrors.sol index ab1320968..5aa1c0a50 100644 --- a/l1-contracts/contracts/common/L1ContractErrors.sol +++ b/l1-contracts/contracts/common/L1ContractErrors.sol @@ -5,6 +5,8 @@ pragma solidity ^0.8.21; error AccessToFallbackDenied(address target, address invoker); // 0x3995f750 error AccessToFunctionDenied(address target, bytes4 selector, address invoker); +// 0x8164f842 +error ApprovalFailed(); // 0x6c167909 error OnlySelfAllowed(); // 0x52e22c98 @@ -13,12 +15,6 @@ error RestrictionWasNotPresent(address restriction); error RestrictionWasAlreadyPresent(address restriction); // 0x3331e9c0 error CallNotAllowed(bytes call); -// 0x59e1b0d2 -error ChainZeroAddress(); -// 0xff4bbdf1 -error NotAHyperchain(address chainAddress); -// 0xa3decdf3 -error NotAnAdmin(address expected, address actual); // 0xf6fd7071 error RemovingPermanentRestriction(); // 0xfcb9b2e1 @@ -31,8 +27,6 @@ error AddressAlreadySet(address addr); error AddressHasNoCode(address); // 0x1f73225f error AddressMismatch(address expected, address supplied); -// 0x1eee5481 -error AddressTooLow(address); // 0x5e85ae73 error AmountMustBeGreaterThanZero(); // 0xfde974f4 @@ -45,8 +39,6 @@ error AssetIdAlreadyRegistered(); error AlreadyWhitelisted(address); // 0x04a0b7e9 error AssetIdNotSupported(bytes32 assetId); -// 0x6afd6c20 -error BadReturnData(); // 0x6ef9a972 error BaseTokenGasPriceDenominatorNotSet(); // 0x55ad3fd3 @@ -55,14 +47,10 @@ error BatchHashMismatch(bytes32 expected, bytes32 actual); error BatchNotExecuted(uint256 batchNumber); // 0xbd4455ff error BatchNumberMismatch(uint256 expectedBatchNumber, uint256 providedBatchNumber); -// 0xafd53e2f -error BlobHashCommitmentError(uint256 index, bool blobHashEmpty, bool blobCommitmentEmpty); // 0x6cf12312 error BridgeHubAlreadyRegistered(); // 0xdb538614 error BridgeMintNotImplemented(); -// 0xcf102c5a -error CalldataLengthTooBig(); // 0xe85392f9 error CanOnlyProcessOneBatch(); // 0x00c6ead2 @@ -77,10 +65,6 @@ error ChainIdCantBeCurrentChain(); error ChainIdMismatch(); // 0x23f3c357 error ChainIdNotRegistered(uint256 chainId); -// 0x5de72107 -error ChainNotLegacy(); -// 0x78d2ed02 -error ChainAlreadyLive(); // 0x8f620a06 error ChainIdTooBig(); // 0xf7a01e4d @@ -95,34 +79,22 @@ error DeployingBridgedTokenForNativeToken(); error DepositDoesNotExist(); // 0xad2fa98e error DepositExists(); -// 0x79cacff1 -error DepositFailed(); // 0x0e7ee319 error DiamondAlreadyFrozen(); -// 0x682dabb4 -error DiamondFreezeIncorrectState(); // 0xa7151b9a error DiamondNotFrozen(); // 0x7138356f error EmptyAddress(); // 0x2d4d012f error EmptyAssetId(); -// 0xfc7ab1d3 -error EmptyBlobVersionHash(uint256 index); // 0x1c25715b error EmptyBytes32(); // 0x95b66fe9 error EmptyDeposit(); // 0x627e0872 error ETHDepositNotSupported(); -// -error FailedToTransferTokens(address tokenContract, address to, uint256 amount); // 0xac4a3f98 error FacetExists(bytes4 selector, address); -// 0x79e12cc3 -error FacetIsFrozen(bytes4 func); -/// -error FunctionNotSupported(); // 0xc91cf3b1 error GasPerPubdataMismatch(); // 0x6d4a7df8 @@ -137,26 +109,16 @@ error GenesisUpgradeZero(); error HashedLogIsDefault(); // 0x0b08d5be error HashMismatch(bytes32 expected, bytes32 actual); -// 0xb615c2b1 +// 0x601b6882 error ZKChainLimitReached(); -// -error InsufficientAllowance(uint256 providedAllowance, uint256 requiredAmount); // 0xdd381a4c error IncorrectBridgeHubAddress(address bridgehub); // 0x826fb11e error InsufficientChainBalance(); -// 0x356680b7 -error InsufficientFunds(); // 0xcbd9d2e0 error InvalidCaller(address); -// 0x7a47c9a2 -error InvalidChainId(); // 0x4fbe5dba error InvalidDelay(); -// 0x0af806e0 -error InvalidHash(); -// -error InvalidInput(); // 0xc1780bd6 error InvalidLogSender(address sender, uint256 logKey); // 0xd8e9405c @@ -165,50 +127,28 @@ error InvalidNumberOfBlobs(uint256 expected, uint256 numCommitments, uint256 num error InvalidProof(); // 0x5428eae7 error InvalidProtocolVersion(); -// 0x53e6d04d -error InvalidPubdataCommitmentsSize(); // 0x5513177c error InvalidPubdataHash(bytes32 expectedHash, bytes32 provided); -// 0x9094af7e -error InvalidPubdataLength(); -// 0xc5d09071 -error InvalidPubdataMode(); // 0x6f1cf752 error InvalidPubdataPricingMode(); // 0x12ba286f error InvalidSelector(bytes4 func); // 0x5cb29523 error InvalidTxType(uint256 txType); -// 0x5f1aa154 +// 0x0214acb6 error InvalidUpgradeTxn(UpgradeTxVerifyParam); -// 0xaa7feadc -error InvalidValue(); -// 0x888b2f09 -error L1TokenDeploymentWithZeroChainId(bytes32 assetId); -// 0xa4f62e33 -error L2BridgeNotDeployed(uint256 chainId); -// 0xff8811ff -error L2BridgeNotSet(uint256 chainId); -// 0xcb5e4247 -error L2BytecodeHashMismatch(bytes32 expected, bytes32 provided); // 0xfb5c22e6 error L2TimestampTooBig(); // 0xd2c011d6 error L2UpgradeNonceNotEqualToNewProtocolVersion(uint256 nonce, uint256 protocolVersion); // 0x97e1359e error L2WithdrawalMessageWrongLength(uint256 messageLen); -// 0x32eb8b2f -error LegacyMethodIsSupportedOnlyForEra(); // 0xe37d2c02 error LengthIsNotDivisibleBy32(uint256 length); // 0x1b6825bb error LogAlreadyProcessed(uint8); -// 0x43e266b0 +// 0xcea34703 error MalformedBytecode(BytecodeError); -// 0x59170bf0 -error MalformedCalldata(); -// 0x16509b9a -error MalformedMessage(); // 0x9bb54c35 error MerkleIndexOutOfBounds(); // 0x8e23ac1a @@ -231,8 +171,6 @@ error NoCallsProvided(); error NoFunctionsForDiamondCut(); // 0xcab098d8 error NoFundsTransferred(); -// 0x92290acc -error NonEmptyBlobVersionHash(uint256 index); // 0xc21b1ab7 error NonEmptyCalldata(); // 0x536ec84b @@ -243,8 +181,6 @@ error NonIncreasingTimestamp(); error NonSequentialBatch(); // 0x0ac76f01 error NonSequentialVersion(); -// 0x4ef79e5a -error NonZeroAddress(address); // 0xdd629f86 error NotEnoughGas(); // 0xdd7e3621 @@ -267,10 +203,6 @@ error PatchCantSetUpgradeTxn(); error PatchUpgradeCantSetBootloader(); // 0x559cc34e error PatchUpgradeCantSetDefaultAccount(); -// 0x8d5851de -error PointEvalCallFailed(bytes); -// 0x4daa985d -error PointEvalFailed(bytes); // 0x9b48e060 error PreviousOperationNotExecuted(); // 0x5c598b60 @@ -293,12 +225,8 @@ error ProtocolVersionMinorDeltaTooBig(uint256 limit, uint256 proposed); error ProtocolVersionTooSmall(); // 0x53dee67b error PubdataCommitmentsEmpty(); -// 0x7734c31a -error PubdataCommitmentsTooBig(); // 0x959f26fb error PubdataGreaterThanLimit(uint256 limit, uint256 length); -// 0x2a4a14df -error PubdataPerBatchIsLessThanTxn(); // 0x63c36549 error QueueIsEmpty(); // 0xab143c06 @@ -309,25 +237,19 @@ error RemoveFunctionFacetAddressNotZero(address facet); error RemoveFunctionFacetAddressZero(); // 0x3580370c error ReplaceFunctionFacetAddressZero(); -// 0xdab52f4b -error RevertedBatchBeforeNewBatch(); // 0x9a67c1cb error RevertedBatchNotAfterNewLastBatch(); // 0xd3b6535b error SelectorsMustAllHaveSameFreezability(); -// 0x7774d2f9 +// 0xd7a6b5e6 error SharedBridgeValueNotSet(SharedBridgeKey); -// 0xc1d9246c -error SharedBridgeBalanceMismatch(); // 0x856d5b77 error SharedBridgeNotSet(); -// 0xcac5fc40 -error SharedBridgeValueAlreadySet(SharedBridgeKey); // 0xdf3a8fdd error SlotOccupied(); -// 0xd0bc70cf +// 0xec273439 error CTMAlreadyRegistered(); -// 0x09865e10 +// 0xc630ef3c error CTMNotRegistered(); // 0xae43b424 error SystemLogsSizeTooBig(); @@ -335,16 +257,10 @@ error SystemLogsSizeTooBig(); error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp); // 0x2d50c33b error TimestampError(); -// 0x4f4b634e -error TokenAlreadyRegistered(address token); -// 0xddef98d7 -error TokenNotRegistered(address token); // 0x06439c6b error TokenNotSupported(address token); // 0x23830e28 error TokensWithFeesNotSupported(); -// 0xf640f0e5 -error TooManyBlobs(); // 0x76da24b9 error TooManyFactoryDeps(); // 0xf0b4e88f @@ -359,49 +275,35 @@ error TxnBodyGasLimitNotEnoughGas(); error Unauthorized(address caller); // 0xe52478c7 error UndefinedDiamondCutAction(); -// 0x07218375 -error UnexpectedNumberOfFactoryDeps(); // 0x6aa39880 error UnexpectedSystemLog(uint256 logKey); -// -error UnimplementedMessage(string); // 0xf093c2e5 error UpgradeBatchNumberIsNotZero(); // 0x084a1449 error UnsupportedEncodingVersion(); -// -error UnsupportedPaymasterFlow(); // 0x47b3b145 error ValidateTxnNotEnoughGas(); // 0x626ade30 error ValueMismatch(uint256 expected, uint256 actual); // 0xe1022469 error VerifiedBatchesExceedsCommittedBatches(); -// 0x2dbdba00 -error VerifyProofCommittedVerifiedMismatch(); // 0xae899454 error WithdrawalAlreadyFinalized(); -// 0x27fcd9d1 -error WithdrawalFailed(); // 0x750b219c error WithdrawFailed(); // 0x15e8e429 error WrongMagicValue(uint256 expectedMagicValue, uint256 providedMagicValue); // 0xd92e233d error ZeroAddress(); -// 0x669567ea -error ZeroBalance(); // 0xc84885d4 error ZeroChainId(); -// 0x520aa59c -error PubdataIsEmpty(); // 0x99d8fec9 error EmptyData(); -// 0xc99a8360 +// 0xf3dd1b9c error UnsupportedCommitBatchEncoding(uint8 version); -// 0xe167e4a6 +// 0xf338f830 error UnsupportedProofBatchEncoding(uint8 version); -// 0xe8e3f6f4 +// 0x14d2ed8a error UnsupportedExecuteBatchEncoding(uint8 version); // 0xd7d93e1f error IncorrectBatchBounds( @@ -412,12 +314,48 @@ error IncorrectBatchBounds( ); // 0x64107968 error AssetHandlerNotRegistered(bytes32 assetId); -// 0x10f30e75 -error NotBridgehub(address addr); -// 0x2554babc -error InvalidAddress(address expected, address actual); +// 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(); +// 0x6e3331f5 +error IncorrectPricingMode(); +// 0xd0266e26 +error NotSettlementLayer(); +// 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); enum SharedBridgeKey { PostUpgradeFirstBatch, diff --git a/l1-contracts/contracts/common/L2ContractAddresses.sol b/l1-contracts/contracts/common/L2ContractAddresses.sol index a8fba013c..2f656acd9 100644 --- a/l1-contracts/contracts/common/L2ContractAddresses.sol +++ b/l1-contracts/contracts/common/L2ContractAddresses.sol @@ -38,7 +38,7 @@ address constant L2_COMPLEX_UPGRADER_ADDR = address(0x800f); /// @dev The address used to execute the genesis upgrade address constant L2_GENESIS_UPGRADE_ADDR = address(0x10001); -/// @dev The address of the L2 bridge hub system contract, used to start L2<>L2 transactions +/// @dev The address of the L2 bridge hub system contract, used to start L1->L2 transactions address constant L2_BRIDGEHUB_ADDR = address(0x10002); /// @dev the address of the l2 asset router. @@ -69,15 +69,12 @@ interface IL2Messenger { /// 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(0x10004); -/// @dev the address of the l2 asse3t router. +/// @dev the address of the l2 asset router. address constant L2_MESSAGE_ROOT_ADDR = address(0x10005); /// @dev the offset for the system contracts uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000; // 2^15 -/// @dev the address of the deployer system contract -address constant DEPLOYER_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x06); - /// @dev the address of the l2 messenger system contract IL2Messenger constant L2_MESSENGER = IL2Messenger(address(SYSTEM_CONTRACTS_OFFSET + 0x08)); diff --git a/l1-contracts/contracts/common/libraries/DataEncoding.sol b/l1-contracts/contracts/common/libraries/DataEncoding.sol index 9df83d67a..f4aaff8a0 100644 --- a/l1-contracts/contracts/common/libraries/DataEncoding.sol +++ b/l1-contracts/contracts/common/libraries/DataEncoding.sol @@ -15,27 +15,27 @@ import {UnsupportedEncodingVersion} from "../L1ContractErrors.sol"; library DataEncoding { /// @notice Abi.encodes the data required for bridgeMint on remote chain. /// @param _originalCaller The address which initiated the transfer. - /// @param _l2Receiver The address which to receive tokens on remote chain. - /// @param _l1Token The transferred token address. + /// @param _remoteReceiver The address which to receive tokens on remote chain. + /// @param _originToken The transferred token address. /// @param _amount The amount of token to be transferred. /// @param _erc20Metadata The transferred token metadata. /// @return The encoded bridgeMint data function encodeBridgeMintData( address _originalCaller, - address _l2Receiver, - address _l1Token, + address _remoteReceiver, + address _originToken, uint256 _amount, bytes memory _erc20Metadata ) internal pure returns (bytes memory) { // solhint-disable-next-line func-named-parameters - return abi.encode(_originalCaller, _l2Receiver, _l1Token, _amount, _erc20Metadata); + return abi.encode(_originalCaller, _remoteReceiver, _originToken, _amount, _erc20Metadata); } /// @notice Function decoding transfer data previously encoded with this library. /// @param _bridgeMintData The encoded bridgeMint data /// @return _originalCaller The address which initiated the transfer. - /// @return _l2Receiver The address which to receive tokens on remote chain. - /// @return _parsedL1Token The transferred token address. + /// @return _remoteReceiver The address which to receive tokens on remote chain. + /// @return _parsedOriginToken The transferred token address. /// @return _amount The amount of token to be transferred. /// @return _erc20Metadata The transferred token metadata. function decodeBridgeMintData( @@ -45,13 +45,13 @@ library DataEncoding { pure returns ( address _originalCaller, - address _l2Receiver, - address _parsedL1Token, + address _remoteReceiver, + address _parsedOriginToken, uint256 _amount, bytes memory _erc20Metadata ) { - (_originalCaller, _l2Receiver, _parsedL1Token, _amount, _erc20Metadata) = abi.decode( + (_originalCaller, _remoteReceiver, _parsedOriginToken, _amount, _erc20Metadata) = abi.decode( _bridgeMintData, (address, address, address, uint256, bytes) ); @@ -68,11 +68,11 @@ library DataEncoding { /// @notice Encodes the asset data by combining chain id, asset deployment tracker and asset data. /// @param _chainId The id of the chain token is native to. - /// @param _tokenAaddress The address of token that has to be encoded (asset data is the address itself). + /// @param _tokenAddress The address of token that has to be encoded (asset data is the address itself). /// @param _sender The asset deployment tracker address. /// @return The encoded asset data. - function encodeAssetId(uint256 _chainId, address _tokenAaddress, address _sender) internal pure returns (bytes32) { - return keccak256(abi.encode(_chainId, _sender, _tokenAaddress)); + function encodeAssetId(uint256 _chainId, address _tokenAddress, address _sender) internal pure returns (bytes32) { + return keccak256(abi.encode(_chainId, _sender, _tokenAddress)); } /// @notice Encodes the asset data by combining chain id, NTV as asset deployment tracker and asset data. @@ -83,7 +83,7 @@ library DataEncoding { return keccak256(abi.encode(_chainId, L2_NATIVE_TOKEN_VAULT_ADDR, _assetData)); } - /// @notice Encodes the asset data by combining chain id, NTV as asset deployment tracker and asset data. + /// @notice Encodes the asset data by combining chain id, NTV as asset deployment tracker and token address. /// @param _chainId The id of the chain token is native to. /// @param _tokenAddress The address of token that has to be encoded (asset data is the address itself). /// @return The encoded asset data. @@ -108,7 +108,7 @@ library DataEncoding { if (_encodingVersion == LEGACY_ENCODING_VERSION) { address tokenAddress = INativeTokenVault(_nativeTokenVault).tokenAddress(_assetId); (uint256 depositAmount, ) = abi.decode(_transferData, (uint256, address)); - txDataHash = keccak256(abi.encode(_originalCaller, tokenAddress, depositAmount)); + txDataHash = encodeLegacyTxDataHash(_originalCaller, tokenAddress, depositAmount); } else if (_encodingVersion == NEW_ENCODING_VERSION) { // Similarly to calldata, the txDataHash is collision-resistant. // In the legacy data hash, the first encoded variable was the address, which is padded with zeros during `abi.encode`. @@ -120,12 +120,25 @@ library DataEncoding { } } + /// @notice Encodes the legacy transaction data hash. + /// @dev the encoding strats with 0t + /// @param _originalCaller The address of the entity that initiated the deposit. + /// @param _l1Token The address of the L1 token. + /// @param _amount The amount of the L1 token. + /// @return txDataHash The resulting encoded transaction data hash. + function encodeLegacyTxDataHash( + address _originalCaller, + address _l1Token, + uint256 _amount + ) internal pure returns (bytes32) { + return keccak256(abi.encode(_originalCaller, _l1Token, _amount)); + } + /// @notice Decodes the token data by combining chain id, asset deployment tracker and asset data. function decodeTokenData( bytes calldata _tokenData ) internal pure returns (uint256 chainId, bytes memory name, bytes memory symbol, bytes memory decimals) { bytes1 encodingVersion = _tokenData[0]; - // kl todo check correct if (encodingVersion == LEGACY_ENCODING_VERSION) { (name, symbol, decimals) = abi.decode(_tokenData, (bytes, bytes, bytes)); } else if (encodingVersion == NEW_ENCODING_VERSION) { @@ -135,7 +148,8 @@ library DataEncoding { } } - /// @notice Encodes the token data by combining chain id, asset deployment tracker and asset data. + /// @notice Encodes the token data by combining chain id, and its metadata. + /// @dev Note that all the metadata of the token is expected to be ABI encoded. /// @param _chainId The id of the chain token is native to. /// @param _name The name of the token. /// @param _symbol The symbol of the token. diff --git a/l1-contracts/contracts/common/libraries/FullMerkle.sol b/l1-contracts/contracts/common/libraries/FullMerkle.sol index d39ccde48..4dbab106b 100644 --- a/l1-contracts/contracts/common/libraries/FullMerkle.sol +++ b/l1-contracts/contracts/common/libraries/FullMerkle.sol @@ -2,10 +2,9 @@ pragma solidity 0.8.24; -// solhint-disable reason-string, gas-custom-errors - import {UncheckedMath} from "../../common/libraries/UncheckedMath.sol"; import {Merkle} from "./Merkle.sol"; +import {MerkleWrongIndex, MerkleWrongLength} from "../L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -20,11 +19,9 @@ library FullMerkle { } /** - * @dev Initialize a {Bytes32PushTree} using {Merkle.efficientHash} to hash internal nodes. + * @dev Initialize a {FullTree} using {Merkle.efficientHash} to hash internal nodes. * The capacity of the tree (i.e. number of leaves) is set to `2**levels`. * - * Calling this function on MerkleTree that was already setup and used will reset it to a blank state. - * * 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. * @param zero The zero value to be used in the tree. @@ -74,9 +71,10 @@ library FullMerkle { * @param _itemHash The new hash of the leaf. */ function updateLeaf(FullTree storage self, uint256 _index, bytes32 _itemHash) internal returns (bytes32) { - // solhint-disable-next-line gas-custom-errors uint256 maxNodeNumber = self._leafNumber - 1; - require(_index <= maxNodeNumber, "FMT, wrong index"); + if (_index > maxNodeNumber) { + revert MerkleWrongIndex(_index, maxNodeNumber); + } self._nodes[0][_index] = _itemHash; bytes32 currentHash = _itemHash; for (uint256 i; i < self._height; i = i.uncheckedInc()) { @@ -100,8 +98,9 @@ library FullMerkle { * @param _newLeaves The new leaves to be added to the tree. */ function updateAllLeaves(FullTree storage self, bytes32[] memory _newLeaves) internal returns (bytes32) { - // solhint-disable-next-line gas-custom-errors - require(_newLeaves.length == self._leafNumber, "FMT, wrong length"); + if (_newLeaves.length != self._leafNumber) { + revert MerkleWrongLength(_newLeaves.length, self._leafNumber); + } return updateAllNodesAtHeight(self, 0, _newLeaves); } diff --git a/l1-contracts/contracts/common/libraries/L2ContractHelper.sol b/l1-contracts/contracts/common/libraries/L2ContractHelper.sol index 2d1a26c1f..f57db8444 100644 --- a/l1-contracts/contracts/common/libraries/L2ContractHelper.sol +++ b/l1-contracts/contracts/common/libraries/L2ContractHelper.sol @@ -85,6 +85,35 @@ library L2ContractHelper { hashedBytecode = hashedBytecode | bytes32(bytecodeLenInWords << 224); } + /// @notice Validate the bytecode format and calculate its hash. + /// @param _bytecode The bytecode to hash. + /// @return hashedBytecode The 32-byte hash of the bytecode. + /// Note: The function reverts the execution if the bytecode has non expected format: + /// - Bytecode bytes length is not a multiple of 32 + /// - Bytecode bytes length is not less than 2^21 bytes (2^16 words) + /// - Bytecode words length is not odd + function hashL2BytecodeCalldata(bytes calldata _bytecode) internal pure returns (bytes32 hashedBytecode) { + // Note that the length of the bytecode must be provided in 32-byte words. + if (_bytecode.length % 32 != 0) { + revert LengthIsNotDivisibleBy32(_bytecode.length); + } + + uint256 bytecodeLenInWords = _bytecode.length / 32; + // bytecode length must be less than 2^16 words + if (bytecodeLenInWords >= 2 ** 16) { + revert MalformedBytecode(BytecodeError.NumberOfWords); + } + // bytecode length in words must be odd + if (bytecodeLenInWords % 2 == 0) { + revert MalformedBytecode(BytecodeError.WordsMustBeOdd); + } + hashedBytecode = sha256(_bytecode) & 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; + // Setting the version of the hash + hashedBytecode = (hashedBytecode | bytes32(uint256(1 << 248))); + // Setting the length + hashedBytecode = hashedBytecode | bytes32(bytecodeLenInWords << 224); + } + /// @notice Validates the format of the given bytecode hash. /// @dev Due to the specification of the L2 bytecode hash, not every 32 bytes could be a legit bytecode hash. /// @dev The function reverts on invalid bytecode hash format. diff --git a/l1-contracts/contracts/common/libraries/Merkle.sol b/l1-contracts/contracts/common/libraries/Merkle.sol index 66db8ea75..457d6342d 100644 --- a/l1-contracts/contracts/common/libraries/Merkle.sol +++ b/l1-contracts/contracts/common/libraries/Merkle.sol @@ -2,10 +2,8 @@ // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; -// solhint-disable gas-custom-errors - import {UncheckedMath} from "../../common/libraries/UncheckedMath.sol"; -import {MerklePathEmpty, MerklePathOutOfBounds, MerkleIndexOutOfBounds} from "../../common/L1ContractErrors.sol"; +import {MerklePathEmpty, MerklePathOutOfBounds, MerkleIndexOutOfBounds, MerklePathLengthMismatch, MerkleNothingToProve, MerkleIndexOrHeightMismatch} from "../../common/L1ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -14,6 +12,7 @@ library Merkle { /// @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 @@ -76,7 +75,9 @@ library Merkle { bytes32[] memory _itemHashes ) internal pure returns (bytes32) { uint256 pathLength = _startPath.length; - require(pathLength == _endPath.length, "Merkle: path length mismatch"); + if (pathLength != _endPath.length) { + revert MerklePathLengthMismatch(pathLength, _endPath.length); + } if (pathLength >= 256) { revert MerklePathOutOfBounds(); } @@ -85,8 +86,12 @@ library Merkle { if (pathLength == 0 && (_startIndex != 0 || levelLen != 1)) { revert MerklePathEmpty(); } - require(levelLen > 0, "Merkle: nothing to prove"); - require(_startIndex + levelLen <= (1 << pathLength), "Merkle: index/height mismatch"); + if (levelLen == 0) { + revert MerkleNothingToProve(); + } + if (_startIndex + levelLen > (1 << pathLength)) { + revert MerkleIndexOrHeightMismatch(); + } bytes32[] memory itemHashes = _itemHashes; for (uint256 level; level < pathLength; level = level.uncheckedInc()) { diff --git a/l1-contracts/contracts/common/libraries/SystemContractsCaller.sol b/l1-contracts/contracts/common/libraries/SystemContractsCaller.sol index b6bf0c54a..30dbf3a81 100644 --- a/l1-contracts/contracts/common/libraries/SystemContractsCaller.sol +++ b/l1-contracts/contracts/common/libraries/SystemContractsCaller.sol @@ -48,7 +48,7 @@ library SystemContractsCaller { assembly { dataStart := add(data, 0x20) } - uint32 dataLength = uint32(Utils.safeCastToU32(data.length)); + uint32 dataLength = Utils.safeCastToU32(data.length); uint256 farCallAbi = getFarCallABI({ dataOffset: 0, diff --git a/l1-contracts/contracts/common/libraries/UnsafeBytes.sol b/l1-contracts/contracts/common/libraries/UnsafeBytes.sol index 4edf94004..e2680d9e0 100644 --- a/l1-contracts/contracts/common/libraries/UnsafeBytes.sol +++ b/l1-contracts/contracts/common/libraries/UnsafeBytes.sol @@ -30,13 +30,6 @@ library UnsafeBytes { } } - function readUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 result, uint256 offset) { - assembly { - offset := add(_start, 16) - result := mload(add(_bytes, offset)) - } - } - function readUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256 result, uint256 offset) { assembly { offset := add(_start, 32) diff --git a/l1-contracts/contracts/dev-contracts/DummyRestriction.sol b/l1-contracts/contracts/dev-contracts/DummyRestriction.sol new file mode 100644 index 000000000..8ce2680db --- /dev/null +++ b/l1-contracts/contracts/dev-contracts/DummyRestriction.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {Call} from "../governance/Common.sol"; +import {IRestriction, RESTRICTION_MAGIC} from "../governance/restriction/IRestriction.sol"; + +/// @title Restriction contract interface +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +contract DummyRestriction is IRestriction { + bool immutable correctMagic; + + constructor(bool useCorrectMagic) { + correctMagic = useCorrectMagic; + } + + /// @notice A method used to check that the contract supports this interface. + /// @return Returns the `RESTRICTION_MAGIC` + function getSupportsRestrictionMagic() external view returns (bytes32) { + if (correctMagic) { + return RESTRICTION_MAGIC; + } else { + // Invalid magic + return bytes32(0); + } + } + + /// @notice Ensures that the invoker has the required role to call the function. + /// @param _call The call data. + /// @param _invoker The address of the invoker. + function validateCall(Call calldata _call, address _invoker) external view virtual { + // nothing + } +} diff --git a/l1-contracts/contracts/dev-contracts/WETH9.sol b/l1-contracts/contracts/dev-contracts/WETH9.sol index 5ab311b13..fccb38b8d 100644 --- a/l1-contracts/contracts/dev-contracts/WETH9.sol +++ b/l1-contracts/contracts/dev-contracts/WETH9.sol @@ -60,7 +60,6 @@ contract WETH9 { function transferFrom(address src, address dst, uint256 wad) public returns (bool) { require(balanceOf[src] >= wad, "weth9, 2"); - if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { require(allowance[src][msg.sender] >= wad, "weth9, 3"); allowance[src][msg.sender] -= wad; diff --git a/l1-contracts/contracts/dev-contracts/test/AdminFacetTest.sol b/l1-contracts/contracts/dev-contracts/test/AdminFacetTest.sol index bf5ef724f..ae8825eba 100644 --- a/l1-contracts/contracts/dev-contracts/test/AdminFacetTest.sol +++ b/l1-contracts/contracts/dev-contracts/test/AdminFacetTest.sol @@ -3,12 +3,13 @@ pragma solidity 0.8.24; import {AdminFacet} from "../../state-transition/chain-deps/facets/Admin.sol"; +import {RollupDAManager} from "../../state-transition/data-availability/RollupDAManager.sol"; contract AdminFacetTest is AdminFacet { // add this to be excluded from coverage report function test() internal virtual {} - constructor(uint256 _l1ChainId) AdminFacet(_l1ChainId) { + constructor(uint256 _l1ChainId) AdminFacet(_l1ChainId, RollupDAManager(address(0))) { s.admin = msg.sender; s.chainTypeManager = msg.sender; } diff --git a/l1-contracts/contracts/dev-contracts/test/CustomUpgradeTest.sol b/l1-contracts/contracts/dev-contracts/test/CustomUpgradeTest.sol index 7055ce557..e20d44863 100644 --- a/l1-contracts/contracts/dev-contracts/test/CustomUpgradeTest.sol +++ b/l1-contracts/contracts/dev-contracts/test/CustomUpgradeTest.sol @@ -25,7 +25,7 @@ contract CustomUpgradeTest is BaseZkSyncUpgrade { /// upgrade. function _postUpgrade(bytes calldata _customCallDataForUpgrade) internal override {} - /// @notice The main function that will be called by the upgrade proxy. + /// @notice The main function that will be delegate-called by the chain. /// @param _proposedUpgrade The upgrade to be executed. function upgrade(ProposedUpgrade calldata _proposedUpgrade) public override returns (bytes32) { (uint32 newMinorVersion, bool isPatchOnly) = _setNewProtocolVersion(_proposedUpgrade.newProtocolVersion); @@ -34,12 +34,7 @@ contract CustomUpgradeTest is BaseZkSyncUpgrade { _setBaseSystemContracts(_proposedUpgrade.bootloaderHash, _proposedUpgrade.defaultAccountHash, isPatchOnly); bytes32 txHash; - txHash = _setL2SystemContractUpgrade( - _proposedUpgrade.l2ProtocolUpgradeTx, - _proposedUpgrade.factoryDeps, - newMinorVersion, - isPatchOnly - ); + txHash = _setL2SystemContractUpgrade(_proposedUpgrade.l2ProtocolUpgradeTx, newMinorVersion, isPatchOnly); _postUpgrade(_proposedUpgrade.postUpgradeCalldata); diff --git a/l1-contracts/contracts/dev-contracts/test/DummyBridgehubSetter.sol b/l1-contracts/contracts/dev-contracts/test/DummyBridgehubSetter.sol index 8ae0404e7..a84f476f1 100644 --- a/l1-contracts/contracts/dev-contracts/test/DummyBridgehubSetter.sol +++ b/l1-contracts/contracts/dev-contracts/test/DummyBridgehubSetter.sol @@ -16,7 +16,7 @@ contract DummyBridgehubSetter is Bridgehub { ) Bridgehub(_l1ChainId, _owner, _maxNumberOfZKChains) {} function setZKChain(uint256 _chainId, address _zkChain) external { - _registerNewZKChain(_chainId, _zkChain); + _registerNewZKChain(_chainId, _zkChain, true); } function setCTM(uint256 _chainId, address _ctm) external { diff --git a/l1-contracts/contracts/dev-contracts/test/DummyChainTypeManagerForValidatorTimelock.sol b/l1-contracts/contracts/dev-contracts/test/DummyChainTypeManagerForValidatorTimelock.sol index 8e876abb2..75c8cd121 100644 --- a/l1-contracts/contracts/dev-contracts/test/DummyChainTypeManagerForValidatorTimelock.sol +++ b/l1-contracts/contracts/dev-contracts/test/DummyChainTypeManagerForValidatorTimelock.sol @@ -20,10 +20,14 @@ contract DummyChainTypeManagerForValidatorTimelock { return chainAdmin; } - function getZKChain(uint256) external view returns (address) { + function getZKChain(uint256) public view returns (address) { return zkChainAddress; } + function getHyperchain(uint256 _chainId) external view returns (address) { + return getZKChain(_chainId); + } + function setZKChain(uint256, address _zkChain) external { zkChainAddress = _zkChain; } diff --git a/l1-contracts/contracts/dev-contracts/test/DummySharedBridge.sol b/l1-contracts/contracts/dev-contracts/test/DummySharedBridge.sol index c75ec4530..0033fac3c 100644 --- a/l1-contracts/contracts/dev-contracts/test/DummySharedBridge.sol +++ b/l1-contracts/contracts/dev-contracts/test/DummySharedBridge.sol @@ -10,7 +10,6 @@ import {TWO_BRIDGES_MAGIC_VALUE, ETH_TOKEN_ADDRESS} from "../../common/Config.so import {IL1NativeTokenVault} from "../../bridge/ntv/L1NativeTokenVault.sol"; import {L2_NATIVE_TOKEN_VAULT_ADDR} from "../../common/L2ContractAddresses.sol"; import {SafeERC20} from "@openzeppelin/contracts-v4/token/ERC20/utils/SafeERC20.sol"; -import {IL2Bridge} from "../../bridge/interfaces/IL2Bridge.sol"; import {IL2SharedBridgeLegacy} from "../../bridge/interfaces/IL2SharedBridgeLegacy.sol"; import {IL2SharedBridgeLegacyFunctions} from "../../bridge/interfaces/IL2SharedBridgeLegacyFunctions.sol"; diff --git a/l1-contracts/contracts/dev-contracts/test/ExecutorProvingTest.sol b/l1-contracts/contracts/dev-contracts/test/ExecutorProvingTest.sol index 5794dfbe6..3df69577f 100644 --- a/l1-contracts/contracts/dev-contracts/test/ExecutorProvingTest.sol +++ b/l1-contracts/contracts/dev-contracts/test/ExecutorProvingTest.sol @@ -8,6 +8,8 @@ import {LogProcessingOutput} from "../../state-transition/chain-interfaces/IExec import {LogProcessingOutput} from "../../state-transition/chain-interfaces/IExecutor.sol"; contract ExecutorProvingTest is ExecutorFacet { + constructor() ExecutorFacet(block.chainid) {} + function getBatchProofPublicInput( bytes32 _prevBatchCommitment, bytes32 _currentBatchCommitment diff --git a/l1-contracts/contracts/dev-contracts/test/L2NativeTokenVaultDev.sol b/l1-contracts/contracts/dev-contracts/test/L2NativeTokenVaultDev.sol index fc1991503..896197fea 100644 --- a/l1-contracts/contracts/dev-contracts/test/L2NativeTokenVaultDev.sol +++ b/l1-contracts/contracts/dev-contracts/test/L2NativeTokenVaultDev.sol @@ -59,14 +59,14 @@ contract L2NativeTokenVaultDev is L2NativeTokenVault { tokenBeacon.transferOwnership(owner()); bridgedTokenBeacon = IBeacon(address(tokenBeacon)); - emit L2TokenBeaconUpdated(address(bridgedTokenBeacon), l2TokenProxyBytecodeHash); + emit L2TokenBeaconUpdated(address(bridgedTokenBeacon), L2_TOKEN_PROXY_BYTECODE_HASH); } function test() external pure { // test } - function _deployBeaconProxy(bytes32 _salt) internal virtual override returns (BeaconProxy proxy) { + function _deployBeaconProxy(bytes32 _salt, uint256) internal virtual override returns (BeaconProxy proxy) { // Use CREATE2 to deploy the BeaconProxy address proxyAddress = Create2.deploy( 0, diff --git a/l1-contracts/contracts/dev-contracts/test/TestExecutor.sol b/l1-contracts/contracts/dev-contracts/test/TestExecutor.sol index 10b907aec..55881eeec 100644 --- a/l1-contracts/contracts/dev-contracts/test/TestExecutor.sol +++ b/l1-contracts/contracts/dev-contracts/test/TestExecutor.sol @@ -5,6 +5,7 @@ import {ExecutorFacet} from "../../state-transition/chain-deps/facets/Executor.s pragma solidity 0.8.24; contract TestExecutor is ExecutorFacet { + constructor() ExecutorFacet(block.chainid) {} function setPriorityTreeStartIndex(uint256 _startIndex) external { s.priorityTree.startIndex = _startIndex; } diff --git a/l1-contracts/contracts/governance/AccessControlRestriction.sol b/l1-contracts/contracts/governance/AccessControlRestriction.sol index 3fc67f875..6052d1e6a 100644 --- a/l1-contracts/contracts/governance/AccessControlRestriction.sol +++ b/l1-contracts/contracts/governance/AccessControlRestriction.sol @@ -2,23 +2,23 @@ pragma solidity 0.8.24; -import {AccessToFallbackDenied, AccessToFunctionDenied} from "../common/L1ContractErrors.sol"; +import {AccessToFallbackDenied, AccessToFunctionDenied, ZeroAddress} from "../common/L1ContractErrors.sol"; import {IAccessControlRestriction} from "./IAccessControlRestriction.sol"; import {AccessControlDefaultAdminRules} from "@openzeppelin/contracts-v4/access/AccessControlDefaultAdminRules.sol"; -import {IRestriction} from "./IRestriction.sol"; +import {Restriction} from "./restriction/Restriction.sol"; import {Call} from "./Common.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev /// @notice The Restriction that is designed to provide the access control logic for the `ChainAdmin` contract. -/// @dev It inherits from `AccessControlDefaultAdminRules` without overriding `_setRoleAdmin` functionaity. In other +/// @dev It inherits from `AccessControlDefaultAdminRules` without overriding `_setRoleAdmin` functionality. In other /// words, the `DEFAULT_ADMIN_ROLE` is the only role that can manage roles. This is done for simplicity. /// @dev An instance of this restriction should be deployed separately for each `ChainAdmin` contract. /// @dev IMPORTANT: this function does not validate the ability of the invoker to use `msg.value`. Thus, /// either all callers with access to functions should be trusted to not steal ETH from the `ChainAdmin` account -/// or not ETH should be passively stored in `ChainAdmin` account. -contract AccessControlRestriction is IRestriction, IAccessControlRestriction, AccessControlDefaultAdminRules { - /// @notice Required roles to call a specific functions. +/// or no ETH should be passively stored in `ChainAdmin` account. +contract AccessControlRestriction is Restriction, IAccessControlRestriction, AccessControlDefaultAdminRules { + /// @notice Required roles to call a specific function. /// @dev Note, that the role 0 means the `DEFAULT_ADMIN_ROLE` from the `AccessControlDefaultAdminRules` contract. mapping(address target => mapping(bytes4 selector => bytes32 requiredRole)) public requiredRoles; @@ -39,6 +39,9 @@ contract AccessControlRestriction is IRestriction, IAccessControlRestriction, Ac bytes4 _selector, bytes32 _requiredRole ) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (_target == address(0)) { + revert ZeroAddress(); + } requiredRoles[_target][_selector] = _requiredRole; emit RoleSet(_target, _selector, _requiredRole); @@ -48,13 +51,16 @@ contract AccessControlRestriction is IRestriction, IAccessControlRestriction, Ac /// @param _target The address of the contract. /// @param _requiredRole The required role. function setRequiredRoleForFallback(address _target, bytes32 _requiredRole) external onlyRole(DEFAULT_ADMIN_ROLE) { + if (_target == address(0)) { + revert ZeroAddress(); + } requiredRolesForFallback[_target] = _requiredRole; emit FallbackRoleSet(_target, _requiredRole); } - /// @inheritdoc IRestriction - function validateCall(Call calldata _call, address _invoker) external view { + /// @inheritdoc Restriction + function validateCall(Call calldata _call, address _invoker) external view override { // Note, that since `DEFAULT_ADMIN_ROLE` is 0 and the default storage value for the // `requiredRoles` and `requiredRolesForFallback` is 0, the default admin is by default a required // role for all the functions. diff --git a/l1-contracts/contracts/governance/ChainAdmin.sol b/l1-contracts/contracts/governance/ChainAdmin.sol index f6a93146f..25a30c498 100644 --- a/l1-contracts/contracts/governance/ChainAdmin.sol +++ b/l1-contracts/contracts/governance/ChainAdmin.sol @@ -6,7 +6,8 @@ pragma solidity 0.8.24; import {NoCallsProvided, OnlySelfAllowed, RestrictionWasNotPresent, RestrictionWasAlreadyPresent} from "../common/L1ContractErrors.sol"; import {IChainAdmin} from "./IChainAdmin.sol"; -import {IRestriction} from "./IRestriction.sol"; +import {Restriction} from "./restriction/Restriction.sol"; +import {RestrictionValidator} from "./restriction/RestrictionValidator.sol"; import {Call} from "./Common.sol"; import {EnumerableSet} from "@openzeppelin/contracts-v4/utils/structs/EnumerableSet.sol"; @@ -15,11 +16,19 @@ import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev /// @notice The contract is designed to hold the `admin` role in ZKSync Chain (State Transition) contracts. -/// The owner of the contract can perform any external calls and also save the information needed for -/// the blockchain node to accept the protocol upgrade. +/// @dev Note, that it does not implement any form of access control by default, but instead utilizes +/// so called "restrictions": contracts that implement the `IRestriction` interface and ensure that +/// particular restrictions are ensured for the contract, including access control, security invariants, etc. contract ChainAdmin is IChainAdmin, ReentrancyGuard { using EnumerableSet for EnumerableSet.AddressSet; + /// @notice Mapping of protocol versions to their expected upgrade timestamps. + /// @dev Needed for the offchain node administration to know when to start building batches with the new protocol version. + mapping(uint256 protocolVersion => uint256 upgradeTimestamp) public protocolVersionToUpgradeTimestamp; + + /// @notice The set of active restrictions. + EnumerableSet.AddressSet internal activeRestrictions; + /// @notice Ensures that only the `ChainAdmin` contract itself can call the function. /// @dev All functions that require access-control should use `onlySelf` modifier, while the access control logic /// should be implemented in the restriction contracts. @@ -38,13 +47,6 @@ contract ChainAdmin is IChainAdmin, ReentrancyGuard { } } - /// @notice Mapping of protocol versions to their expected upgrade timestamps. - /// @dev Needed for the offchain node administration to know when to start building batches with the new protocol version. - mapping(uint256 protocolVersion => uint256 upgradeTimestamp) public protocolVersionToUpgradeTimestamp; - - /// @notice The set of active restrictions. - EnumerableSet.AddressSet internal activeRestrictions; - /// @notice Returns the list of active restrictions. function getRestrictions() public view returns (address[] memory) { return activeRestrictions.values(); @@ -107,19 +109,21 @@ contract ChainAdmin is IChainAdmin, ReentrancyGuard { /// @notice Function that returns the current admin can perform the call. /// @dev By default it always returns true, but can be overridden in derived contracts. - function _validateCall(Call calldata _call) internal view { + function _validateCall(Call calldata _call) private view { address[] memory restrictions = getRestrictions(); unchecked { for (uint256 i = 0; i < restrictions.length; ++i) { - IRestriction(restrictions[i]).validateCall(_call, msg.sender); + Restriction(restrictions[i]).validateCall(_call, msg.sender); } } } /// @notice Adds a new restriction to the active restrictions set. /// @param _restriction The address of the restriction contract to be added. - function _addRestriction(address _restriction) internal { + function _addRestriction(address _restriction) private { + RestrictionValidator.validateRestriction(_restriction); + if (!activeRestrictions.add(_restriction)) { revert RestrictionWasAlreadyPresent(_restriction); } diff --git a/l1-contracts/contracts/governance/L2AdminFactory.sol b/l1-contracts/contracts/governance/L2AdminFactory.sol index d4fe4637c..c8196c616 100644 --- a/l1-contracts/contracts/governance/L2AdminFactory.sol +++ b/l1-contracts/contracts/governance/L2AdminFactory.sol @@ -3,6 +3,7 @@ pragma solidity 0.8.24; import {ChainAdmin} from "./ChainAdmin.sol"; +import {RestrictionValidator} from "./restriction/RestrictionValidator.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -14,6 +15,8 @@ import {ChainAdmin} from "./ChainAdmin.sol"; /// @dev The contract is immutable, in case the restrictions need to be changed, /// a new contract should be deployed. contract L2AdminFactory { + /// @notice Emitted when an admin is deployed on the L2. + /// @param admin The address of the newly deployed admin. event AdminDeployed(address admin); /// @dev We use storage instead of immutable variables due to the @@ -21,22 +24,42 @@ contract L2AdminFactory { address[] public requiredRestrictions; constructor(address[] memory _requiredRestrictions) { + _validateRestrctions(_requiredRestrictions); requiredRestrictions = _requiredRestrictions; } /// @notice Deploys a new L2 admin contract. /// @return admin The address of the deployed admin contract. - function deployAdmin(address[] calldata _additionalRestrictions, bytes32 _salt) external returns (address admin) { - address[] memory restrictions = new address[](requiredRestrictions.length + _additionalRestrictions.length); + // solhint-disable-next-line gas-calldata-parameters + function deployAdmin(address[] memory _additionalRestrictions, bytes32 _salt) external returns (address admin) { + // Even though the chain admin will likely perform similar checks, + // we keep those here just in case, since it is not expensive, while allowing to fail fast. + _validateRestrctions(_additionalRestrictions); uint256 cachedRequired = requiredRestrictions.length; - for (uint256 i = 0; i < cachedRequired; ++i) { - restrictions[i] = requiredRestrictions[i]; - } uint256 cachedAdditional = _additionalRestrictions.length; - for (uint256 i = 0; i < cachedAdditional; ++i) { - restrictions[requiredRestrictions.length + i] = _additionalRestrictions[i]; + address[] memory restrictions = new address[](cachedRequired + cachedAdditional); + + unchecked { + for (uint256 i = 0; i < cachedRequired; ++i) { + restrictions[i] = requiredRestrictions[i]; + } + for (uint256 i = 0; i < cachedAdditional; ++i) { + restrictions[cachedRequired + i] = _additionalRestrictions[i]; + } } admin = address(new ChainAdmin{salt: _salt}(restrictions)); } + + /// @notice Checks that the provided list of restrictions is correct. + /// @param _restrictions List of the restrictions to check. + /// @dev In case either of the restrictions is not correct, the function reverts. + function _validateRestrctions(address[] memory _restrictions) internal view { + unchecked { + uint256 length = _restrictions.length; + for (uint256 i = 0; i < length; ++i) { + RestrictionValidator.validateRestriction(_restrictions[i]); + } + } + } } diff --git a/l1-contracts/contracts/governance/PermanentRestriction.sol b/l1-contracts/contracts/governance/PermanentRestriction.sol index 153ce369e..30b586086 100644 --- a/l1-contracts/contracts/governance/PermanentRestriction.sol +++ b/l1-contracts/contracts/governance/PermanentRestriction.sol @@ -2,15 +2,15 @@ pragma solidity 0.8.24; -import {UnsupportedEncodingVersion, CallNotAllowed, ChainZeroAddress, NotAHyperchain, NotAnAdmin, RemovingPermanentRestriction, ZeroAddress, UnallowedImplementation, AlreadyWhitelisted, NotAllowed, NotBridgehub, InvalidSelector, InvalidAddress, NotEnoughGas} from "../common/L1ContractErrors.sol"; +import {CallNotAllowed, RemovingPermanentRestriction, ZeroAddress, UnallowedImplementation, AlreadyWhitelisted, NotAllowed} from "../common/L1ContractErrors.sol"; import {L2TransactionRequestTwoBridgesOuter, BridgehubBurnCTMAssetData} from "../bridgehub/IBridgehub.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; import {L2ContractHelper} from "../common/libraries/L2ContractHelper.sol"; -import {NEW_ENCODING_VERSION} from "../bridge/asset-router/IAssetRouterBase.sol"; +import {NEW_ENCODING_VERSION, IAssetRouterBase} from "../bridge/asset-router/IAssetRouterBase.sol"; import {Call} from "./Common.sol"; -import {IRestriction} from "./IRestriction.sol"; +import {Restriction} from "./restriction/Restriction.sol"; import {IChainAdmin} from "./IChainAdmin.sol"; import {IBridgehub} from "../bridgehub/IBridgehub.sol"; import {IZKChain} from "../state-transition/chain-interfaces/IZKChain.sol"; @@ -19,11 +19,6 @@ import {IAdmin} from "../state-transition/chain-interfaces/IAdmin.sol"; import {IPermanentRestriction} from "./IPermanentRestriction.sol"; -/// @dev We use try-catch to test whether some of the conditions should be checked. -/// To avoid attacks based on the 63/64 gas limitations, we ensure that each such call -/// has at least this amount. -uint256 constant MIN_GAS_FOR_FALLABLE_CALL = 5_000_000; - /// @title PermanentRestriction contract /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -31,7 +26,7 @@ uint256 constant MIN_GAS_FOR_FALLABLE_CALL = 5_000_000; /// properties are preserved forever. /// @dev To be deployed as a transparent upgradable proxy, owned by a trusted decentralized governance. /// @dev Once of the instances of such contract is to ensure that a ZkSyncHyperchain is a rollup forever. -contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2StepUpgradeable { +contract PermanentRestriction is Restriction, IPermanentRestriction, Ownable2StepUpgradeable { /// @notice The address of the Bridgehub contract. IBridgehub public immutable BRIDGE_HUB; @@ -48,18 +43,22 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St mapping(bytes allowedCalldata => bool isAllowed) public allowedCalls; /// @notice The mapping of the validated selectors. - mapping(bytes4 selector => bool isValidated) public validatedSelectors; + mapping(bytes4 selector => bool isValidated) public selectorsToValidate; /// @notice The mapping of whitelisted L2 admins. mapping(address adminAddress => bool isWhitelisted) public allowedL2Admins; constructor(IBridgehub _bridgehub, address _l2AdminFactory) { + _disableInitializers(); BRIDGE_HUB = _bridgehub; L2_ADMIN_FACTORY = _l2AdminFactory; } + /// @notice The initialization function for the proxy contract. + /// @param _initialOwner The initial owner of the permanent restriction. + /// @dev Expected to be delegatecalled by the `TransparentUpgradableProxy` + /// upon initialization. function initialize(address _initialOwner) external initializer { - // solhint-disable-next-line gas-custom-errors, reason-string if (_initialOwner == address(0)) { revert ZeroAddress(); } @@ -69,7 +68,7 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @notice Allows a certain `ChainAdmin` implementation to be used as an admin. /// @param _implementationHash The hash of the implementation code. /// @param _isAllowed The flag that indicates if the implementation is allowed. - function allowAdminImplementation(bytes32 _implementationHash, bool _isAllowed) external onlyOwner { + function setAllowedAdminImplementation(bytes32 _implementationHash, bool _isAllowed) external onlyOwner { allowedAdminImplementations[_implementationHash] = _isAllowed; emit AdminImplementationAllowed(_implementationHash, _isAllowed); @@ -87,8 +86,8 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @notice Allows a certain selector to be validated. /// @param _selector The selector of the function. /// @param _isValidated The flag that indicates if the selector is validated. - function setSelectorIsValidated(bytes4 _selector, bool _isValidated) external onlyOwner { - validatedSelectors[_selector] = _isValidated; + function setSelectorShouldBeValidated(bytes4 _selector, bool _isValidated) external onlyOwner { + selectorsToValidate[_selector] = _isValidated; emit SelectorValidationChanged(_selector, _isValidated); } @@ -115,7 +114,7 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St emit AllowL2Admin(expectedAddress); } - /// @inheritdoc IRestriction + /// @inheritdoc Restriction function validateCall( Call calldata _call, address // _invoker @@ -129,20 +128,18 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @param _call The call data. /// @dev Note that we do not need to validate the migration to the L1 layer as the admin /// is not changed in this case. - function _validateMigrationToL2(Call calldata _call) internal view { - _ensureEnoughGas(); - try this.tryGetNewAdminFromMigration(_call) returns (address admin) { + function _validateMigrationToL2(Call calldata _call) private view { + (address admin, bool isMigration) = _getNewAdminFromMigration(_call); + if (isMigration) { if (!allowedL2Admins[admin]) { revert NotAllowed(admin); } - } catch { - // It was not the migration call, so we do nothing } } /// @notice Validates the call as the chain admin /// @param _call The call data. - function _validateAsChainAdmin(Call calldata _call) internal view { + function _validateAsChainAdmin(Call calldata _call) private view { if (!_isAdminOfAChain(_call.target)) { // We only validate calls related to being an admin of a chain return; @@ -161,7 +158,7 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St return; } - if (!validatedSelectors[selector]) { + if (!selectorsToValidate[selector]) { // The selector is not validated, any data is allowed. return; } @@ -174,7 +171,7 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @notice Validates the correctness of the new admin. /// @param _call The call data. /// @dev Ensures that the admin has a whitelisted implementation and does not remove this restriction. - function _validateNewAdmin(Call calldata _call) internal view { + function _validateNewAdmin(Call calldata _call) private view { address newChainAdmin = abi.decode(_call.data[4:], (address)); bytes32 implementationCodeHash = newChainAdmin.codehash; @@ -193,7 +190,7 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @notice Validates the removal of the restriction. /// @param _call The call data. /// @dev Ensures that this restriction is not removed. - function _validateRemoveRestriction(Call calldata _call) internal view { + function _validateRemoveRestriction(Call calldata _call) private view { if (_call.target != msg.sender) { return; } @@ -212,19 +209,8 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St /// @notice Checks if the `msg.sender` is an admin of a certain ZkSyncHyperchain. /// @param _chain The address of the chain. function _isAdminOfAChain(address _chain) internal view returns (bool) { - _ensureEnoughGas(); - (bool success, ) = address(this).staticcall(abi.encodeCall(this.tryCompareAdminOfAChain, (_chain, msg.sender))); - return success; - } - - /// @notice Tries to compare the admin of a chain with the potential admin. - /// @param _chain The address of the chain. - /// @param _potentialAdmin The address of the potential admin. - /// @dev This function reverts if the `_chain` is not a ZkSyncHyperchain or the `_potentialAdmin` is not the - /// admin of the chain. - function tryCompareAdminOfAChain(address _chain, address _potentialAdmin) external view { if (_chain == address(0)) { - revert ChainZeroAddress(); + return false; } // Unfortunately there is no easy way to double check that indeed the `_chain` is a ZkSyncHyperchain. @@ -233,79 +219,128 @@ contract PermanentRestriction is IRestriction, IPermanentRestriction, Ownable2St // - Query the Bridgehub for the Hyperchain with the given `chainId`. // - We compare the corresponding addresses - // Note, that we do not use an explicit call here to ensure that the function does not panic in case of - // incorrect `_chain` address. - (bool success, bytes memory data) = _chain.staticcall(abi.encodeWithSelector(IGetters.getChainId.selector)); - if (!success || data.length < 32) { - revert NotAHyperchain(_chain); - } + // Note, that we do use assembly here to ensure that the function does not panic in case of + // either incorrect `_chain` address or in case the returndata is too large + + (uint256 chainId, bool chainIdQuerySuccess) = _getChainIdUnffallibleCall(_chain); - // Can not fail - uint256 chainId = abi.decode(data, (uint256)); + if (!chainIdQuerySuccess) { + // It is not a hyperchain, so we can return `false` here. + return false; + } // Note, that here it is important to use the legacy `getHyperchain` function, so that the contract // is compatible with the legacy ones. if (BRIDGE_HUB.getHyperchain(chainId) != _chain) { - revert NotAHyperchain(_chain); + // It is not a hyperchain, so we can return `false` here. + return false; } - // Now, the chain is known to be a hyperchain, so it should implement the corresponding interface + // Now, the chain is known to be a hyperchain, so it must implement the corresponding interface address admin = IZKChain(_chain).getAdmin(); - if (admin != _potentialAdmin) { - revert NotAnAdmin(admin, _potentialAdmin); + + return admin == msg.sender; + } + + /// @notice Tries to call `IGetters.getChainId()` function on the `_potentialChainAddress`. + /// It ensures that the returndata is of correct format and if not, it returns false. + /// @param _chain The address of the potential chain + /// @return chainId The chainId of the chain. + /// @return success Whether the `chain` is indeed an address of a ZK Chain. + /// @dev Returns a tuple of the chainId and whether the call was successful. + /// If the second item is `false`, the caller should ignore the first value. + function _getChainIdUnffallibleCall(address _chain) private view returns (uint256 chainId, bool success) { + bytes4 selector = IGetters.getChainId.selector; + assembly { + // We use scratch space here, so it is safe + mstore(0, selector) + success := staticcall(gas(), _chain, 0, 4, 0, 0) + + let isReturndataSizeCorrect := eq(returndatasize(), 32) + + success := and(success, isReturndataSizeCorrect) + + if success { + // We use scratch space here, so it is safe + returndatacopy(0, 0, 32) + + chainId := mload(0) + } } } /// @notice Tries to get the new admin from the migration. /// @param _call The call data. - /// @dev This function reverts if the provided call was not a migration call. - function tryGetNewAdminFromMigration(Call calldata _call) external view returns (address) { + /// @return Returns a tuple of of the new admin and whether the transaction is indeed the migration. + /// If the second item is `false`, the caller should ignore the first value. + /// @dev If any other error is returned, it is assumed to be out of gas or some other unexpected + /// error that should be bubbled up by the caller. + function _getNewAdminFromMigration(Call calldata _call) internal view returns (address, bool) { if (_call.target != address(BRIDGE_HUB)) { - revert NotBridgehub(_call.target); + return (address(0), false); + } + + if (_call.data.length < 4) { + return (address(0), false); } if (bytes4(_call.data[:4]) != IBridgehub.requestL2TransactionTwoBridges.selector) { - revert InvalidSelector(bytes4(_call.data[:4])); + return (address(0), false); } address sharedBridge = BRIDGE_HUB.sharedBridge(); + // Assuming that correctly encoded calldata is provided, the following line must never fail, + // since the correct selector was checked before. L2TransactionRequestTwoBridgesOuter memory request = abi.decode( _call.data[4:], (L2TransactionRequestTwoBridgesOuter) ); if (request.secondBridgeAddress != sharedBridge) { - revert InvalidAddress(sharedBridge, request.secondBridgeAddress); + return (address(0), false); } bytes memory secondBridgeData = request.secondBridgeCalldata; + if (secondBridgeData.length == 0) { + return (address(0), false); + } + if (secondBridgeData[0] != NEW_ENCODING_VERSION) { - revert UnsupportedEncodingVersion(); + return (address(0), false); } bytes memory encodedData = new bytes(secondBridgeData.length - 1); assembly { mcopy(add(encodedData, 0x20), add(secondBridgeData, 0x21), mload(encodedData)) } + // From now on, we know that the used encoding version is `NEW_ENCODING_VERSION` that is + // supported only in the new protocol version with Gateway support, so we can assume + // that the methods like e.g. Bridgehub.ctmAssetIdToAddress must exist. + + // This is the format of the `secondBridgeData` under the `NEW_ENCODING_VERSION`. + // If it fails, it would mean that the data is not correct and the call would eventually fail anyway. (bytes32 chainAssetId, bytes memory bridgehubData) = abi.decode(encodedData, (bytes32, bytes)); + // We will just check that the chainAssetId is a valid chainAssetId. // For now, for simplicity, we do not check that the admin is exactly the admin // of this chain. address ctmAddress = BRIDGE_HUB.ctmAssetIdToAddress(chainAssetId); if (ctmAddress == address(0)) { - revert ZeroAddress(); + return (address(0), false); + } + + // Almost certainly it will be Bridgehub, but we add this check just in case we have circumstances + // that require us to use a different asset handler. + address assetHandlerAddress = IAssetRouterBase(sharedBridge).assetHandlerAddress(chainAssetId); + if (assetHandlerAddress != address(BRIDGE_HUB)) { + return (address(0), false); } + // The asset handler of CTM is the bridgehub and so the following decoding should work BridgehubBurnCTMAssetData memory burnData = abi.decode(bridgehubData, (BridgehubBurnCTMAssetData)); (address l2Admin, ) = abi.decode(burnData.ctmData, (address, bytes)); - return l2Admin; - } - - function _ensureEnoughGas() internal view { - if (gasleft() < MIN_GAS_FOR_FALLABLE_CALL) { - revert NotEnoughGas(); - } + return (l2Admin, true); } } diff --git a/l1-contracts/contracts/governance/IRestriction.sol b/l1-contracts/contracts/governance/restriction/IRestriction.sol similarity index 53% rename from l1-contracts/contracts/governance/IRestriction.sol rename to l1-contracts/contracts/governance/restriction/IRestriction.sol index b2cc79428..9124d1f67 100644 --- a/l1-contracts/contracts/governance/IRestriction.sol +++ b/l1-contracts/contracts/governance/restriction/IRestriction.sol @@ -2,12 +2,19 @@ pragma solidity 0.8.24; -import {Call} from "./Common.sol"; +import {Call} from "../Common.sol"; + +/// @dev The magic value that has to be returned by the `getSupportsRestrictionMagic` +bytes32 constant RESTRICTION_MAGIC = keccak256("Restriction"); /// @title Restriction contract interface /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev interface IRestriction { + /// @notice A method used to check that the contract supports this interface. + /// @return Returns the `RESTRICTION_MAGIC` + function getSupportsRestrictionMagic() external view returns (bytes32); + /// @notice Ensures that the invoker has the required role to call the function. /// @param _call The call data. /// @param _invoker The address of the invoker. diff --git a/l1-contracts/contracts/governance/restriction/Restriction.sol b/l1-contracts/contracts/governance/restriction/Restriction.sol new file mode 100644 index 000000000..e516b9b0e --- /dev/null +++ b/l1-contracts/contracts/governance/restriction/Restriction.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {Call} from "../Common.sol"; +import {IRestriction, RESTRICTION_MAGIC} from "./IRestriction.sol"; + +/// @title Restriction contract interface +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +abstract contract Restriction is IRestriction { + /// @notice A method used to check that the contract supports this interface. + /// @return Returns the `RESTRICTION_MAGIC` + function getSupportsRestrictionMagic() external view returns (bytes32) { + return RESTRICTION_MAGIC; + } + + /// @notice Ensures that the invoker has the required role to call the function. + /// @param _call The call data. + /// @param _invoker The address of the invoker. + function validateCall(Call calldata _call, address _invoker) external view virtual; +} diff --git a/l1-contracts/contracts/governance/restriction/RestrictionValidator.sol b/l1-contracts/contracts/governance/restriction/RestrictionValidator.sol new file mode 100644 index 000000000..e0d110947 --- /dev/null +++ b/l1-contracts/contracts/governance/restriction/RestrictionValidator.sol @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {NotARestriction} from "../../common/L1ContractErrors.sol"; +import {IRestriction, RESTRICTION_MAGIC} from "./IRestriction.sol"; + +/// @title Restriction validator +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice The library which validates whether an address can be a valid restriction +library RestrictionValidator { + /// @notice Ensures that the provided address implements the restriction interface + /// @dev Note that it *can not guarantee* that the corresponding address indeed implements + /// the interface completely or that it is implemented correctly. It is mainly used to + /// ensure that invalid restrictions can not be accidentally added. + function validateRestriction(address _restriction) internal view { + if (IRestriction(_restriction).getSupportsRestrictionMagic() != RESTRICTION_MAGIC) { + revert NotARestriction(_restriction); + } + } +} diff --git a/l1-contracts/contracts/state-transition/ChainTypeManager.sol b/l1-contracts/contracts/state-transition/ChainTypeManager.sol index 2760e36c3..49e13ef9e 100644 --- a/l1-contracts/contracts/state-transition/ChainTypeManager.sol +++ b/l1-contracts/contracts/state-transition/ChainTypeManager.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {EnumerableMap} from "@openzeppelin/contracts-v4/utils/structs/EnumerableMap.sol"; import {SafeCast} from "@openzeppelin/contracts-v4/utils/math/SafeCast.sol"; @@ -19,6 +17,7 @@ import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/ac import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; import {L2_TO_L1_LOG_SERIALIZE_SIZE, DEFAULT_L2_LOGS_TREE_ROOT_HASH, EMPTY_STRING_KECCAK} from "../common/Config.sol"; import {Unauthorized, ZeroAddress, HashMismatch, GenesisUpgradeZero, GenesisBatchHashZero, GenesisIndexStorageZero, GenesisBatchCommitmentZero} from "../common/L1ContractErrors.sol"; +import {InitialForceDeploymentMismatch, AdminZero, OutdatedProtocolVersion} from "./L1StateTransitionErrors.sol"; import {SemVer} from "../common/libraries/SemVer.sol"; import {IBridgehub} from "../bridgehub/IBridgehub.sol"; @@ -123,7 +122,7 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg _transferOwnership(_initializeData.owner); protocolVersion = _initializeData.protocolVersion; - protocolVersionDeadline[_initializeData.protocolVersion] = type(uint256).max; + _setProtocolVersionDeadline(_initializeData.protocolVersion, type(uint256).max); validatorTimelock = _initializeData.validatorTimelock; _setChainCreationParams(_initializeData.chainCreationParams); @@ -211,7 +210,7 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg /// @dev set validatorTimelock. Cannot do it during initialization, as validatorTimelock is deployed after CTM /// @param _validatorTimelock the new validatorTimelock address - function setValidatorTimelock(address _validatorTimelock) external onlyOwnerOrAdmin { + function setValidatorTimelock(address _validatorTimelock) external onlyOwner { address oldValidatorTimelock = validatorTimelock; validatorTimelock = _validatorTimelock; emit NewValidatorTimelock(oldValidatorTimelock, _validatorTimelock); @@ -231,8 +230,8 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg bytes32 newCutHash = keccak256(abi.encode(_cutData)); uint256 previousProtocolVersion = protocolVersion; upgradeCutHash[_oldProtocolVersion] = newCutHash; - protocolVersionDeadline[_oldProtocolVersion] = _oldProtocolVersionDeadline; - protocolVersionDeadline[_newProtocolVersion] = type(uint256).max; + _setProtocolVersionDeadline(_oldProtocolVersion, _oldProtocolVersionDeadline); + _setProtocolVersionDeadline(_newProtocolVersion, type(uint256).max); protocolVersion = _newProtocolVersion; emit NewProtocolVersion(previousProtocolVersion, _newProtocolVersion); emit NewUpgradeCutHash(_oldProtocolVersion, newCutHash); @@ -245,11 +244,11 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg return block.timestamp <= protocolVersionDeadline[_protocolVersion]; } - /// @dev set the protocol version timestamp + /// @notice Set the protocol version deadline /// @param _protocolVersion the protocol version /// @param _timestamp the timestamp is the deadline function setProtocolVersionDeadline(uint256 _protocolVersion, uint256 _timestamp) external onlyOwner { - protocolVersionDeadline[_protocolVersion] = _timestamp; + _setProtocolVersionDeadline(_protocolVersion, _timestamp); } /// @dev set upgrade for some protocolVersion @@ -328,7 +327,7 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg /// @param _chainId the chainId of the chain /// @param _validator the new validator /// @param _active whether the validator is active - function setValidator(uint256 _chainId, address _validator, bool _active) external onlyOwnerOrAdmin { + function setValidator(uint256 _chainId, address _validator, bool _active) external onlyOwner { IZKChain(getZKChain(_chainId)).setValidator(_validator, _active); } @@ -357,7 +356,6 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg return getZKChain(_chainId); } - // check not registered Diamond.DiamondCutData memory diamondCut = abi.decode(_diamondCut, (Diamond.DiamondCutData)); { @@ -416,7 +414,9 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg { // check input bytes32 forceDeploymentHash = keccak256(abi.encode(_forceDeploymentData)); - require(forceDeploymentHash == initialForceDeploymentHash, "CTM: initial force deployment mismatch"); + if (forceDeploymentHash != initialForceDeploymentHash) { + revert InitialForceDeploymentMismatch(forceDeploymentHash, initialForceDeploymentHash); + } } // genesis upgrade, deploys some contracts, sets chainId IAdmin(zkChainAddress).genesisUpgrade( @@ -432,17 +432,6 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg return IZKChain(getZKChain(_chainId)).getProtocolVersion(); } - /// @param _newSettlementLayerChainId the chainId of the chain - /// @param _isWhitelisted whether the chain is whitelisted - function registerSettlementLayer(uint256 _newSettlementLayerChainId, bool _isWhitelisted) external onlyOwner { - require(_newSettlementLayerChainId != 0, "Bad chain id"); - - // Currently, we require that the sync layer is deployed by the same CTM. - require(getZKChain(_newSettlementLayerChainId) != address(0), "CTM: sync layer not registered"); - - IBridgehub(BRIDGE_HUB).registerSettlementLayer(_newSettlementLayerChainId, _isWhitelisted); - } - /// @notice Called by the bridgehub during the migration of a chain to another settlement layer. /// @param _chainId The chain id of the chain to be migrated. /// @param _data The data needed to perform the migration. @@ -453,12 +442,16 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg // Note that the `_diamondCut` here is not for the current chain, for the chain where the migration // happens. The correctness of it will be checked on the CTM on the new settlement layer. (address _newSettlementLayerAdmin, bytes memory _diamondCut) = abi.decode(_data, (address, bytes)); - require(_newSettlementLayerAdmin != address(0), "CTM: admin zero"); + if (_newSettlementLayerAdmin == address(0)) { + revert AdminZero(); + } // We ensure that the chain has the latest protocol version to avoid edge cases // related to different protocol version support. - address zkChain = getZKChain(_chainId); - require(IZKChain(zkChain).getProtocolVersion() == protocolVersion, "CTM: outdated pv"); + uint256 chainProtocolVersion = IZKChain(getZKChain(_chainId)).getProtocolVersion(); + if (chainProtocolVersion != protocolVersion) { + revert OutdatedProtocolVersion(chainProtocolVersion, protocolVersion); + } return abi.encode( @@ -483,7 +476,9 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg // We ensure that the chain has the latest protocol version to avoid edge cases // related to different protocol version support. - require(_protocolVersion == protocolVersion, "CTM, outdated pv"); + if (_protocolVersion != protocolVersion) { + revert OutdatedProtocolVersion(_protocolVersion, protocolVersion); + } chainAddress = _deployNewChain({ _chainId: _chainId, _baseTokenAssetId: _baseTokenAssetId, @@ -507,12 +502,31 @@ contract ChainTypeManager is IChainTypeManager, ReentrancyGuard, Ownable2StepUpg // state updates that occur. } + /// @notice Set the protocol version deadline + /// @param _protocolVersion the protocol version + /// @param _timestamp the timestamp is the deadline + function _setProtocolVersionDeadline(uint256 _protocolVersion, uint256 _timestamp) internal { + protocolVersionDeadline[_protocolVersion] = _timestamp; + emit UpdateProtocolVersionDeadline(_protocolVersion, _timestamp); + } + /*////////////////////////////////////////////////////////////// Legacy functions //////////////////////////////////////////////////////////////*/ /// @notice return the chain contract address for a chainId function getHyperchain(uint256 _chainId) public view returns (address) { + // During upgrade, there will be a period when the zkChains mapping on + // bridgehub will not be filled yet, while the ValidatorTimelock + // will still query the address to obtain the chain id. + // + // To cover this case, we firstly use the existing storage and only then + // we use the bridgehub if the former was not present. + // This logic should be deleted in one of the future upgrades. + address legacyAddress = getZKChainLegacy(_chainId); + if (legacyAddress != address(0)) { + return legacyAddress; + } return getZKChain(_chainId); } } diff --git a/l1-contracts/contracts/state-transition/IChainTypeManager.sol b/l1-contracts/contracts/state-transition/IChainTypeManager.sol index 90b500b28..b8d50d22c 100644 --- a/l1-contracts/contracts/state-transition/IChainTypeManager.sol +++ b/l1-contracts/contracts/state-transition/IChainTypeManager.sol @@ -78,6 +78,9 @@ interface IChainTypeManager { /// @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; @@ -86,6 +89,8 @@ interface IChainTypeManager { 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); @@ -153,10 +158,6 @@ interface IChainTypeManager { function getSemverProtocolVersion() external view returns (uint32, uint32, uint32); - function registerSettlementLayer(uint256 _newSettlementLayerChainId, bool _isWhitelisted) external; - - event BridgeInitialize(address indexed l1Token, string name, string symbol, uint8 decimals); - function forwardedBridgeBurn( uint256 _chainId, bytes calldata _data diff --git a/l1-contracts/contracts/state-transition/L1StateTransitionErrors.sol b/l1-contracts/contracts/state-transition/L1StateTransitionErrors.sol new file mode 100644 index 000000000..55bb7ac16 --- /dev/null +++ b/l1-contracts/contracts/state-transition/L1StateTransitionErrors.sol @@ -0,0 +1,141 @@ +// 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 BlobDataOffset); + +// 0xbeb96791 +error InvalidNumberOfBlobs(uint256 blobsProvided, uint256 maxBlobsSupported); + +// 0xcd384e46 +error InvalidBlobsHashes(uint256 operatorDAInputLength, uint256 minNumberOfBlobHashes); + +// 0xd2531c15 +error InvalidL2DAOutputHash(bytes32 l2DAValidatorOutputHash); + +// 0x77a3c423 +error OnlyOneBlobWithCalldata(); + +// 0x086bb220 +error PubdataTooSmall(uint256 pubdataInputLength, uint256 blobCommitmentSize); + +// 0xcba35a08 +error PubdataTooLong(uint256 pubdataLength, uint256 blobSizeBytes); + +// 0x1b0f562e +error InvalidPubdataHash(); + +// 0x5717f940 +error InvalidPubdataSource(uint8 pubdataSource); + +// 0x125d99b0 +error BlobHashBlobCommitmentMismatchValue(); + +// 0x7fbff2dd +error L1DAValidatorInvalidSender(address msgSender); + +// 0x5ade0455 +error RootMismatch(); + +// 0xc06789fa +error InvalidCommitment(); + +// 0xc866ff2c +error InitialForceDeploymentMismatch(bytes32 forceDeploymentHash, bytes32 initialForceDeploymentHash); + +// 0xb325f767 +error AdminZero(); + +// 0x681150be +error OutdatedProtocolVersion(uint256 protocolVersion, uint256 currentProtocolVersion); + +// 0x8e7df0b6 +error ChainWasMigrated(); + +// 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); diff --git a/l1-contracts/contracts/state-transition/ValidatorTimelock.sol b/l1-contracts/contracts/state-transition/ValidatorTimelock.sol index 64cc0bc20..550d39e2c 100644 --- a/l1-contracts/contracts/state-transition/ValidatorTimelock.sol +++ b/l1-contracts/contracts/state-transition/ValidatorTimelock.sol @@ -52,13 +52,9 @@ contract ValidatorTimelock is IExecutor, Ownable2Step { /// @dev The delay between committing and executing batches. uint32 public executionDelay; - /// @dev Era's chainID - uint256 internal immutable ERA_CHAIN_ID; - - constructor(address _initialOwner, uint32 _executionDelay, uint256 _eraChainId) { + constructor(address _initialOwner, uint32 _executionDelay) { _transferOwnership(_initialOwner); executionDelay = _executionDelay; - ERA_CHAIN_ID = _eraChainId; } /// @notice Checks if the caller is the admin of the chain. @@ -183,7 +179,13 @@ contract ValidatorTimelock is IExecutor, Ownable2Step { /// @dev Call the zkChain diamond contract with the same calldata as this contract was called. /// Note: it is called the zkChain diamond contract, not delegatecalled! function _propagateToZKChain(uint256 _chainId) internal { - address contractAddress = chainTypeManager.getZKChain(_chainId); + // Note, that it is important to use chain type manager and + // the legacy method here for obtaining the chain id in order for + // this contract to before the CTM upgrade is finalized. + address contractAddress = chainTypeManager.getHyperchain(_chainId); + if (contractAddress == address(0)) { + revert ZeroAddress(); + } assembly { // Copy function signature and arguments from calldata at zero position into memory at pointer position calldatacopy(0, 0, calldatasize()) diff --git a/l1-contracts/contracts/state-transition/chain-deps/DiamondProxy.sol b/l1-contracts/contracts/state-transition/chain-deps/DiamondProxy.sol index db29da126..1e297d53a 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/DiamondProxy.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/DiamondProxy.sol @@ -2,6 +2,9 @@ pragma solidity 0.8.24; +// Note, that while we do try to make use of custom errors whenever possible, +// we do not change it for `DiamondProxy`, since it is a contract that can not be +// upgraded or changed, so we keep its code always consistent with the production version. // solhint-disable gas-custom-errors import {Diamond} from "../libraries/Diamond.sol"; diff --git a/l1-contracts/contracts/state-transition/chain-deps/GatewayCTMDeployer.sol b/l1-contracts/contracts/state-transition/chain-deps/GatewayCTMDeployer.sol new file mode 100644 index 000000000..dbfdf4ba8 --- /dev/null +++ b/l1-contracts/contracts/state-transition/chain-deps/GatewayCTMDeployer.sol @@ -0,0 +1,374 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {MailboxFacet} from "./facets/Mailbox.sol"; +import {ExecutorFacet} from "./facets/Executor.sol"; +import {GettersFacet} from "./facets/Getters.sol"; +import {AdminFacet} from "./facets/Admin.sol"; +import {Multicall3} from "../../dev-contracts/Multicall3.sol"; + +import {RollupDAManager} from "../data-availability/RollupDAManager.sol"; +import {RelayedSLDAValidator} from "../data-availability/RelayedSLDAValidator.sol"; +import {ValidiumL1DAValidator} from "../data-availability/ValidiumL1DAValidator.sol"; + +import {Verifier} from "../Verifier.sol"; +import {VerifierParams, IVerifier} from "../chain-interfaces/IVerifier.sol"; +import {TestnetVerifier} from "../TestnetVerifier.sol"; +import {ValidatorTimelock} from "../ValidatorTimelock.sol"; +import {FeeParams} from "../chain-deps/ZKChainStorage.sol"; + +import {DiamondInit} from "./DiamondInit.sol"; +import {L1GenesisUpgrade} from "../../upgrades/L1GenesisUpgrade.sol"; +import {Diamond} from "../libraries/Diamond.sol"; + +import {ChainTypeManager} from "../ChainTypeManager.sol"; + +import {L2_BRIDGEHUB_ADDR} from "../../common/L2ContractAddresses.sol"; + +import {ProxyAdmin} from "@openzeppelin/contracts-v4/proxy/transparent/ProxyAdmin.sol"; +import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; +import {InitializeDataNewChain as DiamondInitializeDataNewChain} from "../chain-interfaces/IDiamondInit.sol"; +import {ChainTypeManagerInitializeData, ChainCreationParams, IChainTypeManager} from "../IChainTypeManager.sol"; + +/// @notice Configuration parameters for deploying the GatewayCTMDeployer contract. +struct GatewayCTMDeployerConfig { + /// @notice Address of the aliased governance contract. + address aliasedGovernanceAddress; + /// @notice Salt used for deterministic deployments via CREATE2. + bytes32 salt; + /// @notice Chain ID of the Era chain. + uint256 eraChainId; + /// @notice Chain ID of the L1 chain. + uint256 l1ChainId; + /// @notice Address of the Rollup L2 Data Availability Validator. + address rollupL2DAValidatorAddress; + /// @notice Flag indicating whether to use the testnet verifier. + bool testnetVerifier; + /// @notice Array of function selectors for the Admin facet. + bytes4[] adminSelectors; + /// @notice Array of function selectors for the Executor facet. + bytes4[] executorSelectors; + /// @notice Array of function selectors for the Mailbox facet. + bytes4[] mailboxSelectors; + /// @notice Array of function selectors for the Getters facet. + bytes4[] gettersSelectors; + /// @notice Parameters for the verifier contract. + VerifierParams verifierParams; + /// @notice Parameters related to fees. + /// @dev They are mainly related to the L1->L2 transactions, fees for + /// which are not processed on Gateway. However, we still need these + /// values to deploy new chain's instances on Gateway. + FeeParams feeParams; + /// @notice Hash of the bootloader bytecode. + bytes32 bootloaderHash; + /// @notice Hash of the default account bytecode. + bytes32 defaultAccountHash; + /// @notice Maximum gas limit for priority transactions. + uint256 priorityTxMaxGasLimit; + /// @notice Root hash of the genesis state. + bytes32 genesisRoot; + /// @notice Leaf index in the genesis rollup. + uint256 genesisRollupLeafIndex; + /// @notice Commitment of the genesis batch. + bytes32 genesisBatchCommitment; + /// @notice Data for force deployments. + bytes forceDeploymentsData; + /// @notice The latest protocol version. + uint256 protocolVersion; +} + +/// @notice Addresses of state transition related contracts. +// solhint-disable-next-line gas-struct-packing +struct StateTransitionContracts { + /// @notice Address of the ChainTypeManager proxy contract. + address chainTypeManagerProxy; + /// @notice Address of the ChainTypeManager implementation contract. + address chainTypeManagerImplementation; + /// @notice Address of the Verifier contract. + address verifier; + /// @notice Address of the Admin facet contract. + address adminFacet; + /// @notice Address of the Mailbox facet contract. + address mailboxFacet; + /// @notice Address of the Executor facet contract. + address executorFacet; + /// @notice Address of the Getters facet contract. + address gettersFacet; + /// @notice Address of the DiamondInit contract. + address diamondInit; + /// @notice Address of the GenesisUpgrade contract. + address genesisUpgrade; + /// @notice Address of the ValidatorTimelock contract. + address validatorTimelock; + /// @notice Address of the ProxyAdmin for ChainTypeManager. + address chainTypeManagerProxyAdmin; +} + +/// @notice Addresses of Data Availability (DA) related contracts. +// solhint-disable-next-line gas-struct-packing +struct DAContracts { + /// @notice Address of the RollupDAManager contract. + address rollupDAManager; + /// @notice Address of the RelayedSLDAValidator contract. + address relayedSLDAValidator; + /// @notice Address of the ValidiumL1DAValidator contract. + address validiumDAValidator; +} + +/// @notice Collection of all deployed contracts by the GatewayCTMDeployer. +struct DeployedContracts { + /// @notice Address of the Multicall3 contract. + address multicall3; + /// @notice Struct containing state transition related contracts. + StateTransitionContracts stateTransition; + /// @notice Struct containing Data Availability related contracts. + DAContracts daContracts; + /// @notice Encoded data for the diamond cut operation. + bytes diamondCutData; +} + +/// @dev The constant address to be used for the blobHashRetriever inside the contracts. +/// At the time of this writing the blob hash retriever is not used at all, but the zero-address +/// check is still yet present, so we use address one as the substitution. +address constant BLOB_HASH_RETRIEVER_ADDR = address(uint160(1)); + +/// @title GatewayCTMDeployer +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice Contract responsible for deploying all the CTM-related contracts on top +/// of the Gateway contract. +/// @dev The expectation is that this contract will be deployed via the built-in L2 `Create2Factory`. +/// This will achieve the fact that the address of this contract (and thus, the addresses of the +/// contract it deploys are deterministic). An important role that this contract plays is in +/// being the first owner of some of the contracts (e.g. ValidatorTimelock), which helps it to initialize it properly +/// and transfer the ownership to the correct governance. +/// @dev Note, that it is expected to be used in zkEVM environment only. Since all of the deployments +/// are done by hash in zkEVM, this contract is actually quite small and cheap to execute in zkEVM environment. +contract GatewayCTMDeployer { + DeployedContracts internal deployedContracts; + + /// @notice Returns deployed contracts. + /// @dev Just using `public` mode for the `deployedContracts` field did not work + /// due to internal issues during testing. + /// @return contracts The struct with information about the deployed contracts. + function getDeployedContracts() external view returns (DeployedContracts memory contracts) { + contracts = deployedContracts; + } + + constructor(GatewayCTMDeployerConfig memory _config) { + // Caching some values + bytes32 salt = _config.salt; + uint256 eraChainId = _config.eraChainId; + uint256 l1ChainId = _config.l1ChainId; + + DeployedContracts memory contracts; + + contracts.multicall3 = address(new Multicall3{salt: salt}()); + + _deployFacetsAndUpgrades({ + _salt: salt, + _eraChainId: eraChainId, + _l1ChainId: l1ChainId, + _rollupL2DAValidatorAddress: _config.rollupL2DAValidatorAddress, + _aliasedGovernanceAddress: _config.aliasedGovernanceAddress, + _deployedContracts: contracts + }); + _deployVerifier(salt, _config.testnetVerifier, contracts); + + ValidatorTimelock timelock = new ValidatorTimelock{salt: salt}(address(this), 0); + contracts.stateTransition.validatorTimelock = address(timelock); + + _deployCTM(salt, _config, contracts); + _setChainTypeManagerInValidatorTimelock(_config.aliasedGovernanceAddress, timelock, contracts); + + deployedContracts = contracts; + } + + /// @notice Deploys facets and upgrade contracts. + /// @param _salt Salt used for CREATE2 deployments. + /// @param _eraChainId Era Chain ID. + /// @param _l1ChainId L1 Chain ID. + /// @param _rollupL2DAValidatorAddress The expected L2 DA Validator to be + /// used by permanent rollups. + /// @param _aliasedGovernanceAddress The aliased address of the governnace. + /// @param _deployedContracts The struct with deployed contracts, that will be mofiied + /// in the process of the execution of this function. + function _deployFacetsAndUpgrades( + bytes32 _salt, + uint256 _eraChainId, + uint256 _l1ChainId, + address _rollupL2DAValidatorAddress, + address _aliasedGovernanceAddress, + DeployedContracts memory _deployedContracts + ) internal { + _deployedContracts.stateTransition.mailboxFacet = address( + new MailboxFacet{salt: _salt}(_eraChainId, _l1ChainId) + ); + _deployedContracts.stateTransition.executorFacet = address(new ExecutorFacet{salt: _salt}(_l1ChainId)); + _deployedContracts.stateTransition.gettersFacet = address(new GettersFacet{salt: _salt}()); + + RollupDAManager rollupDAManager = _deployRollupDAContracts( + _salt, + _rollupL2DAValidatorAddress, + _aliasedGovernanceAddress, + _deployedContracts + ); + _deployedContracts.stateTransition.adminFacet = address( + new AdminFacet{salt: _salt}(_l1ChainId, rollupDAManager) + ); + + _deployedContracts.stateTransition.diamondInit = address(new DiamondInit{salt: _salt}()); + _deployedContracts.stateTransition.genesisUpgrade = address(new L1GenesisUpgrade{salt: _salt}()); + } + + /// @notice Deploys verifier. + /// @param _salt Salt used for CREATE2 deployments. + /// @param _testnetVerifier Whether testnet verifier should be used. + /// @param _deployedContracts The struct with deployed contracts, that will be mofiied + /// in the process of the execution of this function. + function _deployVerifier( + bytes32 _salt, + bool _testnetVerifier, + DeployedContracts memory _deployedContracts + ) internal { + if (_testnetVerifier) { + _deployedContracts.stateTransition.verifier = address(new TestnetVerifier{salt: _salt}()); + } else { + _deployedContracts.stateTransition.verifier = address(new Verifier{salt: _salt}()); + } + } + + /// @notice Deploys DA-related contracts. + /// @param _salt Salt used for CREATE2 deployments. + /// @param _rollupL2DAValidatorAddress The expected L2 DA Validator to be + /// used by permanent rollups. + /// @param _aliasedGovernanceAddress The aliased address of the governnace. + /// @param _deployedContracts The struct with deployed contracts, that will be mofiied + /// in the process of the execution of this function. + function _deployRollupDAContracts( + bytes32 _salt, + address _rollupL2DAValidatorAddress, + address _aliasedGovernanceAddress, + DeployedContracts memory _deployedContracts + ) internal returns (RollupDAManager rollupDAManager) { + rollupDAManager = new RollupDAManager{salt: _salt}(); + + ValidiumL1DAValidator validiumDAValidator = new ValidiumL1DAValidator{salt: _salt}(); + + RelayedSLDAValidator relayedSLDAValidator = new RelayedSLDAValidator{salt: _salt}(); + rollupDAManager.updateDAPair(address(relayedSLDAValidator), _rollupL2DAValidatorAddress, true); + + // Note, that the governance still has to accept it. + // It will happen in a separate voting after the deployment is done. + rollupDAManager.transferOwnership(_aliasedGovernanceAddress); + + _deployedContracts.daContracts.rollupDAManager = address(rollupDAManager); + _deployedContracts.daContracts.relayedSLDAValidator = address(relayedSLDAValidator); + _deployedContracts.daContracts.validiumDAValidator = address(validiumDAValidator); + } + + /// @notice Deploys DA-related contracts. + /// @param _salt Salt used for CREATE2 deployments. + /// @param _config The deployment config. + /// @param _deployedContracts The struct with deployed contracts, that will be mofiied + /// in the process of the execution of this function. + function _deployCTM( + bytes32 _salt, + GatewayCTMDeployerConfig memory _config, + DeployedContracts memory _deployedContracts + ) internal { + _deployedContracts.stateTransition.chainTypeManagerImplementation = address( + new ChainTypeManager{salt: _salt}(L2_BRIDGEHUB_ADDR) + ); + ProxyAdmin proxyAdmin = new ProxyAdmin{salt: _salt}(); + proxyAdmin.transferOwnership(_config.aliasedGovernanceAddress); + _deployedContracts.stateTransition.chainTypeManagerProxyAdmin = address(proxyAdmin); + + Diamond.FacetCut[] memory facetCuts = new Diamond.FacetCut[](4); + facetCuts[0] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.adminFacet, + action: Diamond.Action.Add, + isFreezable: false, + selectors: _config.adminSelectors + }); + facetCuts[1] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.gettersFacet, + action: Diamond.Action.Add, + isFreezable: false, + selectors: _config.gettersSelectors + }); + facetCuts[2] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.mailboxFacet, + action: Diamond.Action.Add, + isFreezable: true, + selectors: _config.mailboxSelectors + }); + facetCuts[3] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.executorFacet, + action: Diamond.Action.Add, + isFreezable: true, + selectors: _config.executorSelectors + }); + + DiamondInitializeDataNewChain memory initializeData = DiamondInitializeDataNewChain({ + verifier: IVerifier(_deployedContracts.stateTransition.verifier), + verifierParams: _config.verifierParams, + l2BootloaderBytecodeHash: _config.bootloaderHash, + l2DefaultAccountBytecodeHash: _config.defaultAccountHash, + priorityTxMaxGasLimit: _config.priorityTxMaxGasLimit, + feeParams: _config.feeParams, + blobVersionedHashRetriever: BLOB_HASH_RETRIEVER_ADDR + }); + + Diamond.DiamondCutData memory diamondCut = Diamond.DiamondCutData({ + facetCuts: facetCuts, + initAddress: _deployedContracts.stateTransition.diamondInit, + initCalldata: abi.encode(initializeData) + }); + + _deployedContracts.diamondCutData = abi.encode(diamondCut); + + ChainCreationParams memory chainCreationParams = ChainCreationParams({ + genesisUpgrade: _deployedContracts.stateTransition.genesisUpgrade, + genesisBatchHash: _config.genesisRoot, + genesisIndexRepeatedStorageChanges: uint64(_config.genesisRollupLeafIndex), + genesisBatchCommitment: _config.genesisBatchCommitment, + diamondCut: diamondCut, + // Note, it is the same as for contracts that are based on L2 + forceDeploymentsData: _config.forceDeploymentsData + }); + + ChainTypeManagerInitializeData memory diamondInitData = ChainTypeManagerInitializeData({ + owner: _config.aliasedGovernanceAddress, + validatorTimelock: _deployedContracts.stateTransition.validatorTimelock, + chainCreationParams: chainCreationParams, + protocolVersion: _config.protocolVersion + }); + + _deployedContracts.stateTransition.chainTypeManagerProxy = address( + new TransparentUpgradeableProxy{salt: _salt}( + _deployedContracts.stateTransition.chainTypeManagerImplementation, + address(proxyAdmin), + abi.encodeCall(ChainTypeManager.initialize, (diamondInitData)) + ) + ); + } + + /// @notice Sets the previously deployed CTM inside the ValidatorTimelock + /// @param _aliasedGovernanceAddress The aliased address of the governnace. + /// @param _timelock The address of the validator timelock + /// @param _deployedContracts The struct with deployed contracts, that will be mofiied + /// in the process of the execution of this function. + function _setChainTypeManagerInValidatorTimelock( + address _aliasedGovernanceAddress, + ValidatorTimelock _timelock, + DeployedContracts memory _deployedContracts + ) internal { + _timelock.setChainTypeManager(IChainTypeManager(_deployedContracts.stateTransition.chainTypeManagerProxy)); + + // Note, that the governance still has to accept it. + // It will happen in a separate voting after the deployment is done. + _timelock.transferOwnership(_aliasedGovernanceAddress); + } +} diff --git a/l1-contracts/contracts/state-transition/chain-deps/ZKChainStorage.sol b/l1-contracts/contracts/state-transition/chain-deps/ZKChainStorage.sol index 5f19aecd4..4d3d2f4ff 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/ZKChainStorage.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/ZKChainStorage.sol @@ -169,4 +169,6 @@ struct ZKChainStorage { address settlementLayer; /// @dev Priority tree, the new data structure for priority queue PriorityTree.Tree priorityTree; + /// @dev Whether the chain is a permanent rollup + bool isPermanentRollup; } diff --git a/l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol b/l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol index 27bbe3155..7ea8c9ff9 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/facets/Admin.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {IAdmin} from "../../chain-interfaces/IAdmin.sol"; import {Diamond} from "../../libraries/Diamond.sol"; import {MAX_GAS_PER_TRANSACTION, ZKChainCommitment} from "../../../common/Config.sol"; @@ -13,7 +11,9 @@ import {PriorityQueue} from "../../../state-transition/libraries/PriorityQueue.s import {ZKChainBase} from "./ZKChainBase.sol"; import {IChainTypeManager} from "../../IChainTypeManager.sol"; import {IL1GenesisUpgrade} from "../../../upgrades/IL1GenesisUpgrade.sol"; -import {Unauthorized, TooMuchGas, PriorityTxPubdataExceedsMaxPubDataPerBatch, InvalidPubdataPricingMode, ProtocolIdMismatch, ChainAlreadyLive, HashMismatch, ProtocolIdNotGreater, DenominatorIsZero, DiamondAlreadyFrozen, DiamondNotFrozen} from "../../../common/L1ContractErrors.sol"; +import {Unauthorized, TooMuchGas, PriorityTxPubdataExceedsMaxPubDataPerBatch, InvalidPubdataPricingMode, ProtocolIdMismatch, HashMismatch, ProtocolIdNotGreater, DenominatorIsZero, DiamondAlreadyFrozen, DiamondNotFrozen, IncorrectPricingMode, InvalidDAForPermanentRollup, AlreadyPermanentRollup} from "../../../common/L1ContractErrors.sol"; +import {NotL1, L1DAValidatorAddressIsZero, L2DAValidatorAddressIsZero, AlreadyMigrated, NotChainAdmin, ProtocolVersionNotUpToDate, ExecutedIsNotConsistentWithVerified, VerifiedIsNotConsistentWithCommitted, InvalidNumberOfBatchHashes, PriorityQueueNotReady, VerifiedIsNotConsistentWithCommitted, NotAllBatchesExecuted, OutdatedProtocolVersion, NotHistoricalRoot, ContractNotDeployed, NotMigrated} from "../../L1StateTransitionErrors.sol"; +import {RollupDAManager} from "../../data-availability/RollupDAManager.sol"; // While formally the following import is not used, it is needed to inherit documentation from it import {IZKChainBase} from "../../chain-interfaces/IZKChainBase.sol"; @@ -32,12 +32,18 @@ contract AdminFacet is ZKChainBase, IAdmin { /// L1 that is at the most base layer. uint256 internal immutable L1_CHAIN_ID; - constructor(uint256 _l1ChainId) { + /// @notice The address that is responsible for determining whether a certain DA pair is allowed for rollups. + RollupDAManager internal immutable ROLLUP_DA_MANAGER; + + constructor(uint256 _l1ChainId, RollupDAManager _rollupDAManager) { L1_CHAIN_ID = _l1ChainId; + ROLLUP_DA_MANAGER = _rollupDAManager; } modifier onlyL1() { - require(block.chainid == L1_CHAIN_ID, "AdminFacet: not L1"); + if (block.chainid != L1_CHAIN_ID) { + revert NotL1(block.chainid); + } _; } @@ -126,10 +132,10 @@ contract AdminFacet is ZKChainBase, IAdmin { /// @inheritdoc IAdmin function setPubdataPricingMode(PubdataPricingMode _pricingMode) external onlyAdmin onlyL1 { - // Validium mode can be set only before the first batch is processed - if (s.totalBatchesCommitted != 0) { - revert ChainAlreadyLive(); + if (s.isPermanentRollup && _pricingMode != PubdataPricingMode.Rollup) { + revert IncorrectPricingMode(); } + s.feeParams.pubdataPricingMode = _pricingMode; emit ValidiumModeStatusUpdate(_pricingMode); } @@ -154,12 +160,39 @@ contract AdminFacet is ZKChainBase, IAdmin { /// @inheritdoc IAdmin function setDAValidatorPair(address _l1DAValidator, address _l2DAValidator) external onlyAdmin { - require(_l1DAValidator != address(0), "AdminFacet: L1DAValidator address is zero"); - require(_l2DAValidator != address(0), "AdminFacet: L2DAValidator address is zero"); + if (_l1DAValidator == address(0)) { + revert L1DAValidatorAddressIsZero(); + } + if (_l2DAValidator == address(0)) { + revert L2DAValidatorAddressIsZero(); + } + + if (s.isPermanentRollup && !ROLLUP_DA_MANAGER.isPairAllowed(_l1DAValidator, _l2DAValidator)) { + revert InvalidDAForPermanentRollup(); + } _setDAValidatorPair(_l1DAValidator, _l2DAValidator); } + /// @inheritdoc IAdmin + function makePermanentRollup() external onlyAdmin onlySettlementLayer { + if (s.isPermanentRollup) { + revert AlreadyPermanentRollup(); + } + + if (!ROLLUP_DA_MANAGER.isPairAllowed(s.l1DAValidator, s.l2DAValidator)) { + // The correct data availability pair should be set beforehand. + revert InvalidDAForPermanentRollup(); + } + + if (s.feeParams.pubdataPricingMode != PubdataPricingMode.Rollup) { + // The correct pubdata pricing mode should be set beforehand. + revert IncorrectPricingMode(); + } + + s.isPermanentRollup = true; + } + /*////////////////////////////////////////////////////////////// UPGRADE EXECUTION //////////////////////////////////////////////////////////////*/ @@ -251,19 +284,27 @@ contract AdminFacet is ZKChainBase, IAdmin { address _originalCaller, bytes calldata _data ) external payable override onlyBridgehub returns (bytes memory chainBridgeMintData) { - require(s.settlementLayer == address(0), "Af: already migrated"); - require(_originalCaller == s.admin, "Af: not chainAdmin"); + if (s.settlementLayer != address(0)) { + revert AlreadyMigrated(); + } + if (_originalCaller != s.admin) { + revert NotChainAdmin(_originalCaller, s.admin); + } // As of now all we need in this function is the chainId so we encode it and pass it down in the _chainData field uint256 protocolVersion = abi.decode(_data, (uint256)); uint256 currentProtocolVersion = s.protocolVersion; - require(currentProtocolVersion == protocolVersion, "CTM: protocolVersion not up to date"); + if (currentProtocolVersion != protocolVersion) { + revert ProtocolVersionNotUpToDate(currentProtocolVersion, protocolVersion); + } if (block.chainid != L1_CHAIN_ID) { // We assume that GW -> L1 transactions can never fail and provide no recovery mechanism from it. // That's why we need to bound the gas that can be consumed during such a migration. - require(s.totalBatchesCommitted == s.totalBatchesExecuted, "Af: not all batches executed"); + if (s.totalBatchesCommitted != s.totalBatchesExecuted) { + revert NotAllBatchesExecuted(); + } } s.settlementLayer = _settlementLayer; @@ -281,8 +322,9 @@ contract AdminFacet is ZKChainBase, IAdmin { uint256 currentProtocolVersion = s.protocolVersion; uint256 protocolVersion = ctm.protocolVersion(); - require(currentProtocolVersion == protocolVersion, "CTM: protocolVersion not up to date"); - + if (currentProtocolVersion != protocolVersion) { + revert OutdatedProtocolVersion(protocolVersion, currentProtocolVersion); + } uint256 batchesExecuted = _commitment.totalBatchesExecuted; uint256 batchesVerified = _commitment.totalBatchesVerified; uint256 batchesCommitted = _commitment.totalBatchesCommitted; @@ -290,18 +332,22 @@ contract AdminFacet is ZKChainBase, IAdmin { s.totalBatchesCommitted = batchesCommitted; s.totalBatchesVerified = batchesVerified; s.totalBatchesExecuted = batchesExecuted; + s.isPermanentRollup = _commitment.isPermanentRollup; // Some consistency checks just in case. - require(batchesExecuted <= batchesVerified, "Executed is not consistent with verified"); - require(batchesVerified <= batchesCommitted, "Verified is not consistent with committed"); + if (batchesExecuted > batchesVerified) { + revert ExecutedIsNotConsistentWithVerified(batchesExecuted, batchesVerified); + } + if (batchesVerified > batchesCommitted) { + revert VerifiedIsNotConsistentWithCommitted(batchesVerified, batchesCommitted); + } // In the worst case, we may need to revert all the committed batches that were not executed. // This means that the stored batch hashes should be stored for [batchesExecuted; batchesCommitted] batches, i.e. // there should be batchesCommitted - batchesExecuted + 1 hashes. - require( - _commitment.batchHashes.length == batchesCommitted - batchesExecuted + 1, - "Invalid number of batch hashes" - ); + if (_commitment.batchHashes.length != batchesCommitted - batchesExecuted + 1) { + revert InvalidNumberOfBatchHashes(_commitment.batchHashes.length, batchesCommitted - batchesExecuted + 1); + } // Note that this part is done in O(N), i.e. it is the responsibility of the admin of the chain to ensure that the total number of // outstanding committed batches is not too long. @@ -312,17 +358,24 @@ contract AdminFacet is ZKChainBase, IAdmin { if (block.chainid == L1_CHAIN_ID) { // L1 PTree contains all L1->L2 transactions. - require( - s.priorityTree.isHistoricalRoot( + if ( + !s.priorityTree.isHistoricalRoot( _commitment.priorityTree.sides[_commitment.priorityTree.sides.length - 1] - ), - "Admin: not historical root" - ); - require(_contractAlreadyDeployed, "Af: contract not deployed"); - require(s.settlementLayer != address(0), "Af: not migrated"); - s.priorityTree.checkL1Reinit(_commitment.priorityTree); + ) + ) { + revert NotHistoricalRoot(); + } + if (!_contractAlreadyDeployed) { + revert ContractNotDeployed(); + } + if (s.settlementLayer == address(0)) { + revert NotMigrated(); + } + s.priorityTree.l1Reinit(_commitment.priorityTree); } else if (_contractAlreadyDeployed) { - require(s.settlementLayer != address(0), "Af: not migrated 2"); + if (s.settlementLayer == address(0)) { + revert NotMigrated(); + } s.priorityTree.checkGWReinit(_commitment.priorityTree); s.priorityTree.initFromCommitment(_commitment.priorityTree); } else { @@ -341,7 +394,6 @@ contract AdminFacet is ZKChainBase, IAdmin { } /// @inheritdoc IAdmin - /// @dev Note that this function does not check that the caller is the chain admin. function forwardedBridgeRecoverFailedTransfer( uint256 /* _chainId */, bytes32 /* _assetInfo */, @@ -351,13 +403,18 @@ contract AdminFacet is ZKChainBase, IAdmin { // As of now all we need in this function is the chainId so we encode it and pass it down in the _chainData field uint256 protocolVersion = abi.decode(_chainData, (uint256)); - require(s.settlementLayer != address(0), "Af: not migrated"); + if (s.settlementLayer == address(0)) { + revert NotMigrated(); + } // Sanity check that the _depositSender is the chain admin. - require(_depositSender == s.admin, "Af: not chainAdmin"); + if (_depositSender != s.admin) { + revert NotChainAdmin(_depositSender, s.admin); + } uint256 currentProtocolVersion = s.protocolVersion; - - require(currentProtocolVersion == protocolVersion, "CTM: protocolVersion not up to date"); + if (currentProtocolVersion != protocolVersion) { + revert OutdatedProtocolVersion(protocolVersion, currentProtocolVersion); + } s.settlementLayer = address(0); } @@ -366,7 +423,9 @@ contract AdminFacet is ZKChainBase, IAdmin { /// @dev Note, that this is a getter method helpful for debugging and should not be relied upon by clients. /// @return commitment The commitment for the chain. function prepareChainCommitment() public view returns (ZKChainCommitment memory commitment) { - require(s.priorityQueue.getFirstUnprocessedPriorityTx() >= s.priorityTree.startIndex, "PQ not ready"); + if (s.priorityQueue.getFirstUnprocessedPriorityTx() < s.priorityTree.startIndex) { + revert PriorityQueueNotReady(); + } commitment.totalBatchesCommitted = s.totalBatchesCommitted; commitment.totalBatchesVerified = s.totalBatchesVerified; @@ -374,16 +433,21 @@ contract AdminFacet is ZKChainBase, IAdmin { commitment.l2SystemContractsUpgradeBatchNumber = s.l2SystemContractsUpgradeBatchNumber; commitment.l2SystemContractsUpgradeTxHash = s.l2SystemContractsUpgradeTxHash; commitment.priorityTree = s.priorityTree.getCommitment(); + commitment.isPermanentRollup = s.isPermanentRollup; // just in case - require( - commitment.totalBatchesExecuted <= commitment.totalBatchesVerified, - "Verified is not consistent with executed" - ); - require( - commitment.totalBatchesVerified <= commitment.totalBatchesCommitted, - "Verified is not consistent with committed" - ); + if (commitment.totalBatchesExecuted > commitment.totalBatchesVerified) { + revert ExecutedIsNotConsistentWithVerified( + commitment.totalBatchesExecuted, + commitment.totalBatchesVerified + ); + } + if (commitment.totalBatchesVerified > commitment.totalBatchesCommitted) { + revert VerifiedIsNotConsistentWithCommitted( + commitment.totalBatchesVerified, + commitment.totalBatchesCommitted + ); + } uint256 blocksToRemember = commitment.totalBatchesCommitted - commitment.totalBatchesExecuted + 1; diff --git a/l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol b/l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol index 0875d2e95..01a15829c 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/facets/Executor.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {ZKChainBase} from "./ZKChainBase.sol"; import {IBridgehub} from "../../../bridgehub/IBridgehub.sol"; import {IMessageRoot} from "../../../bridgehub/IMessageRoot.sol"; @@ -18,6 +16,7 @@ import {IChainTypeManager} from "../../IChainTypeManager.sol"; import {PriorityTree, PriorityOpsBatchInfo} from "../../libraries/PriorityTree.sol"; import {IL1DAValidator, L1DAValidatorOutput} from "../../chain-interfaces/IL1DAValidator.sol"; import {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 {ChainWasMigrated, 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"; @@ -33,12 +32,22 @@ contract ExecutorFacet is ZKChainBase, IExecutor { /// @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; + /// @dev Checks that the chain is connected to the current bridehub and not migrated away. modifier chainOnCurrentBridgehub() { - require(s.settlementLayer == address(0), "Chain was migrated"); + if (s.settlementLayer != address(0)) { + revert ChainWasMigrated(); + } _; } + 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 @@ -199,7 +208,9 @@ contract ExecutorFacet is ZKChainBase, IExecutor { if (logSender != L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR) { revert InvalidLogSender(logSender, logKey); } - require(s.l2DAValidator == address(uint160(uint256(logValue))), "lo"); + if (s.l2DAValidator != address(uint160(uint256(logValue)))) { + revert MismatchL2DAValidator(); + } } else if (logKey == uint256(SystemLogKey.L2_DA_VALIDATOR_OUTPUT_HASH_KEY)) { if (logSender != L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR) { revert InvalidLogSender(logSender, logKey); @@ -391,17 +402,7 @@ contract ExecutorFacet is ZKChainBase, IExecutor { // Save root hash of L2 -> L1 logs tree s.l2LogsRootHashes[currentBatchNumber] = _storedBatch.l2LogsTreeRoot; - - // Once the batch is executed, we include its message to the message root. - IMessageRoot messageRootContract = IBridgehub(s.bridgehub).messageRoot(); - messageRootContract.addChainBatchRoot(s.chainId, currentBatchNumber, _storedBatch.l2LogsTreeRoot); - - // IBridgehub bridgehub = IBridgehub(s.bridgehub); - // bridgehub.messageRoot().addChainBatchRoot( - // s.chainId, - // _storedBatch.l2LogsTreeRoot, - // block.chainid != bridgehub.L1_CHAIN_ID() - // ); + _appendMessageRoot(currentBatchNumber, _storedBatch.l2LogsTreeRoot); } /// @notice Executes one batch @@ -413,7 +414,9 @@ contract ExecutorFacet is ZKChainBase, IExecutor { PriorityOpsBatchInfo memory _priorityOpsData, uint256 _executedBatchIdx ) internal { - require(_priorityOpsData.itemHashes.length == _storedBatch.numberOfLayer1Txs, "zxc"); + 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); @@ -421,11 +424,24 @@ contract ExecutorFacet is ZKChainBase, IExecutor { uint256 currentBatchNumber = _storedBatch.batchNumber; // Save root hash of L2 -> L1 logs tree - s.l2LogsRootHashes[_storedBatch.batchNumber] = _storedBatch.l2LogsTreeRoot; + s.l2LogsRootHashes[currentBatchNumber] = _storedBatch.l2LogsTreeRoot; + _appendMessageRoot(currentBatchNumber, _storedBatch.l2LogsTreeRoot); + } - // Once the batch is executed, we include its message to the message root. - IMessageRoot messageRootContract = IBridgehub(s.bridgehub).messageRoot(); - messageRootContract.addChainBatchRoot(s.chainId, 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 @@ -438,15 +454,23 @@ contract ExecutorFacet is ZKChainBase, IExecutor { (StoredBatchInfo[] memory batchesData, PriorityOpsBatchInfo[] memory priorityOpsData) = BatchDecoder .decodeAndCheckExecuteData(_executeData, _processFrom, _processTo); uint256 nBatches = batchesData.length; - require(batchesData.length == priorityOpsData.length, "bp"); + if (batchesData.length != priorityOpsData.length) { + revert InvalidBatchesDataLength(batchesData.length, priorityOpsData.length); + } for (uint256 i = 0; i < nBatches; i = i.uncheckedInc()) { if (s.priorityTree.startIndex <= s.priorityQueue.getFirstUnprocessedPriorityTx()) { _executeOneBatch(batchesData[i], priorityOpsData[i], i); } else { - require(priorityOpsData[i].leftPath.length == 0, "le"); - require(priorityOpsData[i].rightPath.length == 0, "re"); - require(priorityOpsData[i].itemHashes.length == 0, "ih"); + 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); } emit BlockExecution(batchesData[i].batchNumber, batchesData[i].batchHash, batchesData[i].commitment); diff --git a/l1-contracts/contracts/state-transition/chain-deps/facets/Getters.sol b/l1-contracts/contracts/state-transition/chain-deps/facets/Getters.sol index b5eda6d19..e7ad6ef21 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/facets/Getters.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/facets/Getters.sol @@ -110,6 +110,11 @@ contract GettersFacet is ZKChainBase, IGetters, ILegacyGetters { return _getTotalPriorityTxs(); } + /// @inheritdoc IGetters + function getPriorityTreeStartIndex() external view returns (uint256) { + return s.priorityTree.startIndex; + } + /// @inheritdoc IGetters function getFirstUnprocessedPriorityTx() external view returns (uint256) { if (s.priorityQueue.getFirstUnprocessedPriorityTx() >= s.priorityTree.startIndex) { diff --git a/l1-contracts/contracts/state-transition/chain-deps/facets/Mailbox.sol b/l1-contracts/contracts/state-transition/chain-deps/facets/Mailbox.sol index d230a04b9..87f3496e7 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/facets/Mailbox.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/facets/Mailbox.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {Math} from "@openzeppelin/contracts-v4/utils/math/Math.sol"; import {IMailbox} from "../../chain-interfaces/IMailbox.sol"; @@ -26,10 +24,9 @@ import {REQUIRED_L2_GAS_PRICE_PER_PUBDATA, L1_GAS_PER_PUBDATA_BYTE, L2_L1_LOGS_T import {L2_BOOTLOADER_ADDRESS, L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR, L2_BRIDGEHUB_ADDR} from "../../../common/L2ContractAddresses.sol"; import {IL1AssetRouter} from "../../../bridge/asset-router/IL1AssetRouter.sol"; -import {IBridgehub} from "../../../bridgehub/IBridgehub.sol"; -import {IChainTypeManager} from "../../IChainTypeManager.sol"; import {MerklePathEmpty, OnlyEraSupported, BatchNotExecuted, HashedLogIsDefault, BaseTokenGasPriceDenominatorNotSet, TransactionNotAllowed, GasPerPubdataMismatch, TooManyFactoryDeps, MsgValueTooLow} from "../../../common/L1ContractErrors.sol"; +import {NotL1, UnsupportedProofMetadataVersion, LocalRootIsZero, LocalRootMustBeZero, NotSettlementLayer, NotHyperchain} 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"; @@ -53,7 +50,9 @@ contract MailboxFacet is ZKChainBase, IMailbox { uint256 internal immutable L1_CHAIN_ID; modifier onlyL1() { - require(block.chainid == L1_CHAIN_ID, "MailboxFacet: not L1"); + if (block.chainid != L1_CHAIN_ID) { + revert NotL1(block.chainid); + } _; } @@ -152,10 +151,9 @@ contract MailboxFacet is ZKChainBase, IMailbox { if (metadataAsUint256 == 0) { // It is the new version bytes1 metadataVersion = bytes1(proofMetadata); - require( - uint256(uint8(metadataVersion)) == SUPPORTED_PROOF_METADATA_VERSION, - "Mailbox: unsupported proof metadata version" - ); + if (uint256(uint8(metadataVersion)) != SUPPORTED_PROOF_METADATA_VERSION) { + revert UnsupportedProofMetadataVersion(uint256(uint8(metadataVersion))); + } proofStartIndex = 1; logLeafProofLen = uint256(uint8(proofMetadata[1])); @@ -232,11 +230,15 @@ contract MailboxFacet is ZKChainBase, IMailbox { } bytes32 correctBatchRoot = s.l2LogsRootHashes[_batchNumber]; - require(correctBatchRoot != bytes32(0), "local root is 0"); + if (correctBatchRoot == bytes32(0)) { + revert LocalRootIsZero(); + } return correctBatchRoot == batchSettlementRoot; } - require(s.l2LogsRootHashes[_batchNumber] == bytes32(0), "local root must be 0"); + if (s.l2LogsRootHashes[_batchNumber] != bytes32(0)) { + revert LocalRootMustBeZero(); + } // Now, we'll have to check that the Gateway included the message. bytes32 batchLeafHash = MessageHashing.batchLeafHash(batchSettlementRoot, _batchNumber); @@ -273,7 +275,9 @@ contract MailboxFacet is ZKChainBase, IMailbox { // to a chain's message root only if the chain has indeed executed its batch on top of it. // // We trust all chains whitelisted by the Bridgehub governance. - require(IBridgehub(s.bridgehub).whitelistedSettlementLayers(settlementLayerChainId), "Mailbox: wrong CTM"); + if (!IBridgehub(s.bridgehub).whitelistedSettlementLayers(settlementLayerChainId)) { + revert NotSettlementLayer(); + } settlementLayerAddress = IBridgehub(s.bridgehub).getZKChain(settlementLayerChainId); } @@ -371,8 +375,12 @@ contract MailboxFacet is ZKChainBase, IMailbox { bytes32 _canonicalTxHash, uint64 _expirationTimestamp ) external override onlyL1 returns (bytes32 canonicalTxHash) { - require(IBridgehub(s.bridgehub).whitelistedSettlementLayers(s.chainId), "Mailbox SL: not SL"); - require(IChainTypeManager(s.chainTypeManager).getZKChain(_chainId) == msg.sender, "Mailbox SL: not zkChain"); + if (!IBridgehub(s.bridgehub).whitelistedSettlementLayers(s.chainId)) { + revert NotSettlementLayer(); + } + if (IChainTypeManager(s.chainTypeManager).getZKChain(_chainId) != msg.sender) { + revert NotHyperchain(); + } BridgehubL2TransactionRequest memory wrappedRequest = _wrapRequest({ _chainId: _chainId, diff --git a/l1-contracts/contracts/state-transition/chain-deps/facets/ZKChainBase.sol b/l1-contracts/contracts/state-transition/chain-deps/facets/ZKChainBase.sol index 6c8a08657..f01682456 100644 --- a/l1-contracts/contracts/state-transition/chain-deps/facets/ZKChainBase.sol +++ b/l1-contracts/contracts/state-transition/chain-deps/facets/ZKChainBase.sol @@ -6,7 +6,7 @@ import {ZKChainStorage} from "../ZKChainStorage.sol"; import {ReentrancyGuard} from "../../../common/ReentrancyGuard.sol"; import {PriorityQueue} from "../../libraries/PriorityQueue.sol"; import {PriorityTree} from "../../libraries/PriorityTree.sol"; -import {Unauthorized} from "../../../common/L1ContractErrors.sol"; +import {Unauthorized, NotSettlementLayer} from "../../../common/L1ContractErrors.sol"; /// @title Base contract containing functions accessible to the other facets. /// @author Matter Labs @@ -62,6 +62,13 @@ contract ZKChainBase is ReentrancyGuard { _; } + modifier onlySettlementLayer() { + if (s.settlementLayer != address(0)) { + revert NotSettlementLayer(); + } + _; + } + function _getTotalPriorityTxs() internal view returns (uint256) { if (s.priorityQueue.getFirstUnprocessedPriorityTx() >= s.priorityTree.startIndex) { return s.priorityTree.getTotalPriorityTxs(); diff --git a/l1-contracts/contracts/state-transition/chain-interfaces/IAdmin.sol b/l1-contracts/contracts/state-transition/chain-interfaces/IAdmin.sol index daf155e3a..ac5cfcc2d 100644 --- a/l1-contracts/contracts/state-transition/chain-interfaces/IAdmin.sol +++ b/l1-contracts/contracts/state-transition/chain-interfaces/IAdmin.sol @@ -80,6 +80,13 @@ interface IAdmin is IZKChainBase { /// @param _l2DAValidator The address of the L2 DA validator function setDAValidatorPair(address _l1DAValidator, address _l2DAValidator) external; + /// @notice Makes the chain as permanent rollup. + /// @dev This is a security feature needed for chains that should be + /// trusted to keep their data available even if the chain admin becomes malicious + /// and tries to set the DA validator pair to something which does not publish DA to Ethereum. + /// @dev DANGEROUS: once activated, there is no way back! + function makePermanentRollup() external; + /// @notice Porter availability status changes event IsPorterAvailableStatusUpdate(bool isPorterAvailable); @@ -129,8 +136,6 @@ interface IAdmin is IZKChainBase { event NewL2DAValidator(address indexed oldL2DAValidator, address indexed newL2DAValidator); event NewL1DAValidator(address indexed oldL1DAValidator, address indexed newL1DAValidator); - event BridgeInitialize(address indexed l1Token, string name, string symbol, uint8 decimals); - event BridgeMint(address indexed _account, uint256 _amount); /// @dev Similar to IL1AssetHandler interface, used to send chains. diff --git a/l1-contracts/contracts/state-transition/chain-interfaces/IExecutor.sol b/l1-contracts/contracts/state-transition/chain-interfaces/IExecutor.sol index 0877dcbf9..8ecee04b2 100644 --- a/l1-contracts/contracts/state-transition/chain-interfaces/IExecutor.sol +++ b/l1-contracts/contracts/state-transition/chain-interfaces/IExecutor.sol @@ -8,9 +8,12 @@ import {IZKChainBase} from "./IZKChainBase.sol"; enum SystemLogKey { L2_TO_L1_LOGS_TREE_ROOT_KEY, PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, - PREV_BATCH_HASH_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 diff --git a/l1-contracts/contracts/state-transition/chain-interfaces/IGetters.sol b/l1-contracts/contracts/state-transition/chain-interfaces/IGetters.sol index d2ee2b3d0..933a2a714 100644 --- a/l1-contracts/contracts/state-transition/chain-interfaces/IGetters.sol +++ b/l1-contracts/contracts/state-transition/chain-interfaces/IGetters.sol @@ -56,6 +56,10 @@ interface IGetters is IZKChainBase { /// @return The total number of priority operations that were added to the priority queue, including all processed ones function getTotalPriorityTxs() external view returns (uint256); + /// @return The start index of the priority tree, i.e. the index of the first priority operation that + /// was included into the priority tree. + function getPriorityTreeStartIndex() external view returns (uint256); + /// @return The root hash of the priority tree function getPriorityTreeRoot() external view returns (bytes32); diff --git a/l1-contracts/contracts/state-transition/chain-interfaces/IL1DAValidator.sol b/l1-contracts/contracts/state-transition/chain-interfaces/IL1DAValidator.sol index a4fe56b01..b5ea1b85c 100644 --- a/l1-contracts/contracts/state-transition/chain-interfaces/IL1DAValidator.sol +++ b/l1-contracts/contracts/state-transition/chain-interfaces/IL1DAValidator.sol @@ -23,7 +23,7 @@ struct L1DAValidatorOutput { 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 _chainId The batch number for which the data availability is being checked. + /// @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. diff --git a/l1-contracts/contracts/state-transition/data-availability/CalldataDA.sol b/l1-contracts/contracts/state-transition/data-availability/CalldataDA.sol index f1e5f7355..423511523 100644 --- a/l1-contracts/contracts/state-transition/data-availability/CalldataDA.sol +++ b/l1-contracts/contracts/state-transition/data-availability/CalldataDA.sol @@ -2,7 +2,7 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string +import {OperatorDAInputTooSmall, InvalidBlobsHashes, InvalidNumberOfBlobs, InvalidL2DAOutputHash, OnlyOneBlobWithCalldata, PubdataTooSmall, PubdataTooLong, InvalidPubdataHash} from "../L1StateTransitionErrors.sol"; /// @dev Total number of bytes in a blob. Blob = 4096 field elements * 31 bytes per field element /// @dev EIP-4844 defines it as 131_072 but we use 4096 * 31 within our circuits to always fit within a field element @@ -44,26 +44,34 @@ abstract contract CalldataDA { // - Then, there are linear hashes of the published blobs, 32 bytes each. // Check that it accommodates enough pubdata for the state diff hash, hash of pubdata + the number of blobs. - require(_operatorDAInput.length >= BLOB_DATA_OFFSET, "too small"); + if (_operatorDAInput.length < BLOB_DATA_OFFSET) { + revert OperatorDAInputTooSmall(_operatorDAInput.length, BLOB_DATA_OFFSET); + } stateDiffHash = bytes32(_operatorDAInput[:32]); fullPubdataHash = bytes32(_operatorDAInput[32:64]); blobsProvided = uint256(uint8(_operatorDAInput[64])); - require(blobsProvided <= _maxBlobsSupported, "invalid number of blobs"); + if (blobsProvided > _maxBlobsSupported) { + revert InvalidNumberOfBlobs(blobsProvided, _maxBlobsSupported); + } // Note that the API of the contract requires that the returned blobs linear hashes have length of // the `_maxBlobsSupported` blobsLinearHashes = new bytes32[](_maxBlobsSupported); - require(_operatorDAInput.length >= BLOB_DATA_OFFSET + 32 * blobsProvided, "invalid blobs hashes"); + if (_operatorDAInput.length < BLOB_DATA_OFFSET + 32 * blobsProvided) { + revert InvalidBlobsHashes(_operatorDAInput.length, BLOB_DATA_OFFSET + 32 * blobsProvided); + } _cloneCalldata(blobsLinearHashes, _operatorDAInput[BLOB_DATA_OFFSET:], blobsProvided); uint256 ptr = BLOB_DATA_OFFSET + 32 * blobsProvided; // Now, we need to double check that the provided input was indeed returned by the L2 DA validator. - require(keccak256(_operatorDAInput[:ptr]) == _l2DAValidatorOutputHash, "invalid l2 DA output hash"); + if (keccak256(_operatorDAInput[:ptr]) != _l2DAValidatorOutputHash) { + revert InvalidL2DAOutputHash(_l2DAValidatorOutputHash); + } // The rest of the output was provided specifically by the operator l1DaInput = _operatorDAInput[ptr:]; @@ -81,8 +89,12 @@ abstract contract CalldataDA { uint256 _maxBlobsSupported, bytes calldata _pubdataInput ) internal pure virtual returns (bytes32[] memory blobCommitments, bytes calldata _pubdata) { - require(_blobsProvided == 1, "only one blob with calldata"); - require(_pubdataInput.length >= BLOB_COMMITMENT_SIZE, "pubdata too small"); + if (_blobsProvided != 1) { + revert OnlyOneBlobWithCalldata(); + } + if (_pubdataInput.length < BLOB_COMMITMENT_SIZE) { + revert PubdataTooSmall(_pubdataInput.length, BLOB_COMMITMENT_SIZE); + } // We typically do not know whether we'll use calldata or blobs at the time when // we start proving the batch. That's why the blob commitment for a single blob is still present in the case of calldata. @@ -91,8 +103,12 @@ abstract contract CalldataDA { _pubdata = _pubdataInput[:_pubdataInput.length - BLOB_COMMITMENT_SIZE]; - require(_pubdata.length <= BLOB_SIZE_BYTES, "cz"); - require(_fullPubdataHash == keccak256(_pubdata), "wp"); + if (_pubdata.length > BLOB_SIZE_BYTES) { + revert PubdataTooLong(_pubdata.length, BLOB_SIZE_BYTES); + } + if (_fullPubdataHash != keccak256(_pubdata)) { + revert InvalidPubdataHash(); + } blobCommitments[0] = bytes32(_pubdataInput[_pubdataInput.length - BLOB_COMMITMENT_SIZE:_pubdataInput.length]); } diff --git a/l1-contracts/contracts/state-transition/data-availability/CalldataDAGateway.sol b/l1-contracts/contracts/state-transition/data-availability/CalldataDAGateway.sol index 3e069bbd5..0a072638f 100644 --- a/l1-contracts/contracts/state-transition/data-availability/CalldataDAGateway.sol +++ b/l1-contracts/contracts/state-transition/data-availability/CalldataDAGateway.sol @@ -3,10 +3,9 @@ pragma solidity 0.8.24; import {CalldataDA, BLOB_COMMITMENT_SIZE, BLOB_SIZE_BYTES} from "./CalldataDA.sol"; +import {PubdataTooSmall, PubdataTooLong, InvalidPubdataHash} from "../L1StateTransitionErrors.sol"; -// solhint-disable gas-custom-errors, reason-string - -/// @notice Contract that contains the functionality for process the calldata DA. +/// @notice Contract that contains the functionality for processing the calldata DA. /// @dev The expected l2DAValidator that should be used with it `RollupL2DAValidator`. abstract contract CalldataDAGateway is CalldataDA { /// @inheritdoc CalldataDA @@ -16,7 +15,9 @@ abstract contract CalldataDAGateway is CalldataDA { uint256 _maxBlobsSupported, bytes calldata _pubdataInput ) internal pure override returns (bytes32[] memory blobCommitments, bytes calldata _pubdata) { - require(_pubdataInput.length >= _blobsProvided * BLOB_COMMITMENT_SIZE, "pubdata too small"); + if (_pubdataInput.length < _blobsProvided * BLOB_COMMITMENT_SIZE) { + revert PubdataTooSmall(_pubdataInput.length, _blobsProvided * BLOB_COMMITMENT_SIZE); + } // We typically do not know whether we'll use calldata or blobs at the time when // we start proving the batch. That's why the blob commitment for a single blob is still present in the case of calldata. @@ -24,8 +25,12 @@ abstract contract CalldataDAGateway is CalldataDA { _pubdata = _pubdataInput[:_pubdataInput.length - _blobsProvided * BLOB_COMMITMENT_SIZE]; - require(_pubdata.length <= _blobsProvided * BLOB_SIZE_BYTES, "cz"); - require(_fullPubdataHash == keccak256(_pubdata), "wp"); + if (_pubdata.length > _blobsProvided * BLOB_SIZE_BYTES) { + revert PubdataTooLong(_pubdata.length, _blobsProvided * BLOB_SIZE_BYTES); + } + if (_fullPubdataHash != keccak256(_pubdata)) { + revert InvalidPubdataHash(); + } bytes calldata providedCommitments = _pubdataInput[_pubdataInput.length - _blobsProvided * diff --git a/l1-contracts/contracts/state-transition/data-availability/RelayedSLDAValidator.sol b/l1-contracts/contracts/state-transition/data-availability/RelayedSLDAValidator.sol index d5f3473a7..0a37e8986 100644 --- a/l1-contracts/contracts/state-transition/data-availability/RelayedSLDAValidator.sol +++ b/l1-contracts/contracts/state-transition/data-availability/RelayedSLDAValidator.sol @@ -2,8 +2,6 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {IL1DAValidator, L1DAValidatorOutput, PubdataSource} from "../chain-interfaces/IL1DAValidator.sol"; import {IL1Messenger} from "../../common/interfaces/IL1Messenger.sol"; @@ -11,6 +9,7 @@ import {CalldataDAGateway} from "./CalldataDAGateway.sol"; import {IBridgehub} from "../../bridgehub/IBridgehub.sol"; import {L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR, L2_BRIDGEHUB_ADDR} from "../../common/L2ContractAddresses.sol"; +import {BlobHashBlobCommitmentMismatchValue, L1DAValidatorInvalidSender, InvalidPubdataSource} from "../L1StateTransitionErrors.sol"; /// @notice The DA validator intended to be used in Era-environment. /// @dev For compatibility reasons it accepts calldata in the same format as the `RollupL1DAValidator`, but unlike the latter it @@ -22,7 +21,9 @@ contract RelayedSLDAValidator is IL1DAValidator, CalldataDAGateway { function _ensureOnlyChainSender(uint256 _chainId) internal view { // Note that this contract is only supposed to be deployed on L2, where the // bridgehub is predeployed at `L2_BRIDGEHUB_ADDR` address. - require(IBridgehub(L2_BRIDGEHUB_ADDR).getZKChain(_chainId) == msg.sender, "l1-da-validator/invalid-sender"); + if (IBridgehub(L2_BRIDGEHUB_ADDR).getZKChain(_chainId) != msg.sender) { + revert L1DAValidatorInvalidSender(msg.sender); + } } /// @dev Relays the calldata to L1. @@ -84,18 +85,19 @@ contract RelayedSLDAValidator is IL1DAValidator, CalldataDAGateway { output.blobsOpeningCommitments = blobCommitments; } else { - revert("l1-da-validator/invalid-pubdata-source"); + revert InvalidPubdataSource(pubdataSource); } // We verify that for each set of blobHash/blobCommitment are either both empty // or there are values for both. // This is mostly a sanity check and it is not strictly required. for (uint256 i = 0; i < _maxBlobsSupported; ++i) { - require( - (output.blobsLinearHashes[i] == bytes32(0) && output.blobsOpeningCommitments[i] == bytes32(0)) || - (output.blobsLinearHashes[i] != bytes32(0) && output.blobsOpeningCommitments[i] != bytes32(0)), - "bh" - ); + if ( + (output.blobsLinearHashes[i] != bytes32(0) || output.blobsOpeningCommitments[i] != bytes32(0)) && + (output.blobsLinearHashes[i] == bytes32(0) || output.blobsOpeningCommitments[i] == bytes32(0)) + ) { + revert BlobHashBlobCommitmentMismatchValue(); + } } } } diff --git a/l1-contracts/contracts/state-transition/data-availability/RollupDAManager.sol b/l1-contracts/contracts/state-transition/data-availability/RollupDAManager.sol new file mode 100644 index 000000000..83987a020 --- /dev/null +++ b/l1-contracts/contracts/state-transition/data-availability/RollupDAManager.sol @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.18; + +import {Ownable2Step} from "@openzeppelin/contracts-v4/access/Ownable2Step.sol"; +import {ZeroAddress} from "../../common/L1ContractErrors.sol"; + +/// @title The RollupManager contract +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice Responsible for determining which DA pairs are allowed to be used +/// for permanent rollups. +contract RollupDAManager is Ownable2Step { + /// @dev Mapping to track the status (enabled/disabled) of each DAPair. + mapping(address l1DAValidator => mapping(address l2DAValidator => bool)) public allowedDAPairs; + + /// @dev Emitted when a DAPair is added or updated. + /// @param l1DAValidator Address of the L1 data availability validator. + /// @param l2DAValidator Address of the L2 data availability validator. + /// @param status Boolean representing the state of the DAPair. + event DAPairUpdated(address indexed l1DAValidator, address indexed l2DAValidator, bool status); + + /// @dev Modifier to ensure addresses in DAPair are not zero addresses. + /// @param l1DAValidator Address of the L1 data availability validator. + /// @param l2DAValidator Address of the L2 data availability validator. + modifier validAddresses(address l1DAValidator, address l2DAValidator) { + if (l1DAValidator == address(0) || l2DAValidator == address(0)) { + revert ZeroAddress(); + } + _; + } + + /// @dev Adds or updates a DAPair in the `allowedDAPairs` mapping. Only callable by the contract owner. + /// + /// Emits a {DAPairUpdated} event. + /// + /// @param _l1DAValidator Address of the L1 data availability validator. + /// @param _l2DAValidator Address of the L2 data availability validator. + /// @param _status Boolean representing whether the DAPair is active or not. + /// + /// Requirements: + /// + /// - The `l1DAValidator` and `l2DAValidator` must be valid addresses (non-zero). + /// - Only the owner of the contract can call this function. + function updateDAPair( + address _l1DAValidator, + address _l2DAValidator, + bool _status + ) external onlyOwner validAddresses(_l1DAValidator, _l2DAValidator) { + allowedDAPairs[_l1DAValidator][_l2DAValidator] = _status; + + emit DAPairUpdated(_l1DAValidator, _l2DAValidator, _status); + } + + /// @notice Returns whether the DA pair is allowed. + /// + /// @param _l1DAValidator Address of the L1 data availability validator. + /// @param _l2DAValidator Address of the L2 data availability validator. + /// @return bool indicating if the DA pair is allowed. + function isPairAllowed(address _l1DAValidator, address _l2DAValidator) external view returns (bool) { + return allowedDAPairs[_l1DAValidator][_l2DAValidator]; + } +} diff --git a/l1-contracts/contracts/state-transition/data-availability/ValidiumL1DAValidator.sol b/l1-contracts/contracts/state-transition/data-availability/ValidiumL1DAValidator.sol index 15825bbdd..24f0919e3 100644 --- a/l1-contracts/contracts/state-transition/data-availability/ValidiumL1DAValidator.sol +++ b/l1-contracts/contracts/state-transition/data-availability/ValidiumL1DAValidator.sol @@ -2,9 +2,8 @@ pragma solidity 0.8.24; -// solhint-disable gas-custom-errors, reason-string - import {IL1DAValidator, L1DAValidatorOutput} from "../chain-interfaces/IL1DAValidator.sol"; +import {ValL1DAWrongInputLength} from "../L1StateTransitionErrors.sol"; contract ValidiumL1DAValidator is IL1DAValidator { function checkDA( @@ -16,8 +15,9 @@ contract ValidiumL1DAValidator is IL1DAValidator { ) external override returns (L1DAValidatorOutput memory output) { // For Validiums, we expect the operator to just provide the data for us. // We don't need to do any checks with regard to the l2DAValidatorOutputHash. - require(_operatorDAInput.length == 32, "ValL1DA wrong input length"); - + if (_operatorDAInput.length != 32) { + revert ValL1DAWrongInputLength(_operatorDAInput.length, 32); + } bytes32 stateDiffHash = abi.decode(_operatorDAInput, (bytes32)); // The rest of the fields that relate to blobs are empty. diff --git a/l1-contracts/contracts/state-transition/l2-deps/IL2GenesisUpgrade.sol b/l1-contracts/contracts/state-transition/l2-deps/IL2GenesisUpgrade.sol index 6221f2e18..418e68512 100644 --- a/l1-contracts/contracts/state-transition/l2-deps/IL2GenesisUpgrade.sol +++ b/l1-contracts/contracts/state-transition/l2-deps/IL2GenesisUpgrade.sol @@ -15,10 +15,16 @@ struct ForceDeployment { bytes input; } +// solhint-disable-next-line gas-struct-packing struct ZKChainSpecificForceDeploymentsData { bytes32 baseTokenAssetId; address l2LegacySharedBridge; - address l2Weth; + address predeployedL2WethAddress; + address baseTokenL1Address; + /// @dev Some info about the base token, it is + /// needed to deploy weth token in case it is not present + string baseTokenName; + string baseTokenSymbol; } /// @author Matter Labs diff --git a/l1-contracts/contracts/state-transition/libraries/PriorityTree.sol b/l1-contracts/contracts/state-transition/libraries/PriorityTree.sol index 71d6d9df1..53325845a 100644 --- a/l1-contracts/contracts/state-transition/libraries/PriorityTree.sol +++ b/l1-contracts/contracts/state-transition/libraries/PriorityTree.sol @@ -2,11 +2,10 @@ // We use a floating point pragma here so it can be used within other projects that interact with the zkSync ecosystem without using our exact pragma version. pragma solidity ^0.8.21; -// solhint-disable gas-custom-errors - import {DynamicIncrementalMerkle} from "../../common/libraries/DynamicIncrementalMerkle.sol"; import {Merkle} from "../../common/libraries/Merkle.sol"; import {PriorityTreeCommitment} from "../../common/Config.sol"; +import {RootMismatch, InvalidCommitment, InvalidStartIndex, InvalidUnprocessedIndex, InvalidNextLeafIndex} from "../L1StateTransitionErrors.sol"; struct PriorityOpsBatchInfo { bytes32[] leftPath; @@ -27,7 +26,7 @@ library PriorityTree { DynamicIncrementalMerkle.Bytes32PushTree tree; } - /// @notice Returns zero if and only if no operations were processed from the queue + /// @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; @@ -75,7 +74,9 @@ library PriorityTree { _tree.unprocessedIndex, _priorityOpsData.itemHashes ); - require(_tree.historicalRoots[expectedRoot], "PT: root mismatch"); + if (!_tree.historicalRoots[expectedRoot]) { + revert RootMismatch(); + } _tree.unprocessedIndex += _priorityOpsData.itemHashes.length; } } @@ -83,7 +84,9 @@ library PriorityTree { /// @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. - require(height > 0, "PT: invalid commitment"); + if (height == 0) { + revert InvalidCommitment(); + } _tree.startIndex = _commitment.startIndex; _tree.unprocessedIndex = _commitment.unprocessedIndex; _tree.tree._nextLeafIndex = _commitment.nextLeafIndex; @@ -98,17 +101,31 @@ library PriorityTree { } /// @notice Reinitialize the tree from a commitment on L1. - function checkL1Reinit(Tree storage _tree, PriorityTreeCommitment memory _commitment) internal view { - require(_tree.startIndex == _commitment.startIndex, "PT: invalid start index"); - require(_tree.unprocessedIndex >= _commitment.unprocessedIndex, "PT: invalid unprocessed index"); - require(_tree.tree._nextLeafIndex >= _commitment.nextLeafIndex, "PT: invalid next leaf index"); + 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 { - require(_tree.startIndex == _commitment.startIndex, "PT: invalid start index"); - require(_tree.unprocessedIndex <= _commitment.unprocessedIndex, "PT: invalid unprocessed index"); - require(_tree.tree._nextLeafIndex <= _commitment.nextLeafIndex, "PT: invalid next leaf index"); + 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. diff --git a/l1-contracts/contracts/transactionFilterer/GatewayTransactionFilterer.sol b/l1-contracts/contracts/transactionFilterer/GatewayTransactionFilterer.sol index ebcb37ff8..25d57ce4f 100644 --- a/l1-contracts/contracts/transactionFilterer/GatewayTransactionFilterer.sol +++ b/l1-contracts/contracts/transactionFilterer/GatewayTransactionFilterer.sol @@ -8,7 +8,6 @@ import {ReentrancyGuard} from "../common/ReentrancyGuard.sol"; import {AlreadyWhitelisted, InvalidSelector, NotWhitelisted, ZeroAddress} from "../common/L1ContractErrors.sol"; import {ITransactionFilterer} from "../state-transition/chain-interfaces/ITransactionFilterer.sol"; import {IBridgehub} from "../bridgehub/IBridgehub.sol"; -import {IL2Bridge} from "../bridge/interfaces/IL2Bridge.sol"; import {IAssetRouterBase} from "../bridge/asset-router/IAssetRouterBase.sol"; import {IL2AssetRouter} from "../bridge/asset-router/IL2AssetRouter.sol"; @@ -86,25 +85,22 @@ contract GatewayTransactionFilterer is ITransactionFilterer, ReentrancyGuard, Ow if (IL2AssetRouter.setAssetHandlerAddress.selector == l2TxSelector) { (, bytes32 decodedAssetId, ) = abi.decode(l2Calldata[4:], (uint256, bytes32, address)); - return _checkSTMAssetId(decodedAssetId); + return _checkCTMAssetId(decodedAssetId); } - if ( - IAssetRouterBase.finalizeDeposit.selector != l2TxSelector && - IL2Bridge.finalizeDeposit.selector != l2TxSelector - ) { + if (IAssetRouterBase.finalizeDeposit.selector != l2TxSelector) { revert InvalidSelector(l2TxSelector); } (, bytes32 decodedAssetId, ) = abi.decode(l2Calldata[4:], (uint256, bytes32, bytes)); - return _checkSTMAssetId(decodedAssetId); + return _checkCTMAssetId(decodedAssetId); } return whitelistedSenders[sender]; } - function _checkSTMAssetId(bytes32 assetId) internal view returns (bool) { - address stmAddress = BRIDGE_HUB.ctmAssetIdToAddress(assetId); - return stmAddress != address(0); + function _checkCTMAssetId(bytes32 assetId) internal view returns (bool) { + address ctmAddress = BRIDGE_HUB.ctmAssetIdToAddress(assetId); + return ctmAddress != address(0); } } diff --git a/l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol b/l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol index edae3870b..a619e5311 100644 --- a/l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol +++ b/l1-contracts/contracts/upgrades/BaseZkSyncUpgrade.sol @@ -11,12 +11,11 @@ import {L2ContractHelper} from "../common/libraries/L2ContractHelper.sol"; import {TransactionValidator} from "../state-transition/libraries/TransactionValidator.sol"; import {MAX_NEW_FACTORY_DEPS, SYSTEM_UPGRADE_L2_TX_TYPE, MAX_ALLOWED_MINOR_VERSION_DELTA} from "../common/Config.sol"; import {L2CanonicalTransaction} from "../common/Messaging.sol"; -import {ProtocolVersionMinorDeltaTooBig, TimeNotReached, InvalidTxType, L2UpgradeNonceNotEqualToNewProtocolVersion, TooManyFactoryDeps, UnexpectedNumberOfFactoryDeps, ProtocolVersionTooSmall, PreviousUpgradeNotFinalized, PreviousUpgradeNotCleaned, L2BytecodeHashMismatch, PatchCantSetUpgradeTxn, PreviousProtocolMajorVersionNotZero, NewProtocolMajorVersionNotZero, PatchUpgradeCantSetDefaultAccount, PatchUpgradeCantSetBootloader} from "./ZkSyncUpgradeErrors.sol"; +import {ProtocolVersionMinorDeltaTooBig, TimeNotReached, InvalidTxType, L2UpgradeNonceNotEqualToNewProtocolVersion, TooManyFactoryDeps, ProtocolVersionTooSmall, PreviousUpgradeNotFinalized, PreviousUpgradeNotCleaned, PatchCantSetUpgradeTxn, PreviousProtocolMajorVersionNotZero, NewProtocolMajorVersionNotZero, PatchUpgradeCantSetDefaultAccount, PatchUpgradeCantSetBootloader} from "./ZkSyncUpgradeErrors.sol"; import {SemVer} from "../common/libraries/SemVer.sol"; /// @notice The struct that represents the upgrade proposal. /// @param l2ProtocolUpgradeTx The system upgrade transaction. -/// @param factoryDeps The list of factory deps for the l2ProtocolUpgradeTx. /// @param bootloaderHash The hash of the new bootloader bytecode. If zero, it will not be updated. /// @param defaultAccountHash The hash of the new default account bytecode. If zero, it will not be updated. /// @param verifier The address of the new verifier. If zero, the verifier will not be updated. @@ -30,7 +29,6 @@ import {SemVer} from "../common/libraries/SemVer.sol"; /// the previous protocol version. struct ProposedUpgrade { L2CanonicalTransaction l2ProtocolUpgradeTx; - bytes[] factoryDeps; bytes32 bootloaderHash; bytes32 defaultAccountHash; address verifier; @@ -63,7 +61,7 @@ abstract contract BaseZkSyncUpgrade is ZKChainBase { /// @notice Notifies about complete upgrade event UpgradeComplete(uint256 indexed newProtocolVersion, bytes32 indexed l2UpgradeTxHash, ProposedUpgrade upgrade); - /// @notice The main function that will be provided by the upgrade proxy + /// @notice The main function that will be delegate-called by the chain. /// @dev This is a virtual function and should be overridden by custom upgrade implementations. /// @param _proposedUpgrade The upgrade to be executed. /// @return txHash The hash of the L2 system contract upgrade transaction. @@ -81,12 +79,7 @@ abstract contract BaseZkSyncUpgrade is ZKChainBase { _upgradeVerifier(_proposedUpgrade.verifier, _proposedUpgrade.verifierParams); _setBaseSystemContracts(_proposedUpgrade.bootloaderHash, _proposedUpgrade.defaultAccountHash, isPatchOnly); - txHash = _setL2SystemContractUpgrade( - _proposedUpgrade.l2ProtocolUpgradeTx, - _proposedUpgrade.factoryDeps, - newMinorVersion, - isPatchOnly - ); + txHash = _setL2SystemContractUpgrade(_proposedUpgrade.l2ProtocolUpgradeTx, newMinorVersion, isPatchOnly); _postUpgrade(_proposedUpgrade.postUpgradeCalldata); @@ -193,14 +186,12 @@ abstract contract BaseZkSyncUpgrade is ZKChainBase { /// @notice Sets the hash of the L2 system contract upgrade transaction for the next batch to be committed /// @dev If the transaction is noop (i.e. its type is 0) it does nothing and returns 0. /// @param _l2ProtocolUpgradeTx The L2 system contract upgrade transaction. - /// @param _factoryDeps The factory dependencies that are used by the transaction. /// @param _newMinorProtocolVersion The new minor protocol version. It must be used as the `nonce` field /// of the `_l2ProtocolUpgradeTx`. /// @param _patchOnly Whether only the patch part of the protocol version semver has changed. /// @return System contracts upgrade transaction hash. Zero if no upgrade transaction is set. function _setL2SystemContractUpgrade( L2CanonicalTransaction calldata _l2ProtocolUpgradeTx, - bytes[] calldata _factoryDeps, uint32 _newMinorProtocolVersion, bool _patchOnly ) internal returns (bytes32) { @@ -233,7 +224,7 @@ abstract contract BaseZkSyncUpgrade is ZKChainBase { revert L2UpgradeNonceNotEqualToNewProtocolVersion(_l2ProtocolUpgradeTx.nonce, _newMinorProtocolVersion); } - _verifyFactoryDeps(_factoryDeps, _l2ProtocolUpgradeTx.factoryDeps); + _verifyFactoryDeps(_l2ProtocolUpgradeTx.factoryDeps); bytes32 l2ProtocolUpgradeTxHash = keccak256(encodedTransaction); @@ -242,24 +233,15 @@ abstract contract BaseZkSyncUpgrade is ZKChainBase { return l2ProtocolUpgradeTxHash; } - /// @notice Verifies that the factory deps correspond to the proper hashes - /// @param _factoryDeps The list of factory deps - /// @param _expectedHashes The list of expected bytecode hashes - function _verifyFactoryDeps(bytes[] calldata _factoryDeps, uint256[] calldata _expectedHashes) private pure { - if (_factoryDeps.length != _expectedHashes.length) { - revert UnexpectedNumberOfFactoryDeps(); - } - if (_factoryDeps.length > MAX_NEW_FACTORY_DEPS) { + /// @notice Verifies that the factory deps provided are in the correct format + /// @param _hashes The list of hashes of factory deps + /// @dev Note, that unlike normal L1->L2 transactions, factory dependencies for + /// an upgrade transaction should be made available prior to the upgrade via publishing those + /// to the `BytecodesSupplier` contract. + function _verifyFactoryDeps(uint256[] calldata _hashes) private pure { + if (_hashes.length > MAX_NEW_FACTORY_DEPS) { revert TooManyFactoryDeps(); } - uint256 length = _factoryDeps.length; - - for (uint256 i = 0; i < length; ++i) { - bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(_factoryDeps[i]); - if (bytecodeHash != bytes32(_expectedHashes[i])) { - revert L2BytecodeHashMismatch(bytecodeHash, bytes32(_expectedHashes[i])); - } - } } /// @notice Changes the protocol version diff --git a/l1-contracts/contracts/upgrades/BytecodesSupplier.sol b/l1-contracts/contracts/upgrades/BytecodesSupplier.sol new file mode 100644 index 000000000..c27c1a1ea --- /dev/null +++ b/l1-contracts/contracts/upgrades/BytecodesSupplier.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {L2ContractHelper} from "../common/libraries/L2ContractHelper.sol"; +import {BytecodeAlreadyPublished} from "../common/L1ContractErrors.sol"; + +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice Contract that is used to track published L2 bytecodes. +/// It will be the contract to which the preimages for the factory dependencies protocol upgrade transaction +/// will be submitted to. +/// @dev The contract has no access control as anyone is allowed to publish any bytecode. +contract BytecodesSupplier { + /// @notice Event emitted when a bytecode is published. + event BytecodePublished(bytes32 indexed bytecodeHash, bytes bytecode); + + /// @notice Mapping of bytecode hashes to the block number when they were published. + mapping(bytes32 bytecodeHash => uint256 blockNumber) public publishingBlock; + + /// @notice Publishes the bytecode hash and the bytecode itself. + /// @param _bytecode Bytecode to be published. + function publishBytecode(bytes calldata _bytecode) public { + bytes32 bytecodeHash = L2ContractHelper.hashL2BytecodeCalldata(_bytecode); + + if (publishingBlock[bytecodeHash] != 0) { + revert BytecodeAlreadyPublished(bytecodeHash); + } + + publishingBlock[bytecodeHash] = block.number; + + emit BytecodePublished(bytecodeHash, _bytecode); + } + + /// @notice Publishes multiple bytecodes. + /// @param _bytecodes Array of bytecodes to be published. + function publishBytecodes(bytes[] calldata _bytecodes) public { + // solhint-disable-next-line gas-length-in-loops + for (uint256 i = 0; i < _bytecodes.length; ++i) { + publishBytecode(_bytecodes[i]); + } + } +} diff --git a/l1-contracts/contracts/upgrades/DefaultUpgrade.sol b/l1-contracts/contracts/upgrades/DefaultUpgrade.sol index c6ebb18dc..87c6dd220 100644 --- a/l1-contracts/contracts/upgrades/DefaultUpgrade.sol +++ b/l1-contracts/contracts/upgrades/DefaultUpgrade.sol @@ -8,7 +8,7 @@ import {BaseZkSyncUpgrade, ProposedUpgrade} from "./BaseZkSyncUpgrade.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev contract DefaultUpgrade is BaseZkSyncUpgrade { - /// @notice The main function that will be called by the upgrade proxy. + /// @notice The main function that will be delegate-called by the chain. /// @param _proposedUpgrade The upgrade to be executed. function upgrade(ProposedUpgrade calldata _proposedUpgrade) public override returns (bytes32) { super.upgrade(_proposedUpgrade); diff --git a/l1-contracts/contracts/upgrades/GatewayHelper.sol b/l1-contracts/contracts/upgrades/GatewayHelper.sol deleted file mode 100644 index 5ae02b9a0..000000000 --- a/l1-contracts/contracts/upgrades/GatewayHelper.sol +++ /dev/null @@ -1,24 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.8.24; - -import {IL1SharedBridgeLegacy} from "../bridge/interfaces/IL1SharedBridgeLegacy.sol"; -import {IBridgehub} from "../bridgehub/IBridgehub.sol"; - -import {ZKChainSpecificForceDeploymentsData} from "../state-transition/l2-deps/IL2GenesisUpgrade.sol"; - -import {ZKChainStorage} from "../state-transition/chain-deps/ZKChainStorage.sol"; - -library GatewayHelper { - function getZKChainSpecificForceDeploymentsData(ZKChainStorage storage s) internal view returns (bytes memory) { - address sharedBridge = IBridgehub(s.bridgehub).sharedBridge(); - address legacySharedBridge = IL1SharedBridgeLegacy(sharedBridge).l2BridgeAddress(s.chainId); - ZKChainSpecificForceDeploymentsData - memory additionalForceDeploymentsData = ZKChainSpecificForceDeploymentsData({ - baseTokenAssetId: s.baseTokenAssetId, - l2LegacySharedBridge: legacySharedBridge, - l2Weth: address(0) // kl todo - }); - return abi.encode(additionalForceDeploymentsData); - } -} diff --git a/l1-contracts/contracts/upgrades/GatewayUpgrade.sol b/l1-contracts/contracts/upgrades/GatewayUpgrade.sol index 3420d81ae..5274c44c3 100644 --- a/l1-contracts/contracts/upgrades/GatewayUpgrade.sol +++ b/l1-contracts/contracts/upgrades/GatewayUpgrade.sol @@ -9,23 +9,21 @@ import {DataEncoding} from "../common/libraries/DataEncoding.sol"; import {Diamond} from "../state-transition/libraries/Diamond.sol"; import {PriorityQueue} from "../state-transition/libraries/PriorityQueue.sol"; import {PriorityTree} from "../state-transition/libraries/PriorityTree.sol"; +import {GatewayUpgradeFailed} from "./ZkSyncUpgradeErrors.sol"; import {IGatewayUpgrade} from "./IGatewayUpgrade.sol"; -import {IComplexUpgrader} from "../state-transition/l2-deps/IComplexUpgrader.sol"; -import {IL2GatewayUpgrade} from "../state-transition/l2-deps/IL2GatewayUpgrade.sol"; - import {IL2ContractDeployer} from "../common/interfaces/IL2ContractDeployer.sol"; - -import {GatewayHelper} from "./GatewayHelper.sol"; +import {L1GatewayHelper} from "./L1GatewayHelper.sol"; // solhint-disable-next-line gas-struct-packing struct GatewayUpgradeEncodedInput { - IL2ContractDeployer.ForceDeployment[] baseForceDeployments; + IL2ContractDeployer.ForceDeployment[] forceDeployments; + uint256 l2GatewayUpgradePosition; bytes fixedForceDeploymentsData; address ctmDeployer; - address l2GatewayUpgrade; address oldValidatorTimelock; address newValidatorTimelock; + address wrappedBaseTokenStore; } /// @author Matter Labs @@ -35,14 +33,17 @@ contract GatewayUpgrade is BaseZkSyncUpgrade { using PriorityQueue for PriorityQueue.Queue; using PriorityTree for PriorityTree.Tree; + /// @notice The address of this contract. + /// @dev needed as this address is delegateCalled, and we delegateCall it again. address public immutable THIS_ADDRESS; constructor() { THIS_ADDRESS = address(this); } - /// @notice The main function that will be called by the upgrade proxy. + /// @notice The main function that will be delegate-called by the chain. /// @param _proposedUpgrade The upgrade to be executed. + /// @dev Doesn't require any access-control restrictions as the contract is used in the delegate call. function upgrade(ProposedUpgrade calldata _proposedUpgrade) public override returns (bytes32) { GatewayUpgradeEncodedInput memory encodedInput = abi.decode( _proposedUpgrade.postUpgradeCalldata, @@ -57,31 +58,32 @@ contract GatewayUpgrade is BaseZkSyncUpgrade { s.validators[encodedInput.newValidatorTimelock] = true; ProposedUpgrade memory proposedUpgrade = _proposedUpgrade; - bytes memory gatewayUpgradeCalldata = abi.encodeCall( - IL2GatewayUpgrade.upgrade, - ( - encodedInput.baseForceDeployments, - encodedInput.ctmDeployer, - encodedInput.fixedForceDeploymentsData, - GatewayHelper.getZKChainSpecificForceDeploymentsData(s) + bytes memory gatewayUpgradeCalldata = abi.encode( + encodedInput.ctmDeployer, + encodedInput.fixedForceDeploymentsData, + L1GatewayHelper.getZKChainSpecificForceDeploymentsData( + s, + encodedInput.wrappedBaseTokenStore, + s.__DEPRECATED_baseToken ) ); + encodedInput.forceDeployments[encodedInput.l2GatewayUpgradePosition].input = gatewayUpgradeCalldata; proposedUpgrade.l2ProtocolUpgradeTx.data = abi.encodeCall( - IComplexUpgrader.upgrade, - (encodedInput.l2GatewayUpgrade, gatewayUpgradeCalldata) + IL2ContractDeployer.forceDeployOnAddresses, + (encodedInput.forceDeployments) ); // slither-disable-next-line controlled-delegatecall - (bool success, ) = THIS_ADDRESS.delegatecall( - abi.encodeWithSelector(IGatewayUpgrade.upgradeExternal.selector, proposedUpgrade) - ); - // solhint-disable-next-line gas-custom-errors - require(success, "GatewayUpgrade: upgrade failed"); + (bool success, ) = THIS_ADDRESS.delegatecall(abi.encodeCall(IGatewayUpgrade.upgradeExternal, proposedUpgrade)); + if (!success) { + revert GatewayUpgradeFailed(); + } return Diamond.DIAMOND_INIT_SUCCESS_RETURN_VALUE; } /// @notice The function that will be called from this same contract, we need an external call to be able to modify _proposedUpgrade (memory/calldata). + /// @dev Doesn't require any access-control restrictions as the contract is used in the delegate call. function upgradeExternal(ProposedUpgrade calldata _proposedUpgrade) external { super.upgrade(_proposedUpgrade); } diff --git a/l1-contracts/contracts/upgrades/GovernanceUpgradeTimer.sol b/l1-contracts/contracts/upgrades/GovernanceUpgradeTimer.sol new file mode 100644 index 000000000..f4b237da1 --- /dev/null +++ b/l1-contracts/contracts/upgrades/GovernanceUpgradeTimer.sol @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.18; + +import {Ownable2Step} from "@openzeppelin/contracts-v4/access/Ownable2Step.sol"; +import {ZeroAddress, TimerAlreadyStarted, CallerNotTimerAdmin, DeadlineNotYetPassed, NewDeadlineNotGreaterThanCurrent, NewDeadlineExceedsMaxDeadline} from "../common/L1ContractErrors.sol"; + +/// @title Governance Upgrade Timer +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice This contract will be used by the governance to ensure that the chains have enough time +/// to upgrade their implementation before finalizing the upgrade on L1. +/// @notice The `startTimer` function should be called once the new version is published. It starts the +/// timer and gives at least `INITIAL_DELAY` for the chains to upgrade. In case for any reason the timeline has to +/// be extended, the owner of this contract can increase the timeline, but only the maximum of `MAX_ADDITIONAL_DELAY` +/// is allowed. +contract GovernanceUpgradeTimer is Ownable2Step { + /// @notice The initial delay to be used. + uint256 public immutable INITIAL_DELAY; + /// @notice The maximal delay for the upgrade. + uint256 public immutable MAX_ADDITIONAL_DELAY; + /// @notice The address that can start the timer. + address public immutable TIMER_GOVERNANCE; + + /// @notice The deadline which we should wait. + uint256 public deadline; + /// @notice The maximal deadline to which the owner of this contract can + /// increase the deadline. + uint256 public maxDeadline; + + /// @dev Emitted when the timer is started, logging the initial `deadline` and `maxDeadline`. + /// @param deadline The initial deadline set for the timer. + /// @param maxDeadline The maximum deadline the timer can be extended to. + event TimerStarted(uint256 deadline, uint256 maxDeadline); + + /// @dev Emitted when the owner changes the deadline. + /// @param newDeadline The new deadline set by the owner. + event DeadlineChanged(uint256 newDeadline); + + /// @dev Initializes the contract with immutable values for `INITIAL_DELAY`, `MAX_ADDITIONAL_DELAY`, and `TIMER_GOVERNANCE`. + /// @param _initialDelay The initial delay in seconds to be added to the current block timestamp to set the deadline. + /// @param _maxAdditionalDelay The maximum number of seconds that can be added to the initial delay to set `maxDeadline`. + /// @param _timerGovernance The address of the timer administrator, who is allowed to start the timer. + /// @param _initialOwner The initial owner of the contract. + constructor(uint256 _initialDelay, uint256 _maxAdditionalDelay, address _timerGovernance, address _initialOwner) { + if (_timerGovernance == address(0)) { + revert ZeroAddress(); + } + + INITIAL_DELAY = _initialDelay; + MAX_ADDITIONAL_DELAY = _maxAdditionalDelay; + TIMER_GOVERNANCE = _timerGovernance; + + _transferOwnership(_initialOwner); + } + + /// @dev Modifier that restricts function access to the `TIMER_GOVERNANCE` address. + /// Reverts with a custom error if the caller is not `TIMER_GOVERNANCE`. + modifier onlyTimerAdmin() { + if (msg.sender != TIMER_GOVERNANCE) { + revert CallerNotTimerAdmin(); + } + _; + } + + /// @dev Starts the timer by setting the `deadline` and `maxDeadline`. Only callable by the `TIMER_GOVERNANCE`. + /// + /// Emits a {TimerStarted} event. + function startTimer() external onlyTimerAdmin { + if (deadline != 0) { + revert TimerAlreadyStarted(); + } + + deadline = block.timestamp + INITIAL_DELAY; + maxDeadline = deadline + MAX_ADDITIONAL_DELAY; + + emit TimerStarted(deadline, maxDeadline); + } + + /// @dev Checks if the current `deadline` has passed. Reverts if the deadline has already passed. + /// + /// Reverts with {DeadlineNotYetPassed} error if the current block timestamp is less than `deadline`. + function checkDeadline() external view { + if (block.timestamp < deadline) { + revert DeadlineNotYetPassed(); + } + } + + /// @dev Allows the owner to change the current `deadline` to a new value. + /// + /// The new deadline must be greater than the current deadline and must not exceed `maxDeadline`. + /// + /// Emits a {DeadlineChanged} event. + /// + /// @param newDeadline The new deadline to be set. + /// + /// Reverts with {NewDeadlineNotGreaterThanCurrent} if the new deadline is not greater than the current one. + /// Reverts with {NewDeadlineExceedsMaxDeadline} if the new deadline exceeds `maxDeadline`. + function changeDeadline(uint256 newDeadline) external onlyOwner { + if (newDeadline <= deadline) { + revert NewDeadlineNotGreaterThanCurrent(); + } + if (newDeadline > maxDeadline) { + revert NewDeadlineExceedsMaxDeadline(); + } + + deadline = newDeadline; + + emit DeadlineChanged(newDeadline); + } +} diff --git a/l1-contracts/contracts/upgrades/IGatewayUpgrade.sol b/l1-contracts/contracts/upgrades/IGatewayUpgrade.sol index eaa74c75b..c2c972a5e 100644 --- a/l1-contracts/contracts/upgrades/IGatewayUpgrade.sol +++ b/l1-contracts/contracts/upgrades/IGatewayUpgrade.sol @@ -4,6 +4,14 @@ pragma solidity 0.8.24; import {ProposedUpgrade} from "./BaseZkSyncUpgrade.sol"; +/** + * @author Matter Labs + * @custom:security-contact security@matterlabs.dev + * @notice Gateway upgrade interface. Used for the protocol upgrade that introduces the Gateway. + */ interface IGatewayUpgrade { + /// @notice The upgrade function called from within this same contract + /// @dev This is needed for memory -> calldata conversion of the _upgrade arg. + /// @param _upgrade The upgrade to be executed. function upgradeExternal(ProposedUpgrade calldata _upgrade) external returns (bytes32); } diff --git a/l1-contracts/contracts/upgrades/IL1GenesisUpgrade.sol b/l1-contracts/contracts/upgrades/IL1GenesisUpgrade.sol index 57dd40131..c217e3be1 100644 --- a/l1-contracts/contracts/upgrades/IL1GenesisUpgrade.sol +++ b/l1-contracts/contracts/upgrades/IL1GenesisUpgrade.sol @@ -4,8 +4,18 @@ pragma solidity 0.8.24; import {L2CanonicalTransaction} from "../common/Messaging.sol"; +/** + * @author Matter Labs + * @custom:security-contact security@matterlabs.dev + * @notice L1 genesis upgrade interface. Every chain has to process an upgrade txs at its genesis. + * @notice This is needed to set system params like the chainId and to deploy some system contracts. + */ interface IL1GenesisUpgrade { /// @dev emitted when a chain registers and a GenesisUpgrade happens + /// @param _zkChain the address of the zk chain + /// @param _l2Transaction the l2 genesis upgrade transaction + /// @param _protocolVersion the current protocol version + /// @param _factoryDeps the factory dependencies needed for the upgrade event GenesisUpgrade( address indexed _zkChain, L2CanonicalTransaction _l2Transaction, @@ -13,6 +23,13 @@ interface IL1GenesisUpgrade { bytes[] _factoryDeps ); + /// @notice The main function that will be called by the Admin facet at genesis. + /// @param _l1GenesisUpgrade the address of the l1 genesis upgrade + /// @param _chainId the chain id + /// @param _protocolVersion the current protocol version + /// @param _l1CtmDeployerAddress the address of the l1 ctm deployer + /// @param _forceDeployments the force deployments + /// @param _factoryDeps the factory dependencies function genesisUpgrade( address _l1GenesisUpgrade, uint256 _chainId, diff --git a/l1-contracts/contracts/upgrades/L1GatewayHelper.sol b/l1-contracts/contracts/upgrades/L1GatewayHelper.sol new file mode 100644 index 000000000..3e418bd67 --- /dev/null +++ b/l1-contracts/contracts/upgrades/L1GatewayHelper.sol @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {IL1SharedBridgeLegacy} from "../bridge/interfaces/IL1SharedBridgeLegacy.sol"; +import {IBridgehub} from "../bridgehub/IBridgehub.sol"; +import {ETH_TOKEN_ADDRESS} from "../common/Config.sol"; +import {ZKChainSpecificForceDeploymentsData} from "../state-transition/l2-deps/IL2GenesisUpgrade.sol"; + +import {ZKChainStorage} from "../state-transition/chain-deps/ZKChainStorage.sol"; + +import {L2WrappedBaseTokenStore} from "../bridge/L2WrappedBaseTokenStore.sol"; +import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; + +/// @title L1GatewayHelper +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +library L1GatewayHelper { + /// @notice The function to retrieve the chain-specific upgrade data. + /// @param s The pointer to the storage of the chain. + /// @param _wrappedBaseTokenStore The address of the `L2WrappedBaseTokenStore` contract. + /// It is expected to be zero during creation of new chains and non-zero during upgrades. + /// @param _baseTokenAddress The L1 address of the base token of the chain. Note, that for + /// chains whose token originates from an L2, this address will be the address of its bridged + /// representation on L1. + function getZKChainSpecificForceDeploymentsData( + ZKChainStorage storage s, + address _wrappedBaseTokenStore, + address _baseTokenAddress + ) internal view returns (bytes memory) { + address sharedBridge = IBridgehub(s.bridgehub).sharedBridge(); + address legacySharedBridge = IL1SharedBridgeLegacy(sharedBridge).l2BridgeAddress(s.chainId); + + address l2WBaseToken; + if (_wrappedBaseTokenStore != address(0)) { + l2WBaseToken = L2WrappedBaseTokenStore(_wrappedBaseTokenStore).l2WBaseTokenAddress(s.chainId); + } + + // It is required for a base token to implement the following methods + string memory baseTokenName; + string memory baseTokenSymbol; + if (_baseTokenAddress == ETH_TOKEN_ADDRESS) { + baseTokenName = string("Ether"); + baseTokenSymbol = string("ETH"); + } else { + baseTokenName = IERC20Metadata(_baseTokenAddress).name(); + baseTokenSymbol = IERC20Metadata(_baseTokenAddress).symbol(); + } + + ZKChainSpecificForceDeploymentsData + memory additionalForceDeploymentsData = ZKChainSpecificForceDeploymentsData({ + baseTokenAssetId: s.baseTokenAssetId, + l2LegacySharedBridge: legacySharedBridge, + predeployedL2WethAddress: l2WBaseToken, + baseTokenL1Address: _baseTokenAddress, + baseTokenName: baseTokenName, + baseTokenSymbol: baseTokenSymbol + }); + return abi.encode(additionalForceDeploymentsData); + } +} diff --git a/l1-contracts/contracts/upgrades/L1GenesisUpgrade.sol b/l1-contracts/contracts/upgrades/L1GenesisUpgrade.sol index a6475f59a..107cecd03 100644 --- a/l1-contracts/contracts/upgrades/L1GenesisUpgrade.sol +++ b/l1-contracts/contracts/upgrades/L1GenesisUpgrade.sol @@ -15,18 +15,22 @@ import {L2_FORCE_DEPLOYER_ADDR, L2_COMPLEX_UPGRADER_ADDR, L2_GENESIS_UPGRADE_ADD import {REQUIRED_L2_GAS_PRICE_PER_PUBDATA, SYSTEM_UPGRADE_L2_TX_TYPE, PRIORITY_TX_MAX_GAS_LIMIT} from "../common/Config.sol"; import {SemVer} from "../common/libraries/SemVer.sol"; -import {IL1SharedBridgeLegacy} from "../bridge/interfaces/IL1SharedBridgeLegacy.sol"; import {IBridgehub} from "../bridgehub/IBridgehub.sol"; -import {ZKChainSpecificForceDeploymentsData} from "../state-transition/l2-deps/IL2GenesisUpgrade.sol"; - import {VerifierParams} from "../state-transition/chain-interfaces/IVerifier.sol"; import {L2ContractHelper} from "../common/libraries/L2ContractHelper.sol"; +import {L1GatewayHelper} from "./L1GatewayHelper.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev contract L1GenesisUpgrade is IL1GenesisUpgrade, BaseZkSyncUpgradeGenesis { - /// @notice The main function that will be called by the upgrade proxy. + /// @notice The main function that will be called by the Admin facet. + /// @param _l1GenesisUpgrade the address of the l1 genesis upgrade + /// @param _chainId the chain id + /// @param _protocolVersion the current protocol version + /// @param _l1CtmDeployerAddress the address of the l1 ctm deployer + /// @param _fixedForceDeploymentsData the force deployments data + /// @param _factoryDeps the factory dependencies function genesisUpgrade( address _l1GenesisUpgrade, uint256 _chainId, @@ -35,12 +39,18 @@ contract L1GenesisUpgrade is IL1GenesisUpgrade, BaseZkSyncUpgradeGenesis { bytes calldata _fixedForceDeploymentsData, bytes[] calldata _factoryDeps ) public override returns (bytes32) { + address baseTokenAddress = IBridgehub(s.bridgehub).baseToken(_chainId); + L2CanonicalTransaction memory l2ProtocolUpgradeTx; { bytes memory complexUpgraderCalldata; { - bytes memory additionalForceDeploymentsData = _getZKChainSpecificForceDeploymentsData(); + bytes memory additionalForceDeploymentsData = L1GatewayHelper.getZKChainSpecificForceDeploymentsData( + s, + address(0), + baseTokenAddress + ); bytes memory l2GenesisUpgradeCalldata = abi.encodeCall( IL2GenesisUpgrade.genesisUpgrade, (_chainId, _l1CtmDeployerAddress, _fixedForceDeploymentsData, additionalForceDeploymentsData) @@ -75,7 +85,6 @@ contract L1GenesisUpgrade is IL1GenesisUpgrade, BaseZkSyncUpgradeGenesis { } ProposedUpgrade memory proposedUpgrade = ProposedUpgrade({ l2ProtocolUpgradeTx: l2ProtocolUpgradeTx, - factoryDeps: _factoryDeps, bootloaderHash: bytes32(0), defaultAccountHash: bytes32(0), verifier: address(0), @@ -107,16 +116,4 @@ contract L1GenesisUpgrade is IL1GenesisUpgrade, BaseZkSyncUpgradeGenesis { super.upgrade(_proposedUpgrade); return Diamond.DIAMOND_INIT_SUCCESS_RETURN_VALUE; } - - function _getZKChainSpecificForceDeploymentsData() internal view returns (bytes memory) { - address sharedBridge = IBridgehub(s.bridgehub).sharedBridge(); - address legacySharedBridge = IL1SharedBridgeLegacy(sharedBridge).l2BridgeAddress(s.chainId); - ZKChainSpecificForceDeploymentsData - memory additionalForceDeploymentsData = ZKChainSpecificForceDeploymentsData({ - baseTokenAssetId: s.baseTokenAssetId, - l2LegacySharedBridge: legacySharedBridge, - l2Weth: address(0) // kl todo - }); - return abi.encode(additionalForceDeploymentsData); - } } diff --git a/l1-contracts/contracts/upgrades/ZkSyncUpgradeErrors.sol b/l1-contracts/contracts/upgrades/ZkSyncUpgradeErrors.sol index b30c882e7..816a8e753 100644 --- a/l1-contracts/contracts/upgrades/ZkSyncUpgradeErrors.sol +++ b/l1-contracts/contracts/upgrades/ZkSyncUpgradeErrors.sol @@ -2,8 +2,6 @@ pragma solidity ^0.8.21; -// 0x7a47c9a2 -error InvalidChainId(); // 0xd7f8c13e error PreviousUpgradeBatchNotCleared(); // 0x3c43ccce @@ -12,12 +10,8 @@ error ProtocolMajorVersionNotZero(); error PatchCantSetUpgradeTxn(); // 0xd2c011d6 error L2UpgradeNonceNotEqualToNewProtocolVersion(uint256 nonce, uint256 protocolVersion); -// 0xcb5e4247 -error L2BytecodeHashMismatch(bytes32 expected, bytes32 provided); // 0x88d7b498 error ProtocolVersionTooSmall(); -// 0x56d45b12 -error ProtocolVersionTooBig(); // 0x5c598b60 error PreviousProtocolMajorVersionNotZero(); // 0x72ea85ad @@ -26,8 +20,6 @@ error NewProtocolMajorVersionNotZero(); error ProtocolVersionMinorDeltaTooBig(uint256 limit, uint256 proposed); // 0xe1a9736b error ProtocolVersionDeltaTooLarge(uint256 _proposedDelta, uint256 _maxDelta); -// 0x6d172ab2 -error ProtocolVersionShouldBeGreater(uint256 _oldProtocolVersion, uint256 _newProtocolVersion); // 0x559cc34e error PatchUpgradeCantSetDefaultAccount(); // 0x962fd7d0 @@ -36,8 +28,6 @@ error PatchUpgradeCantSetBootloader(); error PreviousUpgradeNotFinalized(bytes32 txHash); // 0xa0f47245 error PreviousUpgradeNotCleaned(); -// 0x07218375 -error UnexpectedNumberOfFactoryDeps(); // 0x76da24b9 error TooManyFactoryDeps(); // 0x5cb29523 @@ -46,3 +36,6 @@ error InvalidTxType(uint256 txType); error TimeNotReached(uint256 expectedTimestamp, uint256 actualTimestamp); // 0xd92e233d error ZeroAddress(); + +// 0x388b6f68 +error GatewayUpgradeFailed(); diff --git a/l1-contracts/deploy-scripts/AcceptAdmin.s.sol b/l1-contracts/deploy-scripts/AcceptAdmin.s.sol index 690832a53..bb648262c 100644 --- a/l1-contracts/deploy-scripts/AcceptAdmin.s.sol +++ b/l1-contracts/deploy-scripts/AcceptAdmin.s.sol @@ -11,7 +11,10 @@ import {AccessControlRestriction} from "contracts/governance/AccessControlRestri import {IChainAdmin} from "contracts/governance/IChainAdmin.sol"; import {Call} from "contracts/governance/Common.sol"; import {Utils} from "./Utils.sol"; +import {IGovernance} from "contracts/governance/IGovernance.sol"; import {stdToml} from "forge-std/StdToml.sol"; +import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; +import {ValidatorTimelock} from "contracts/state-transition/ValidatorTimelock.sol"; bytes32 constant SET_TOKEN_MULTIPLIER_SETTER_ROLE = keccak256("SET_TOKEN_MULTIPLIER_SETTER_ROLE"); @@ -99,6 +102,59 @@ contract AcceptAdmin is Script { } } + function governanceExecuteCalls(bytes memory callsToExecute, address governanceAddr) public { + IGovernance governance = IGovernance(governanceAddr); + Ownable2Step ownable = Ownable2Step(governanceAddr); + + Call[] memory calls = abi.decode(callsToExecute, (Call[])); + + IGovernance.Operation memory operation = IGovernance.Operation({ + calls: calls, + predecessor: bytes32(0), + salt: bytes32(0) + }); + + vm.startBroadcast(ownable.owner()); + governance.scheduleTransparent(operation, 0); + // We assume that the total value is 0 + governance.execute{value: 0}(operation); + vm.stopBroadcast(); + } + + function adminExecuteUpgrade( + bytes memory diamondCut, + address adminAddr, + address accessControlRestriction, + address chainDiamondProxy + ) public { + uint256 oldProtocolVersion = IZKChain(chainDiamondProxy).getProtocolVersion(); + Diamond.DiamondCutData memory upgradeCutData = abi.decode(diamondCut, (Diamond.DiamondCutData)); + + Utils.adminExecute( + adminAddr, + accessControlRestriction, + chainDiamondProxy, + abi.encodeCall(IAdmin.upgradeChainFromVersion, (oldProtocolVersion, upgradeCutData)), + 0 + ); + } + + function adminScheduleUpgrade( + address adminAddr, + address accessControlRestriction, + uint256 newProtocolVersion, + uint256 timestamp + ) public { + Utils.adminExecute( + adminAddr, + accessControlRestriction, + adminAddr, + // We do instant upgrades, but obviously it should be different in prod + abi.encodeCall(ChainAdmin.setUpgradeTimestamp, (newProtocolVersion, timestamp)), + 0 + ); + } + function setDAValidatorPair( ChainAdmin chainAdmin, address target, @@ -118,4 +174,34 @@ contract AcceptAdmin is Script { chainAdmin.multicall(calls, true); vm.stopBroadcast(); } + + function makePermanentRollup(ChainAdmin chainAdmin, address target) public { + IZKChain adminContract = IZKChain(target); + + Call[] memory calls = new Call[](1); + calls[0] = Call({target: target, value: 0, data: abi.encodeCall(adminContract.makePermanentRollup, ())}); + + vm.startBroadcast(); + chainAdmin.multicall(calls, true); + vm.stopBroadcast(); + } + + function updateValidator( + address adminAddr, + address accessControlRestriction, + address validatorTimelock, + uint256 chainId, + address validatorAddress, + bool addValidator + ) public { + bytes memory data; + // The interface should be compatible with both the new and the old ValidatorTimelock + if (addValidator) { + data = abi.encodeCall(ValidatorTimelock.addValidator, (chainId, validatorAddress)); + } else { + data = abi.encodeCall(ValidatorTimelock.removeValidator, (chainId, validatorAddress)); + } + + Utils.adminExecute(adminAddr, accessControlRestriction, validatorTimelock, data, 0); + } } diff --git a/l1-contracts/deploy-scripts/DecentralizeGovernanceUpgradeScript.s.sol b/l1-contracts/deploy-scripts/DecentralizeGovernanceUpgradeScript.s.sol index 39ecc4efd..86efb1292 100644 --- a/l1-contracts/deploy-scripts/DecentralizeGovernanceUpgradeScript.s.sol +++ b/l1-contracts/deploy-scripts/DecentralizeGovernanceUpgradeScript.s.sol @@ -1,5 +1,4 @@ // SPDX-License-Identifier: MIT -// solhint-disable reason-string, gas-custom-errors pragma solidity 0.8.24; import {Script} from "forge-std/Script.sol"; @@ -10,6 +9,7 @@ import {ITransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/tra import {Governance} from "contracts/governance/Governance.sol"; import {IChainTypeManager} from "contracts/state-transition/IChainTypeManager.sol"; import {Utils} from "./Utils.sol"; +import {ProxyAdminIncorrect, ProxyAdminIncorrectOwner} from "./ZkSyncScriptErrors.sol"; contract DecentralizeGovernanceUpgradeScript is Script { function upgradeCTM( @@ -18,10 +18,12 @@ contract DecentralizeGovernanceUpgradeScript is Script { Governance _governance, address _newCtmImpl ) public { - // solhint-disable-next-line gas-custom-errors - require(_proxyAdmin.getProxyAdmin(_ctmProxy) == address(_proxyAdmin), "Proxy admin incorrect"); - // solhint-disable-next-line gas-custom-errors - require(_proxyAdmin.owner() == address(_governance), "Proxy admin owner incorrect"); + if (_proxyAdmin.getProxyAdmin(_ctmProxy) != address(_proxyAdmin)) { + revert ProxyAdminIncorrect(_proxyAdmin.getProxyAdmin(_ctmProxy), address(_proxyAdmin)); + } + if (_proxyAdmin.owner() != address(_governance)) { + revert ProxyAdminIncorrectOwner(_proxyAdmin.owner(), address(_governance)); + } bytes memory proxyAdminUpgradeData = abi.encodeCall(ProxyAdmin.upgrade, (_ctmProxy, _newCtmImpl)); diff --git a/l1-contracts/deploy-scripts/DeployL1.s.sol b/l1-contracts/deploy-scripts/DeployL1.s.sol index 8a10c0017..541a00eea 100644 --- a/l1-contracts/deploy-scripts/DeployL1.s.sol +++ b/l1-contracts/deploy-scripts/DeployL1.s.sol @@ -17,6 +17,7 @@ import {DefaultUpgrade} from "contracts/upgrades/DefaultUpgrade.sol"; import {Governance} from "contracts/governance/Governance.sol"; import {L1GenesisUpgrade} from "contracts/upgrades/L1GenesisUpgrade.sol"; import {ChainAdmin} from "contracts/governance/ChainAdmin.sol"; +import {AccessControlRestriction} from "contracts/governance/AccessControlRestriction.sol"; import {ValidatorTimelock} from "contracts/state-transition/ValidatorTimelock.sol"; import {Bridgehub} from "contracts/bridgehub/Bridgehub.sol"; import {MessageRoot} from "contracts/bridgehub/MessageRoot.sol"; @@ -43,7 +44,6 @@ import {BridgedStandardERC20} from "contracts/bridge/BridgedStandardERC20.sol"; import {AddressHasNoCode} from "./ZkSyncScriptErrors.sol"; import {ICTMDeploymentTracker} from "contracts/bridgehub/ICTMDeploymentTracker.sol"; import {IMessageRoot} from "contracts/bridgehub/IMessageRoot.sol"; -import {IL2ContractDeployer} from "contracts/common/interfaces/IL2ContractDeployer.sol"; import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; import {AddressAliasHelper} from "contracts/vendor/AddressAliasHelper.sol"; import {IL1Nullifier} from "contracts/bridge/L1Nullifier.sol"; @@ -55,12 +55,16 @@ import {IMessageRoot} from "contracts/bridgehub/IMessageRoot.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {L2ContractsBytecodesLib} from "./L2ContractsBytecodesLib.sol"; import {ValidiumL1DAValidator} from "contracts/state-transition/data-availability/ValidiumL1DAValidator.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; +import {BytecodesSupplier} from "contracts/upgrades/BytecodesSupplier.sol"; import {DeployUtils, GeneratedData, Config, DeployedAddresses, FixedForceDeploymentsData} from "./DeployUtils.s.sol"; contract DeployL1Script is Script, DeployUtils { using stdToml for string; + address expectedRollupL2DAValidator; + address internal constant ADDRESS_ONE = 0x0000000000000000000000000000000000000001; function run() public { @@ -92,6 +96,10 @@ contract DeployL1Script is Script, DeployUtils { instantiateCreate2Factory(); deployIfNeededMulticall3(); + deployBytecodesSupplier(); + + initializeExpectedL2Addresses(); + deployVerifier(); deployDefaultUpgrade(); @@ -120,7 +128,7 @@ contract DeployL1Script is Script, DeployUtils { initializeGeneratedData(); deployBlobVersionedHashRetriever(); - deployChainTypeManagerContract(); + deployChainTypeManagerContract(addresses.daAddresses.rollupDAManager); registerChainTypeManager(); setChainTypeManagerInValidatorTimelock(); @@ -143,14 +151,30 @@ contract DeployL1Script is Script, DeployUtils { config.contracts.multicall3Addr = MULTICALL3_ADDRESS; } } + + function initializeExpectedL2Addresses() internal { + expectedRollupL2DAValidator = Utils.getL2AddressViaCreate2Factory( + bytes32(0), + L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readRollupL2DAValidatorBytecode()), + hex"" + ); + } + function deployDAValidators() internal { - address contractAddress = deployViaCreate2(Utils.readRollupDAValidatorBytecode(), ""); - console.log("L1RollupDAValidator deployed at:", contractAddress); - addresses.daAddresses.l1RollupDAValidator = contractAddress; + vm.broadcast(msg.sender); + address rollupDAManager = address(new RollupDAManager()); + addresses.daAddresses.rollupDAManager = rollupDAManager; + + address rollupDAValidator = deployViaCreate2(Utils.readRollupDAValidatorBytecode(), ""); + console.log("L1RollupDAValidator deployed at:", rollupDAValidator); + addresses.daAddresses.l1RollupDAValidator = rollupDAValidator; - contractAddress = deployViaCreate2(type(ValidiumL1DAValidator).creationCode, ""); - console.log("L1ValidiumDAValidator deployed at:", contractAddress); - addresses.daAddresses.l1ValidiumDAValidator = contractAddress; + address validiumDAValidator = deployViaCreate2(type(ValidiumL1DAValidator).creationCode, ""); + console.log("L1ValidiumDAValidator deployed at:", validiumDAValidator); + addresses.daAddresses.l1ValidiumDAValidator = validiumDAValidator; + + vm.broadcast(msg.sender); + RollupDAManager(rollupDAManager).updateDAPair(address(rollupDAValidator), expectedRollupL2DAValidator, true); } function deployBridgehubContract() internal { address bridgehubImplementation = deployViaCreate2( @@ -405,7 +429,6 @@ contract DeployL1Script is Script, DeployUtils { abi.encode( config.tokens.tokenWethAddress, addresses.bridges.sharedBridgeProxy, - config.eraChainId, addresses.bridges.l1NullifierProxy ) ); @@ -438,16 +461,6 @@ contract DeployL1Script is Script, DeployUtils { vm.broadcast(msg.sender); IL1NativeTokenVault(addresses.vaults.l1NativeTokenVaultProxy).registerEthToken(); - - // bytes memory data = abi.encodeCall(sharedBridge.setNativeTokenVault, (IL1NativeTokenVault(addresses.vaults.l1NativeTokenVaultProxy))); - // Utils.executeUpgrade({ - // _governor: ownable.owner(), - // _salt: bytes32(0), - // _target: addresses.bridges.sharedBridgeProxy, - // _data: data, - // _value: 0, - // _delay: 0 - // }); } function updateOwners() internal { @@ -470,15 +483,17 @@ contract DeployL1Script is Script, DeployUtils { CTMDeploymentTracker ctmDeploymentTracker = CTMDeploymentTracker(addresses.bridgehub.ctmDeploymentTrackerProxy); ctmDeploymentTracker.transferOwnership(addresses.governance); + RollupDAManager(addresses.daAddresses.rollupDAManager).transferOwnership(addresses.governance); + vm.stopBroadcast(); console.log("Owners updated"); } function saveDiamondSelectors() public { - AdminFacet adminFacet = new AdminFacet(1); + AdminFacet adminFacet = new AdminFacet(1, RollupDAManager(address(0))); GettersFacet gettersFacet = new GettersFacet(); MailboxFacet mailboxFacet = new MailboxFacet(1, 1); - ExecutorFacet executorFacet = new ExecutorFacet(); + ExecutorFacet executorFacet = new ExecutorFacet(1); bytes4[] memory adminFacetSelectors = Utils.getAllSelectors(address(adminFacet).code); bytes4[] memory gettersFacetSelectors = Utils.getAllSelectors(address(gettersFacet).code); bytes4[] memory mailboxFacetSelectors = Utils.getAllSelectors(address(mailboxFacet).code); @@ -543,6 +558,7 @@ contract DeployL1Script is Script, DeployUtils { vm.serializeAddress("state_transition", "diamond_init_addr", addresses.stateTransition.diamondInit); vm.serializeAddress("state_transition", "genesis_upgrade_addr", addresses.stateTransition.genesisUpgrade); vm.serializeAddress("state_transition", "default_upgrade_addr", addresses.stateTransition.defaultUpgrade); + vm.serializeAddress("state_transition", "bytecodes_supplier_addr", addresses.stateTransition.bytecodesSupplier); string memory stateTransition = vm.serializeAddress( "state_transition", "diamond_proxy_addr", @@ -637,6 +653,7 @@ contract DeployL1Script is Script, DeployUtils { vm.serializeString("deployed_addresses", "bridges", bridges); vm.serializeString("deployed_addresses", "state_transition", stateTransition); + vm.serializeAddress("deployed_addresses", "l1_rollup_da_manager", addresses.daAddresses.rollupDAManager); vm.serializeAddress( "deployed_addresses", "rollup_l1_da_validator_addr", @@ -662,6 +679,7 @@ contract DeployL1Script is Script, DeployUtils { vm.serializeAddress("root", "deployer_addr", config.deployerAddress); vm.serializeString("root", "deployed_addresses", deployedAddresses); vm.serializeString("root", "contracts_config", contractsConfig); + vm.serializeAddress("root", "expected_rollup_l2_da_validator_addr", expectedRollupL2DAValidator); string memory toml = vm.serializeAddress("root", "owner_address", config.ownerAddress); vm.writeToml(toml, outputPath); @@ -687,11 +705,10 @@ contract DeployL1Script is Script, DeployUtils { L2ContractsBytecodesLib.readL2NativeTokenVaultBytecode() ), messageRootBytecodeHash: L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readMessageRootBytecode()), - // For newly created chains it it is expected that the following bridges are not present + // For newly created chains it it is expected that the following bridges are not present at the moment + // of creation of the chain l2SharedBridgeLegacyImpl: address(0), - l2BridgedStandardERC20Impl: address(0), - l2BridgeProxyOwnerAddress: address(0), - l2BridgedStandardERC20ProxyOwnerAddress: address(0) + l2BridgedStandardERC20Impl: address(0) }); return abi.encode(data); diff --git a/l1-contracts/deploy-scripts/DeployL2Contracts.sol b/l1-contracts/deploy-scripts/DeployL2Contracts.sol index 31415e186..6e320639a 100644 --- a/l1-contracts/deploy-scripts/DeployL2Contracts.sol +++ b/l1-contracts/deploy-scripts/DeployL2Contracts.sol @@ -133,7 +133,7 @@ contract DeployL2Script is Script { bytecode = L2ContractsBytecodesLib.readRollupL2DAValidatorBytecode(); } - deployed.l2DaValidatorAddress = Utils.deployThroughL1({ + deployed.l2DaValidatorAddress = Utils.deployThroughL1Deterministic({ bytecode: bytecode, constructorargs: bytes(""), create2salt: "", diff --git a/l1-contracts/deploy-scripts/DeployUtils.s.sol b/l1-contracts/deploy-scripts/DeployUtils.s.sol index 33f386cf9..3f4717414 100644 --- a/l1-contracts/deploy-scripts/DeployUtils.s.sol +++ b/l1-contracts/deploy-scripts/DeployUtils.s.sol @@ -54,6 +54,7 @@ import {ICTMDeploymentTracker} from "contracts/bridgehub/ICTMDeploymentTracker.s import {IMessageRoot} from "contracts/bridgehub/IMessageRoot.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {L2ContractsBytecodesLib} from "./L2ContractsBytecodesLib.sol"; +import {BytecodesSupplier} from "contracts/upgrades/BytecodesSupplier.sol"; struct FixedForceDeploymentsData { uint256 l1ChainId; @@ -68,8 +69,6 @@ struct FixedForceDeploymentsData { bytes32 messageRootBytecodeHash; address l2SharedBridgeLegacyImpl; address l2BridgedStandardERC20Impl; - address l2BridgeProxyOwnerAddress; - address l2BridgedStandardERC20ProxyOwnerAddress; } // solhint-disable-next-line gas-struct-packing @@ -95,6 +94,7 @@ struct L1NativeTokenVaultAddresses { } struct DataAvailabilityDeployedAddresses { + address rollupDAManager; address l1RollupDAValidator; address l1ValidiumDAValidator; } @@ -266,6 +266,12 @@ contract DeployUtils is Script { ); } + function deployBytecodesSupplier() internal { + address contractAddress = deployViaCreate2(type(BytecodesSupplier).creationCode, ""); + console.log("BytecodesSupplier deployed at:", contractAddress); + addresses.stateTransition.bytecodesSupplier = contractAddress; + } + function deployVerifier() internal { bytes memory code; if (config.testnetVerifier) { @@ -338,18 +344,21 @@ contract DeployUtils is Script { addresses.transparentProxyAdmin = address(proxyAdmin); } - function deployChainTypeManagerContract() internal { - deployStateTransitionDiamondFacets(); + function deployChainTypeManagerContract(address _rollupDAManager) internal { + deployStateTransitionDiamondFacets(_rollupDAManager); deployChainTypeManagerImplementation(); deployChainTypeManagerProxy(); } - function deployStateTransitionDiamondFacets() internal { - address executorFacet = deployViaCreate2(type(ExecutorFacet).creationCode, abi.encode()); + function deployStateTransitionDiamondFacets(address _rollupDAManager) internal { + address executorFacet = deployViaCreate2(type(ExecutorFacet).creationCode, abi.encode(config.l1ChainId)); console.log("ExecutorFacet deployed at:", executorFacet); addresses.stateTransition.executorFacet = executorFacet; - address adminFacet = deployViaCreate2(type(AdminFacet).creationCode, abi.encode(config.l1ChainId)); + address adminFacet = deployViaCreate2( + type(AdminFacet).creationCode, + abi.encode(config.l1ChainId, _rollupDAManager) + ); console.log("AdminFacet deployed at:", adminFacet); addresses.stateTransition.adminFacet = adminFacet; diff --git a/l1-contracts/deploy-scripts/DeployZKAndBridgeToL1.s.sol b/l1-contracts/deploy-scripts/DeployZKAndBridgeToL1.s.sol new file mode 100644 index 000000000..5e0a87681 --- /dev/null +++ b/l1-contracts/deploy-scripts/DeployZKAndBridgeToL1.s.sol @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +// solhint-disable no-console + +import {Vm} from "forge-std/Vm.sol"; +import {Script, console2 as console} from "forge-std/Script.sol"; +import {stdToml} from "forge-std/StdToml.sol"; + +// It's required to disable lints to force the compiler to compile the contracts +// solhint-disable no-unused-import +import {TestnetERC20Token} from "contracts/dev-contracts/TestnetERC20Token.sol"; +// solhint-disable no-unused-import +import {WETH9} from "contracts/dev-contracts/WETH9.sol"; + +import {L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR} from "contracts/common/L2ContractAddresses.sol"; + +import {FinalizeL1DepositParams} from "contracts/bridge/interfaces/IL1Nullifier.sol"; +import {L1AssetRouter} from "contracts/bridge/asset-router/L1AssetRouter.sol"; +import {L2AssetRouter} from "contracts/bridge/asset-router/L2AssetRouter.sol"; +import {L1Nullifier} from "contracts/bridge/L1Nullifier.sol"; +import {L2NativeTokenVault} from "contracts/bridge/ntv/L2NativeTokenVault.sol"; +import {IL1NativeTokenVault} from "contracts/bridge/ntv/IL1NativeTokenVault.sol"; +import {Utils} from "./Utils.sol"; +import {MintFailed} from "./ZkSyncScriptErrors.sol"; + +contract DeployZKScript is Script { + using stdToml for string; + + struct Config { + TokenDescription zkToken; + address deployerAddress; + address[] additionalAddressesForMinting; + address create2FactoryAddr; + bytes32 create2FactorySalt; + uint256 chainId; + address l1SharedBridge; + address bridgehub; + address l1Nullifier; + address chainAdmin; + address governance; + address deployer; + address owner; + address anotherOwner; + address chainGovernor; + } + + struct TokenDescription { + address addr; + string name; + string symbol; + uint256 decimals; + string implementation; + uint256 mint; + bytes32 assetId; + } + + Config internal config; + + function run() public { + initializeConfig(); + deployZkToken(); + saveOutput(); + } + + function getTokenAddress() public view returns (address) { + return config.zkToken.addr; + } + + function initializeConfig() internal { + config.deployerAddress = msg.sender; + + string memory root = vm.projectRoot(); + + // Grab config from output of l1 deployment + string memory path = string.concat(root, vm.envString("TOKENS_CONFIG")); + string memory toml = vm.readFile(path); + + config.additionalAddressesForMinting = vm.parseTomlAddressArray(toml, "$.additional_addresses_for_minting"); + + // Parse the ZK token configuration + string memory key = "$.tokens.ZK"; + config.zkToken.name = toml.readString(string.concat(key, ".name")); + config.zkToken.symbol = toml.readString(string.concat(key, ".symbol")); + config.zkToken.decimals = toml.readUint(string.concat(key, ".decimals")); + config.zkToken.implementation = toml.readString(string.concat(key, ".implementation")); + config.zkToken.mint = toml.readUint(string.concat(key, ".mint")); + + // Grab config from custom config file + path = string.concat(root, vm.envString("ZK_CHAIN_CONFIG")); + toml = vm.readFile(path); + + config.bridgehub = toml.readAddress("$.deployed_addresses.bridgehub.bridgehub_proxy_addr"); + config.l1SharedBridge = toml.readAddress("$.deployed_addresses.bridges.shared_bridge_proxy_addr"); + config.l1Nullifier = toml.readAddress("$.deployed_addresses.bridges.l1_nullifier_proxy_addr"); + config.chainId = toml.readUint("$.chain.chain_chain_id"); + config.chainGovernor = toml.readAddress("$.owner_address"); + } + + function initializeAdditionalConfig() internal { + string memory root = vm.projectRoot(); + string memory path = string.concat(root, vm.envString("L1_OUTPUT")); + string memory toml = vm.readFile(path); + + config.owner = toml.readAddress("$.owner_address"); + } + + function deployZkToken() internal { + uint256 someBigAmount = 100000000000000000000000000000000; + TokenDescription storage token = config.zkToken; + console.log("Deploying token:", token.name); + + vm.startBroadcast(); + address zkTokenAddress = deployErc20({ + name: token.name, + symbol: token.symbol, + decimals: token.decimals, + mint: token.mint, + additionalAddressesForMinting: config.additionalAddressesForMinting + }); + console.log("Token deployed at:", zkTokenAddress); + token.addr = zkTokenAddress; + address deployer = msg.sender; + TestnetERC20Token zkToken = TestnetERC20Token(zkTokenAddress); + zkToken.mint(deployer, someBigAmount); + uint256 deployerBalance = zkToken.balanceOf(deployer); + console.log("Deployer balance:", deployerBalance); + L2AssetRouter l2AR = L2AssetRouter(L2_ASSET_ROUTER_ADDR); + L2NativeTokenVault l2NTV = L2NativeTokenVault(L2_NATIVE_TOKEN_VAULT_ADDR); + l2NTV.registerToken(zkTokenAddress); + bytes32 zkTokenAssetId = l2NTV.assetId(zkTokenAddress); + config.zkToken.assetId = zkTokenAssetId; + console.log("zkTokenAssetId:", uint256(zkTokenAssetId)); + zkToken.approve(L2_NATIVE_TOKEN_VAULT_ADDR, someBigAmount); + vm.stopBroadcast(); + + vm.broadcast(); + l2AR.withdraw(zkTokenAssetId, abi.encode(someBigAmount, deployer)); + uint256 deployerBalanceAfterWithdraw = zkToken.balanceOf(deployer); + console.log("Deployed balance after withdraw:", deployerBalanceAfterWithdraw); + } + + /// TODO(EVM-748): make that function support non-ETH based chains + function supplyEraWallet(address addr, uint256 amount) public { + initializeConfig(); + + Utils.runL1L2Transaction( + hex"", + Utils.MAX_PRIORITY_TX_GAS, + amount, + new bytes[](0), + addr, + config.chainId, + config.bridgehub, + config.l1SharedBridge + ); + } + + function finalizeZkTokenWithdrawal( + uint256 _chainId, + uint256 _l2BatchNumber, + uint256 _l2MessageIndex, + uint16 _l2TxNumberInBatch, + bytes memory _message, + bytes32[] memory _merkleProof + ) public { + initializeConfig(); + + L1Nullifier l1Nullifier = L1Nullifier(config.l1Nullifier); + + vm.broadcast(); + l1Nullifier.finalizeDeposit( + FinalizeL1DepositParams({ + chainId: _chainId, + l2BatchNumber: _l2BatchNumber, + l2MessageIndex: _l2MessageIndex, + l2Sender: L2_ASSET_ROUTER_ADDR, + l2TxNumberInBatch: _l2TxNumberInBatch, + message: _message, + merkleProof: _merkleProof + }) + ); + } + + function saveL1Address() public { + initializeConfig(); + initializeAdditionalConfig(); + + string memory root = vm.projectRoot(); + string memory path = string.concat(root, vm.envString("ZK_TOKEN_OUTPUT")); + + string memory toml = vm.readFile(path); + + bytes32 zkTokenAssetId = toml.readBytes32("$.ZK.assetId"); + + L1AssetRouter l1AR = L1AssetRouter(config.l1SharedBridge); + console.log("L1 AR address", address(l1AR)); + IL1NativeTokenVault nativeTokenVault = IL1NativeTokenVault(address(l1AR.nativeTokenVault())); + address l1ZKAddress = nativeTokenVault.tokenAddress(zkTokenAssetId); + console.log("L1 ZK address", l1ZKAddress); + TestnetERC20Token l1ZK = TestnetERC20Token(l1ZKAddress); + + uint256 balance = l1ZK.balanceOf(config.deployerAddress); + vm.broadcast(); + l1ZK.transfer(config.owner, balance / 2); + string memory tokenInfo = vm.serializeAddress("ZK", "l1Address", l1ZKAddress); + vm.writeToml(tokenInfo, path, ".ZK.l1Address"); + } + + function fundChainGovernor() public { + initializeConfig(); + + string memory root = vm.projectRoot(); + string memory path = string.concat(root, vm.envString("ZK_TOKEN_OUTPUT")); + string memory toml = vm.readFile(path); + + address l1ZKAddress = toml.readAddress("$.ZK.l1Address.l1Address"); + console.log("L1 ZK address: ", l1ZKAddress); + console.log("Address of governor: ", config.chainGovernor); + TestnetERC20Token l1ZK = TestnetERC20Token(l1ZKAddress); + uint256 balance = l1ZK.balanceOf(config.deployerAddress); + vm.broadcast(); + l1ZK.transfer(config.chainGovernor, balance / 10); + } + + function deployErc20( + string memory name, + string memory symbol, + uint256 decimals, + uint256 mint, + address[] storage additionalAddressesForMinting + ) internal returns (address) { + address tokenAddress = address(new TestnetERC20Token(name, symbol, uint8(decimals))); // No salt for testing + + if (mint > 0) { + additionalAddressesForMinting.push(config.deployerAddress); + uint256 addressMintListLength = additionalAddressesForMinting.length; + for (uint256 i = 0; i < addressMintListLength; ++i) { + (bool success, ) = tokenAddress.call( + abi.encodeWithSignature("mint(address,uint256)", additionalAddressesForMinting[i], mint) + ); + if (!success) { + revert MintFailed(); + } + console.log("Minting to:", additionalAddressesForMinting[i]); + if (!success) { + revert MintFailed(); + } + } + } + + return tokenAddress; + } + + function saveOutput() internal { + TokenDescription memory token = config.zkToken; + string memory section = token.symbol; + + // Serialize each attribute directly under the token's symbol (e.g., [ZK]) + vm.serializeString(section, "name", token.name); + vm.serializeString(section, "symbol", token.symbol); + vm.serializeUint(section, "decimals", token.decimals); + vm.serializeString(section, "implementation", token.implementation); + vm.serializeUintToHex(section, "mint", token.mint); + vm.serializeBytes32(section, "assetId", token.assetId); + vm.serializeAddress(token.symbol, "l1Address", address(0)); + + string memory tokenInfo = vm.serializeAddress(token.symbol, "address", token.addr); + string memory toml = vm.serializeString("root", "ZK", tokenInfo); + string memory root = vm.projectRoot(); + string memory path = string.concat(root, vm.envString("ZK_TOKEN_OUTPUT")); + vm.writeToml(toml, path); + } + + // add this to be excluded from coverage report + function test() internal {} +} diff --git a/l1-contracts/deploy-scripts/GatewayCTMDeployerHelper.sol b/l1-contracts/deploy-scripts/GatewayCTMDeployerHelper.sol new file mode 100644 index 000000000..5bb7f7585 --- /dev/null +++ b/l1-contracts/deploy-scripts/GatewayCTMDeployerHelper.sol @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; + +import {ChainTypeManager} from "contracts/state-transition/ChainTypeManager.sol"; + +import {L2_BRIDGEHUB_ADDR} from "contracts/common/L2ContractAddresses.sol"; + +import {VerifierParams, IVerifier} from "contracts/state-transition/chain-interfaces/IVerifier.sol"; +import {ProxyAdmin} from "@openzeppelin/contracts-v4/proxy/transparent/ProxyAdmin.sol"; +import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; +import {InitializeDataNewChain as DiamondInitializeDataNewChain} from "contracts/state-transition/chain-interfaces/IDiamondInit.sol"; +import {ChainTypeManagerInitializeData, ChainCreationParams, IChainTypeManager} from "contracts/state-transition/IChainTypeManager.sol"; + +import {Utils} from "./Utils.sol"; + +import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; + +import {GatewayCTMDeployerConfig, DeployedContracts, BLOB_HASH_RETRIEVER_ADDR} from "contracts/state-transition/chain-deps/GatewayCTMDeployer.sol"; + +// solhint-disable gas-custom-errors + +struct InnerDeployConfig { + address deployerAddr; + bytes32 salt; +} + +library GatewayCTMDeployerHelper { + function calculateAddresses( + bytes32 _create2Salt, + GatewayCTMDeployerConfig memory config + ) internal returns (DeployedContracts memory contracts, bytes memory create2Calldata, address ctmDeployerAddress) { + (bytes32 bytecodeHash, bytes memory deployData) = Utils.getDeploymentCalldata( + _create2Salt, + Utils.readZKFoundryBytecode("GatewayCTMDeployer.sol", "GatewayCTMDeployer"), + abi.encode(config) + ); + + // Create2Factory has the same interface as the usual deployer. + create2Calldata = deployData; + + ctmDeployerAddress = Utils.getL2AddressViaCreate2Factory(_create2Salt, bytecodeHash, abi.encode(config)); + + InnerDeployConfig memory innerConfig = InnerDeployConfig({deployerAddr: ctmDeployerAddress, salt: config.salt}); + + // Caching some values + bytes32 salt = config.salt; + uint256 eraChainId = config.eraChainId; + uint256 l1ChainId = config.l1ChainId; + + contracts.multicall3 = _deployInternal("Multicall3", "Multicall3.sol", hex"", innerConfig); + + contracts = _deployFacetsAndUpgrades( + salt, + eraChainId, + l1ChainId, + config.rollupL2DAValidatorAddress, + config.aliasedGovernanceAddress, + contracts, + innerConfig + ); + contracts = _deployVerifier(config.testnetVerifier, contracts, innerConfig); + + contracts.stateTransition.validatorTimelock = _deployInternal( + "ValidatorTimelock", + "ValidatorTimelock.sol", + abi.encode(ctmDeployerAddress, 0), + innerConfig + ); + + contracts = _deployCTM(salt, config, contracts, innerConfig); + } + + function _deployFacetsAndUpgrades( + bytes32 _salt, + uint256 _eraChainId, + uint256 _l1ChainId, + address _rollupL2DAValidatorAddress, + address _governanceAddress, + DeployedContracts memory _deployedContracts, + InnerDeployConfig memory innerConfig + ) internal returns (DeployedContracts memory) { + _deployedContracts.stateTransition.mailboxFacet = _deployInternal( + "MailboxFacet", + "Mailbox.sol", + abi.encode(_eraChainId, _l1ChainId), + innerConfig + ); + + _deployedContracts.stateTransition.executorFacet = _deployInternal( + "ExecutorFacet", + "Executor.sol", + abi.encode(_l1ChainId), + innerConfig + ); + + _deployedContracts.stateTransition.gettersFacet = _deployInternal( + "GettersFacet", + "Getters.sol", + hex"", + innerConfig + ); + + address rollupDAManager; + (_deployedContracts, rollupDAManager) = _deployRollupDAManager( + _salt, + _rollupL2DAValidatorAddress, + _governanceAddress, + _deployedContracts, + innerConfig + ); + _deployedContracts.stateTransition.adminFacet = _deployInternal( + "AdminFacet", + "Admin.sol", + abi.encode(_l1ChainId, rollupDAManager), + innerConfig + ); + + _deployedContracts.stateTransition.diamondInit = _deployInternal( + "DiamondInit", + "DiamondInit.sol", + hex"", + innerConfig + ); + _deployedContracts.stateTransition.genesisUpgrade = _deployInternal( + "L1GenesisUpgrade", + "L1GenesisUpgrade.sol", + hex"", + innerConfig + ); + + return _deployedContracts; + } + + function _deployVerifier( + bool _testnetVerifier, + DeployedContracts memory _deployedContracts, + InnerDeployConfig memory innerConfig + ) internal returns (DeployedContracts memory) { + if (_testnetVerifier) { + _deployedContracts.stateTransition.verifier = _deployInternal( + "TestnetVerifier", + "TestnetVerifier.sol", + hex"", + innerConfig + ); + } else { + _deployedContracts.stateTransition.verifier = _deployInternal( + "Verifier", + "Verifier.sol", + hex"", + innerConfig + ); + } + return _deployedContracts; + } + + function _deployRollupDAManager( + bytes32 _salt, + address _rollupL2DAValidatorAddress, + address _governanceAddress, + DeployedContracts memory _deployedContracts, + InnerDeployConfig memory innerConfig + ) internal returns (DeployedContracts memory, address) { + address daManager = _deployInternal("RollupDAManager", "RollupDAManager.sol", hex"", innerConfig); + + address validiumDAValidator = _deployInternal( + "ValidiumL1DAValidator", + "ValidiumL1DAValidator.sol", + hex"", + innerConfig + ); + + address relayedSLDAValidator = _deployInternal( + "RelayedSLDAValidator", + "RelayedSLDAValidator.sol", + hex"", + innerConfig + ); + + _deployedContracts.daContracts.rollupDAManager = daManager; + _deployedContracts.daContracts.relayedSLDAValidator = relayedSLDAValidator; + _deployedContracts.daContracts.validiumDAValidator = validiumDAValidator; + + return (_deployedContracts, daManager); + } + + function _deployCTM( + bytes32 _salt, + GatewayCTMDeployerConfig memory _config, + DeployedContracts memory _deployedContracts, + InnerDeployConfig memory innerConfig + ) internal returns (DeployedContracts memory) { + _deployedContracts.stateTransition.chainTypeManagerImplementation = _deployInternal( + "ChainTypeManager", + "ChainTypeManager.sol", + abi.encode(L2_BRIDGEHUB_ADDR), + innerConfig + ); + + address proxyAdmin = _deployInternal("ProxyAdmin", "ProxyAdmin.sol", hex"", innerConfig); + _deployedContracts.stateTransition.chainTypeManagerProxyAdmin = proxyAdmin; + + Diamond.FacetCut[] memory facetCuts = new Diamond.FacetCut[](4); + facetCuts[0] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.adminFacet, + action: Diamond.Action.Add, + isFreezable: false, + selectors: _config.adminSelectors + }); + facetCuts[1] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.gettersFacet, + action: Diamond.Action.Add, + isFreezable: false, + selectors: _config.gettersSelectors + }); + facetCuts[2] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.mailboxFacet, + action: Diamond.Action.Add, + isFreezable: true, + selectors: _config.mailboxSelectors + }); + facetCuts[3] = Diamond.FacetCut({ + facet: _deployedContracts.stateTransition.executorFacet, + action: Diamond.Action.Add, + isFreezable: true, + selectors: _config.executorSelectors + }); + + DiamondInitializeDataNewChain memory initializeData = DiamondInitializeDataNewChain({ + verifier: IVerifier(_deployedContracts.stateTransition.verifier), + verifierParams: _config.verifierParams, + l2BootloaderBytecodeHash: _config.bootloaderHash, + l2DefaultAccountBytecodeHash: _config.defaultAccountHash, + priorityTxMaxGasLimit: _config.priorityTxMaxGasLimit, + feeParams: _config.feeParams, + blobVersionedHashRetriever: BLOB_HASH_RETRIEVER_ADDR + }); + + Diamond.DiamondCutData memory diamondCut = Diamond.DiamondCutData({ + facetCuts: facetCuts, + initAddress: _deployedContracts.stateTransition.diamondInit, + initCalldata: abi.encode(initializeData) + }); + + _deployedContracts.diamondCutData = abi.encode(diamondCut); + + ChainCreationParams memory chainCreationParams = ChainCreationParams({ + genesisUpgrade: _deployedContracts.stateTransition.genesisUpgrade, + genesisBatchHash: _config.genesisRoot, + genesisIndexRepeatedStorageChanges: uint64(_config.genesisRollupLeafIndex), + genesisBatchCommitment: _config.genesisBatchCommitment, + diamondCut: diamondCut, + forceDeploymentsData: _config.forceDeploymentsData + }); + + ChainTypeManagerInitializeData memory diamondInitData = ChainTypeManagerInitializeData({ + owner: _config.aliasedGovernanceAddress, + validatorTimelock: _deployedContracts.stateTransition.validatorTimelock, + chainCreationParams: chainCreationParams, + protocolVersion: _config.protocolVersion + }); + + _deployedContracts.stateTransition.chainTypeManagerProxy = _deployInternal( + "TransparentUpgradeableProxy", + "TransparentUpgradeableProxy.sol", + abi.encode( + _deployedContracts.stateTransition.chainTypeManagerImplementation, + proxyAdmin, + abi.encodeCall(ChainTypeManager.initialize, (diamondInitData)) + ), + innerConfig + ); + + return _deployedContracts; + } + + function _deployInternal( + string memory contractName, + string memory fileName, + bytes memory params, + InnerDeployConfig memory config + ) private returns (address) { + bytes memory bytecode = Utils.readZKFoundryBytecode(fileName, contractName); + + return + L2ContractHelper.computeCreate2Address( + config.deployerAddr, + config.salt, + L2ContractHelper.hashL2Bytecode(bytecode), + keccak256(params) + ); + } + + /// @notice List of factory dependencies needed for the correct execution of + /// CTMDeployer and healthy functionaling of the system overall + function getListOfFactoryDeps() external returns (bytes[] memory dependencies) { + uint256 totalDependencies = 18; + dependencies = new bytes[](totalDependencies); + uint256 index = 0; + + dependencies[index++] = Utils.readZKFoundryBytecode("GatewayCTMDeployer.sol", "GatewayCTMDeployer"); + dependencies[index++] = Utils.readZKFoundryBytecode("Multicall3.sol", "Multicall3"); + dependencies[index++] = Utils.readZKFoundryBytecode("Mailbox.sol", "MailboxFacet"); + dependencies[index++] = Utils.readZKFoundryBytecode("Executor.sol", "ExecutorFacet"); + dependencies[index++] = Utils.readZKFoundryBytecode("Getters.sol", "GettersFacet"); + dependencies[index++] = Utils.readZKFoundryBytecode("RollupDAManager.sol", "RollupDAManager"); + dependencies[index++] = Utils.readZKFoundryBytecode("ValidiumL1DAValidator.sol", "ValidiumL1DAValidator"); + dependencies[index++] = Utils.readZKFoundryBytecode("RelayedSLDAValidator.sol", "RelayedSLDAValidator"); + dependencies[index++] = Utils.readZKFoundryBytecode("Admin.sol", "AdminFacet"); + dependencies[index++] = Utils.readZKFoundryBytecode("DiamondInit.sol", "DiamondInit"); + dependencies[index++] = Utils.readZKFoundryBytecode("L1GenesisUpgrade.sol", "L1GenesisUpgrade"); + // Include both verifiers since we cannot determine which one will be used + dependencies[index++] = Utils.readZKFoundryBytecode("TestnetVerifier.sol", "TestnetVerifier"); + dependencies[index++] = Utils.readZKFoundryBytecode("Verifier.sol", "Verifier"); + dependencies[index++] = Utils.readZKFoundryBytecode("ValidatorTimelock.sol", "ValidatorTimelock"); + dependencies[index++] = Utils.readZKFoundryBytecode("ChainTypeManager.sol", "ChainTypeManager"); + dependencies[index++] = Utils.readZKFoundryBytecode("ProxyAdmin.sol", "ProxyAdmin"); + dependencies[index++] = Utils.readZKFoundryBytecode( + "TransparentUpgradeableProxy.sol", + "TransparentUpgradeableProxy" + ); + // Not used in scripts, but definitely needed for CTM to work + dependencies[index++] = Utils.readZKFoundryBytecode("DiamondProxy.sol", "DiamondProxy"); + + return dependencies; + } +} diff --git a/l1-contracts/deploy-scripts/GatewayCTMFromL1.s.sol b/l1-contracts/deploy-scripts/GatewayCTMFromL1.s.sol index 6f17c234c..aaf51357a 100644 --- a/l1-contracts/deploy-scripts/GatewayCTMFromL1.s.sol +++ b/l1-contracts/deploy-scripts/GatewayCTMFromL1.s.sol @@ -7,15 +7,21 @@ import {Script, console2 as console} from "forge-std/Script.sol"; // import {Vm} from "forge-std/Vm.sol"; import {stdToml} from "forge-std/StdToml.sol"; +// It's required to disable lints to force the compiler to compile the contracts +// solhint-disable no-unused-import +import {TestnetERC20Token} from "contracts/dev-contracts/TestnetERC20Token.sol"; + import {Ownable} from "@openzeppelin/contracts-v4/access/Ownable.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; import {REQUIRED_L2_GAS_PRICE_PER_PUBDATA} from "contracts/common/Config.sol"; import {L2TransactionRequestTwoBridgesOuter} from "contracts/bridgehub/IBridgehub.sol"; import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; -import {StateTransitionDeployedAddresses, Utils, L2_BRIDGEHUB_ADDRESS} from "./Utils.sol"; +import {StateTransitionDeployedAddresses, Utils, L2_BRIDGEHUB_ADDRESS, L2_CREATE2_FACTORY_ADDRESS} from "./Utils.sol"; import {AddressAliasHelper} from "contracts/vendor/AddressAliasHelper.sol"; import {L2ContractsBytecodesLib} from "./L2ContractsBytecodesLib.sol"; +import {L1AssetRouter} from "contracts/bridge/asset-router/L1AssetRouter.sol"; +import {IL1NativeTokenVault} from "contracts/bridge/ntv/IL1NativeTokenVault.sol"; import {AdminFacet} from "contracts/state-transition/chain-deps/facets/Admin.sol"; import {ExecutorFacet} from "contracts/state-transition/chain-deps/facets/Executor.sol"; @@ -38,6 +44,9 @@ import {FeeParams, PubdataPricingMode} from "contracts/state-transition/chain-de import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; import {ChainTypeManagerInitializeData, ChainCreationParams, IChainTypeManager} from "contracts/state-transition/IChainTypeManager.sol"; +import {DeployedContracts, GatewayCTMDeployerConfig} from "contracts/state-transition/chain-deps/GatewayCTMDeployer.sol"; +import {GatewayCTMDeployerHelper} from "./GatewayCTMDeployerHelper.sol"; + /// @notice Scripts that is responsible for preparing the chain to become a gateway contract GatewayCTMFromL1 is Script { using stdToml for string; @@ -55,6 +64,9 @@ contract GatewayCTMFromL1 is Script { address chainTypeManagerProxy; address sharedBridgeProxy; address governance; + address governanceAddr; + address deployerAddr; + address baseToken; uint256 chainChainId; uint256 eraChainId; uint256 l1ChainId; @@ -75,6 +87,7 @@ contract GatewayCTMFromL1 is Script { uint256 genesisRollupLeafIndex; bytes32 genesisBatchCommitment; uint256 latestProtocolVersion; + address expectedRollupL2DAValidator; bytes forceDeploymentsData; } @@ -87,17 +100,86 @@ contract GatewayCTMFromL1 is Script { } Config internal config; + GatewayCTMDeployerConfig internal gatewayCTMDeployerConfig; Output internal output; - function run() public { - console.log("Setting up the Gateway script"); - + function prepareAddresses() external { initializeConfig(); + if (config.baseToken != ADDRESS_ONE) { + distributeBaseToken(); + } deployGatewayContracts(); + (DeployedContracts memory expectedGatewayContracts, bytes memory create2Calldata, ) = GatewayCTMDeployerHelper + .calculateAddresses(bytes32(0), gatewayCTMDeployerConfig); + + _saveExpectedGatewayContractsToOutput(expectedGatewayContracts); + saveOutput(); + } + + function deployCTM() external { + initializeConfig(); + + (DeployedContracts memory expectedGatewayContracts, bytes memory create2Calldata, ) = GatewayCTMDeployerHelper + .calculateAddresses(bytes32(0), gatewayCTMDeployerConfig); + + bytes[] memory deps = GatewayCTMDeployerHelper.getListOfFactoryDeps(); + + for (uint i = 0; i < deps.length; i++) { + bytes[] memory localDeps = new bytes[](1); + localDeps[0] = deps[i]; + Utils.runL1L2Transaction({ + l2Calldata: hex"", + l2GasLimit: 72_000_000, + l2Value: 0, + factoryDeps: localDeps, + dstAddress: address(0), + chainId: config.chainChainId, + bridgehubAddress: config.bridgehub, + l1SharedBridgeProxy: config.sharedBridgeProxy + }); + } + + Utils.runL1L2Transaction({ + l2Calldata: create2Calldata, + l2GasLimit: 72_000_000, + l2Value: 0, + factoryDeps: new bytes[](0), + dstAddress: L2_CREATE2_FACTORY_ADDRESS, + chainId: config.chainChainId, + bridgehubAddress: config.bridgehub, + l1SharedBridgeProxy: config.sharedBridgeProxy + }); + + _saveExpectedGatewayContractsToOutput(expectedGatewayContracts); saveOutput(); } + function _saveExpectedGatewayContractsToOutput(DeployedContracts memory expectedGatewayContracts) internal { + output = Output({ + gatewayStateTransition: StateTransitionDeployedAddresses({ + chainTypeManagerProxy: expectedGatewayContracts.stateTransition.chainTypeManagerProxy, + chainTypeManagerImplementation: expectedGatewayContracts.stateTransition.chainTypeManagerImplementation, + verifier: expectedGatewayContracts.stateTransition.verifier, + adminFacet: expectedGatewayContracts.stateTransition.adminFacet, + mailboxFacet: expectedGatewayContracts.stateTransition.mailboxFacet, + executorFacet: expectedGatewayContracts.stateTransition.executorFacet, + gettersFacet: expectedGatewayContracts.stateTransition.gettersFacet, + diamondInit: expectedGatewayContracts.stateTransition.diamondInit, + genesisUpgrade: expectedGatewayContracts.stateTransition.genesisUpgrade, + // No need for default upgrade on gateway + defaultUpgrade: address(0), + validatorTimelock: expectedGatewayContracts.stateTransition.validatorTimelock, + diamondProxy: address(0), + bytecodesSupplier: address(0) + }), + multicall3: expectedGatewayContracts.multicall3, + diamondCutData: expectedGatewayContracts.diamondCutData, + relayedSLDAValidator: expectedGatewayContracts.daContracts.relayedSLDAValidator, + validiumDAValidator: expectedGatewayContracts.daContracts.validiumDAValidator + }); + } + function initializeConfig() internal { deployerAddress = msg.sender; string memory root = vm.projectRoot(); @@ -137,8 +219,62 @@ contract GatewayCTMFromL1 is Script { genesisRollupLeafIndex: toml.readUint("$.genesis_rollup_leaf_index"), genesisBatchCommitment: toml.readBytes32("$.genesis_batch_commitment"), latestProtocolVersion: toml.readUint("$.latest_protocol_version"), + expectedRollupL2DAValidator: toml.readAddress("$.expected_rollup_l2_da_validator"), forceDeploymentsData: toml.readBytes("$.force_deployments_data") }); + + address aliasedGovernor = AddressAliasHelper.applyL1ToL2Alias(config.governance); + gatewayCTMDeployerConfig = GatewayCTMDeployerConfig({ + governanceAddress: aliasedGovernor, + salt: bytes32(0), + eraChainId: config.eraChainId, + l1ChainId: config.l1ChainId, + rollupL2DAValidatorAddress: config.expectedRollupL2DAValidator, + testnetVerifier: config.testnetVerifier, + adminSelectors: Utils.getAllSelectorsForFacet("Admin"), + executorSelectors: Utils.getAllSelectorsForFacet("Executor"), + mailboxSelectors: Utils.getAllSelectorsForFacet("Mailbox"), + gettersSelectors: Utils.getAllSelectorsForFacet("Getters"), + verifierParams: VerifierParams({ + recursionNodeLevelVkHash: config.recursionNodeLevelVkHash, + recursionLeafLevelVkHash: config.recursionLeafLevelVkHash, + recursionCircuitsSetVksHash: config.recursionCircuitsSetVksHash + }), + feeParams: FeeParams({ + pubdataPricingMode: config.diamondInitPubdataPricingMode, + batchOverheadL1Gas: uint32(config.diamondInitBatchOverheadL1Gas), + maxPubdataPerBatch: uint32(config.diamondInitMaxPubdataPerBatch), + maxL2GasPerBatch: uint32(config.diamondInitMaxL2GasPerBatch), + priorityTxMaxPubdata: uint32(config.diamondInitPriorityTxMaxPubdata), + minimalL2GasPrice: uint64(config.diamondInitMinimalL2GasPrice) + }), + bootloaderHash: config.bootloaderHash, + defaultAccountHash: config.defaultAAHash, + priorityTxMaxGasLimit: config.priorityTxMaxGasLimit, + genesisRoot: config.genesisRoot, + genesisRollupLeafIndex: uint64(config.genesisRollupLeafIndex), + genesisBatchCommitment: config.genesisBatchCommitment, + forceDeploymentsData: config.forceDeploymentsData, + protocolVersion: config.latestProtocolVersion + }); + } + + function distributeBaseToken() internal { + deployerAddress = msg.sender; + uint256 amountForDistribution = 100000000000000000000; + L1AssetRouter l1AR = L1AssetRouter(config.sharedBridgeProxy); + IL1NativeTokenVault nativeTokenVault = IL1NativeTokenVault(address(l1AR.nativeTokenVault())); + bytes32 baseTokenAssetID = nativeTokenVault.assetId(config.baseToken); + uint256 baseTokenOriginChainId = nativeTokenVault.originChainId(baseTokenAssetID); + TestnetERC20Token baseToken = TestnetERC20Token(config.baseToken); + + vm.startBroadcast(); + if (baseTokenOriginChainId == block.chainid) { + baseToken.mint(config.governanceAddr, amountForDistribution); + } else { + baseToken.transfer(config.governanceAddr, amountForDistribution); + } + vm.stopBroadcast(); } function saveOutput() internal { @@ -200,41 +336,6 @@ contract GatewayCTMFromL1 is Script { vm.writeToml(toml, path); } - /// @dev The sender may not have any privileges - function deployGatewayContracts() public { - output.multicall3 = _deployInternal(L2ContractsBytecodesLib.readMulticall3Bytecode(), hex""); - - deployGatewayFacets(); - - output.gatewayStateTransition.verifier = deployGatewayVerifier(); - output.gatewayStateTransition.validatorTimelock = deployValidatorTimelock(); - output.gatewayStateTransition.genesisUpgrade = address( - _deployInternal(L2ContractsBytecodesLib.readL1GenesisUpgradeBytecode(), hex"") - ); - console.log("Genesis upgrade deployed at", output.gatewayStateTransition.genesisUpgrade); - output.gatewayStateTransition.defaultUpgrade = address( - _deployInternal(L2ContractsBytecodesLib.readDefaultUpgradeBytecode(), hex"") - ); - console.log("Default upgrade deployed at", output.gatewayStateTransition.defaultUpgrade); - output.gatewayStateTransition.diamondInit = address( - _deployInternal(L2ContractsBytecodesLib.readDiamondInitBytecode(), hex"") - ); - console.log("Diamond init deployed at", output.gatewayStateTransition.diamondInit); - - deployGatewayChainTypeManager(); - setChainTypeManagerInValidatorTimelock(); - - output.relayedSLDAValidator = _deployInternal( - L2ContractsBytecodesLib.readRelayedSLDAValidatorBytecode(), - hex"" - ); - - output.validiumDAValidator = _deployInternal( - L2ContractsBytecodesLib.readValidiumL1DAValidatorBytecode(), - hex"" - ); - } - function _deployInternal(bytes memory bytecode, bytes memory constructorargs) internal returns (address) { return Utils.deployThroughL1({ @@ -263,7 +364,9 @@ contract GatewayCTMFromL1 is Script { ); console.log("Mailbox facet deployed at", mailboxFacet); - address executorFacet = address(_deployInternal(L2ContractsBytecodesLib.readExecutorFacetBytecode(), hex"")); + address executorFacet = address( + _deployInternal(L2ContractsBytecodesLib.readExecutorFacetBytecode(), abi.encode(config.l1ChainId)) + ); console.log("ExecutorFacet facet deployed at", executorFacet); address gettersFacet = address(_deployInternal(L2ContractsBytecodesLib.readGettersFacetBytecode(), hex"")); diff --git a/l1-contracts/deploy-scripts/GatewayPreparation.s.sol b/l1-contracts/deploy-scripts/GatewayPreparation.s.sol index 1c68dd82d..633446230 100644 --- a/l1-contracts/deploy-scripts/GatewayPreparation.s.sol +++ b/l1-contracts/deploy-scripts/GatewayPreparation.s.sol @@ -7,6 +7,10 @@ import {Script, console2 as console} from "forge-std/Script.sol"; // import {Vm} from "forge-std/Vm.sol"; import {stdToml} from "forge-std/StdToml.sol"; +// It's required to disable lints to force the compiler to compile the contracts +// solhint-disable no-unused-import +import {TestnetERC20Token} from "contracts/dev-contracts/TestnetERC20Token.sol"; + import {Ownable} from "@openzeppelin/contracts-v4/access/Ownable.sol"; import {IBridgehub, BridgehubBurnCTMAssetData} from "contracts/bridgehub/IBridgehub.sol"; import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; @@ -24,9 +28,13 @@ import {SET_ASSET_HANDLER_COUNTERPART_ENCODING_VERSION} from "contracts/bridge/a import {CTM_DEPLOYMENT_TRACKER_ENCODING_VERSION} from "contracts/bridgehub/CTMDeploymentTracker.sol"; import {L2AssetRouter, IL2AssetRouter} from "contracts/bridge/asset-router/L2AssetRouter.sol"; import {L1Nullifier} from "contracts/bridge/L1Nullifier.sol"; +import {L1AssetRouter} from "contracts/bridge/asset-router/L1AssetRouter.sol"; +import {IL1NativeTokenVault} from "contracts/bridge/ntv/IL1NativeTokenVault.sol"; import {BridgehubMintCTMAssetData} from "contracts/bridgehub/IBridgehub.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {L2_ASSET_ROUTER_ADDR} from "contracts/common/L2ContractAddresses.sol"; +import {ETH_TOKEN_ADDRESS} from "contracts/common/Config.sol"; +import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; import {IAdmin} from "contracts/state-transition/chain-interfaces/IAdmin.sol"; import {FinalizeL1DepositParams} from "contracts/bridge/interfaces/IL1Nullifier.sol"; @@ -246,6 +254,33 @@ contract GatewayPreparation is Script { function migrateChainToGateway(address chainAdmin, address accessControlRestriction, uint256 chainId) public { initializeConfig(); + IBridgehub bridgehubContract = IBridgehub(config.bridgehub); + bytes32 gatewayBaseTokenAssetId = bridgehubContract.baseTokenAssetId(config.gatewayChainId); + bytes32 ethTokenAssetId = DataEncoding.encodeNTVAssetId(block.chainid, ETH_TOKEN_ADDRESS); + + // Fund chain admin with tokens + if (gatewayBaseTokenAssetId != ethTokenAssetId) { + deployerAddress = msg.sender; + uint256 amountForDistribution = 100000000000000000000; + L1AssetRouter l1AR = L1AssetRouter(config.sharedBridgeProxy); + IL1NativeTokenVault nativeTokenVault = IL1NativeTokenVault(address(l1AR.nativeTokenVault())); + address baseTokenAddress = nativeTokenVault.tokenAddress(gatewayBaseTokenAssetId); + uint256 baseTokenOriginChainId = nativeTokenVault.originChainId(gatewayBaseTokenAssetId); + TestnetERC20Token baseToken = TestnetERC20Token(baseTokenAddress); + uint256 deployerBalance = baseToken.balanceOf(deployerAddress); + console.log("Base token origin id: ", baseTokenOriginChainId); + + vm.startBroadcast(); + if (baseTokenOriginChainId == block.chainid) { + baseToken.mint(chainAdmin, amountForDistribution); + } else { + baseToken.transfer(chainAdmin, amountForDistribution); + } + vm.stopBroadcast(); + } + + console.log("Chain Admin address:", chainAdmin); + // TODO(EVM-746): Use L2-based chain admin contract address l2ChainAdmin = AddressAliasHelper.applyL1ToL2Alias(chainAdmin); diff --git a/l1-contracts/deploy-scripts/InitializeL2WethToken.s.sol b/l1-contracts/deploy-scripts/InitializeL2WethToken.s.sol index c9b1de8c6..57a63a176 100644 --- a/l1-contracts/deploy-scripts/InitializeL2WethToken.s.sol +++ b/l1-contracts/deploy-scripts/InitializeL2WethToken.s.sol @@ -44,7 +44,7 @@ contract InitializeL2WethTokenScript is Script { // Parse some config from output of l1 deployment string memory root = vm.projectRoot(); - string memory path = string.concat(root, "/script-out/output-deploy-l1.toml"); + string memory path = string.concat(root, vm.envString("L1_OUTPUT")); string memory toml = vm.readFile(path); config.create2FactoryAddr = toml.readAddress("$.create2_factory_addr"); diff --git a/l1-contracts/deploy-scripts/L2ContractsBytecodesLib.sol b/l1-contracts/deploy-scripts/L2ContractsBytecodesLib.sol index 9b672deb2..7b470f272 100644 --- a/l1-contracts/deploy-scripts/L2ContractsBytecodesLib.sol +++ b/l1-contracts/deploy-scripts/L2ContractsBytecodesLib.sol @@ -76,6 +76,15 @@ library L2ContractsBytecodesLib { ); } + /// @notice Reads the bytecode of the TransparentUpgradeableProxy contract. + /// @return The bytecode of the TransparentUpgradeableProxy contract. + function readTransparentUpgradeableProxyBytecodeFromSystemContracts() internal view returns (bytes memory) { + return + Utils.readHardhatBytecode( + "/../system-contracts/artifacts-zk/@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.json" + ); + } + /// @notice Reads the bytecode of the ForceDeployUpgrader contract. /// @return The bytecode of the ForceDeployUpgrader contract. function readForceDeployUpgraderBytecode() internal view returns (bytes memory) { @@ -302,4 +311,13 @@ library L2ContractsBytecodesLib { "/../l1-contracts/artifacts-zk/contracts/governance/L2ProxyAdminDeployer.sol/L2ProxyAdminDeployer.json" ); } + + /// @notice Reads the bytecode of the L2WrappedBaseToken contract. + /// @return The bytecode of the L2WrappedBaseToken contract. + function readL2WrappedBaseToken() internal view returns (bytes memory) { + return + Utils.readHardhatBytecode( + "/../l1-contracts/artifacts-zk/contracts/bridge/L2WrappedBaseToken.sol/L2WrappedBaseToken.json" + ); + } } diff --git a/l1-contracts/deploy-scripts/RegisterZKChain.s.sol b/l1-contracts/deploy-scripts/RegisterZKChain.s.sol index b1c8ae292..31f16f0fa 100644 --- a/l1-contracts/deploy-scripts/RegisterZKChain.s.sol +++ b/l1-contracts/deploy-scripts/RegisterZKChain.s.sol @@ -86,7 +86,7 @@ contract RegisterZKChainScript is Script { initializeConfig(); // TODO: some chains may not want to have a legacy shared bridge - runInner("/script-out/output-register-zk-chain.toml", true); + runInner("/script-out/output-register-zk-chain.toml", false); } function runForTest() public { @@ -288,7 +288,13 @@ contract RegisterZKChainScript is Script { function registerAssetIdOnBridgehub() internal { IBridgehub bridgehub = IBridgehub(config.bridgehub); Ownable ownable = Ownable(config.bridgehub); - bytes32 baseTokenAssetId = DataEncoding.encodeNTVAssetId(block.chainid, config.baseToken); + INativeTokenVault ntv = INativeTokenVault(config.nativeTokenVault); + bytes32 baseTokenAssetId = ntv.assetId(config.baseToken); + uint256 baseTokenOriginChain = ntv.originChainId(baseTokenAssetId); + + if (baseTokenAssetId == bytes32(0)) { + baseTokenAssetId = DataEncoding.encodeNTVAssetId(block.chainid, config.baseToken); + } if (bridgehub.assetIdIsRegistered(baseTokenAssetId)) { console.log("Base token asset id already registered on Bridgehub"); @@ -308,13 +314,17 @@ contract RegisterZKChainScript is Script { function registerTokenOnNTV() internal { INativeTokenVault ntv = INativeTokenVault(config.nativeTokenVault); - // Ownable ownable = Ownable(config.nativeTokenVault); - bytes32 baseTokenAssetId = DataEncoding.encodeNTVAssetId(block.chainid, config.baseToken); + bytes32 baseTokenAssetId = ntv.assetId(config.baseToken); + uint256 baseTokenOriginChain = ntv.originChainId(baseTokenAssetId); + + // If it hasn't been registered already with ntv + if (baseTokenAssetId == bytes32(0)) { + baseTokenAssetId = DataEncoding.encodeNTVAssetId(block.chainid, config.baseToken); + } config.baseTokenAssetId = baseTokenAssetId; if (ntv.tokenAddress(baseTokenAssetId) != address(0) || config.baseToken == ETH_TOKEN_ADDRESS) { console.log("Token already registered on NTV"); } else { - // bytes memory data = abi.encodeCall(ntv.registerToken, (config.baseToken)); vm.broadcast(); ntv.registerToken(config.baseToken); console.log("Token registered on NTV"); diff --git a/l1-contracts/deploy-scripts/Utils.sol b/l1-contracts/deploy-scripts/Utils.sol index 9147b20be..4995fc65b 100644 --- a/l1-contracts/deploy-scripts/Utils.sol +++ b/l1-contracts/deploy-scripts/Utils.sol @@ -46,6 +46,7 @@ address constant L2_BRIDGEHUB_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x02); address constant L2_ASSET_ROUTER_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x03); address constant L2_NATIVE_TOKEN_VAULT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x04); address constant L2_MESSAGE_ROOT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x05); +address constant L2_WETH_IMPL_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x07); address constant L2_CREATE2_FACTORY_ADDRESS = address(USER_CONTRACTS_OFFSET); @@ -63,6 +64,7 @@ struct StateTransitionDeployedAddresses { address defaultUpgrade; address validatorTimelock; address diamondProxy; + address bytecodesSupplier; } /// @dev We need to use a struct instead of list of params to prevent stack too deep error @@ -189,7 +191,6 @@ library Utils { function readHardhatBytecode(string memory artifactPath) internal view returns (bytes memory) { string memory root = vm.projectRoot(); string memory path = string.concat(root, artifactPath); - console.log(path); string memory json = vm.readFile(path); bytes memory bytecode = vm.parseJsonBytes(json, ".bytecode"); return bytecode; @@ -209,10 +210,34 @@ library Utils { ".json" ) ); - bytes memory bytecode = vm.parseJson(file, "$.bytecode"); + bytes memory bytecode = vm.parseJsonBytes(file, "$.bytecode"); return bytecode; } + /** + * @dev Returns the bytecode of a given system contract. + */ + function readPrecompileBytecode(string memory filename) internal view returns (bytes memory) { + // It is the only exceptional case + if (keccak256(abi.encodePacked(filename)) == keccak256(abi.encodePacked("EventWriter"))) { + return + vm.readFileBinary( + // solhint-disable-next-line func-named-parameters + string.concat("../system-contracts/contracts-preprocessed/artifacts/", filename, ".yul.zbin") + ); + } + + return + vm.readFileBinary( + // solhint-disable-next-line func-named-parameters + string.concat( + "../system-contracts/contracts-preprocessed/precompiles/artifacts/", + filename, + ".yul.zbin" + ) + ); + } + /** * @dev Deploy a Create2Factory contract. */ @@ -224,8 +249,8 @@ library Utils { child := create(0, add(bytecode, 0x20), mload(bytecode)) } vm.stopBroadcast(); - require(child != address(0), "Failed to deploy Create2Factory"); - require(child.code.length > 0, "Failed to deploy Create2Factory"); + require(child != address(0), "Failed to deploy create2factory"); + require(child.code.length > 0, "Failed to deploy create2factory"); return child; } @@ -795,6 +820,15 @@ library Utils { return bytecode; } + function readZKFoundryBytecode( + string memory fileName, + string memory contractName + ) internal view returns (bytes memory) { + string memory path = string.concat("/../l1-contracts/zkout/", fileName, "/", contractName, ".json"); + bytes memory bytecode = readFoundryBytecode(path); + return bytecode; + } + /** * @dev Read hardhat bytecodes */ diff --git a/l1-contracts/deploy-scripts/ZkSyncScriptErrors.sol b/l1-contracts/deploy-scripts/ZkSyncScriptErrors.sol index 76295d633..8b19da970 100644 --- a/l1-contracts/deploy-scripts/ZkSyncScriptErrors.sol +++ b/l1-contracts/deploy-scripts/ZkSyncScriptErrors.sol @@ -1,12 +1,14 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.24; -error FailedToDeploy(ZksyncContract); -error BytecodeNotSet(); -error FailedToDeployViaCreate2(); -error MissingAddress(ZksyncContract); +// 0x86bb51b8 error AddressHasNoCode(address); +// 0x07637bd8 error MintFailed(); +// 0xbd13da86 +error ProxyAdminIncorrect(address expectedProxyAdmin, address proxyAdmin); +// 0x565fae63 +error ProxyAdminIncorrectOwner(address proxyAdmin, address governance); enum ZksyncContract { Create2Factory, diff --git a/l1-contracts/deploy-scripts/upgrade/BytecodePublisher.s.sol b/l1-contracts/deploy-scripts/upgrade/BytecodePublisher.s.sol new file mode 100644 index 000000000..aca79e2e1 --- /dev/null +++ b/l1-contracts/deploy-scripts/upgrade/BytecodePublisher.s.sol @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +// solhint-disable gas-custom-errors, reason-string + +import {Vm} from "forge-std/Vm.sol"; +import {console2 as console} from "forge-std/Script.sol"; + +import {BytecodesSupplier} from "contracts/upgrades/BytecodesSupplier.sol"; +import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; + +library BytecodePublisher { + // Cheatcodes address, 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D. + address internal constant VM_ADDRESS = address(uint160(uint256(keccak256("hevm cheat code")))); + Vm internal constant vm = Vm(VM_ADDRESS); + + // 100 kb + uint256 constant MAX_BATCH_SIZE = 126_000; + + /// @notice Publishes bytecodes in batches, each not exceeding 100KB + /// @param bytecodes The array of bytecodes to publish + function publishBytecodesInBatches(BytecodesSupplier bytecodesSupplier, bytes[] memory bytecodes) internal { + uint256 totalBytecodes = bytecodes.length; + require(totalBytecodes > 0, "No bytecodes to publish"); + + uint256 currentBatchSize = 0; + uint256 batchStartIndex = 0; + + for (uint256 i = 0; i < totalBytecodes; i++) { + bytes32 hash = L2ContractHelper.hashL2Bytecode(bytecodes[i]); + if (bytecodesSupplier.publishingBlock(hash) != 0) { + console.log("The following bytecode has already been published:"); + console.logBytes32(hash); + continue; + } else { + console.log("Publishing the following bytecode:"); + console.logBytes32(hash); + } + + uint256 bytecodeSize = bytecodes[i].length; + + if (bytecodeSize > MAX_BATCH_SIZE) { + console.log("The following bytecode is too large ", i); + console.log("Its size ", bytecodeSize); + + revert("Bytecode is not publishable"); + } + + // Check if adding this bytecode exceeds the MAX_BATCH_SIZE + if (currentBatchSize + bytecodeSize > MAX_BATCH_SIZE) { + // Publish the current batch + bytes[] memory currentBatch = slice(bytecodes, batchStartIndex, i); + _publishBatch(bytecodesSupplier, currentBatch); + + // Reset for the next batch + batchStartIndex = i; + currentBatchSize = bytecodeSize; + } else { + currentBatchSize += bytecodeSize; + } + } + + // Publish the last batch if any + if (batchStartIndex < totalBytecodes) { + bytes[] memory lastBatch = slice(bytecodes, batchStartIndex, totalBytecodes); + _publishBatch(bytecodesSupplier, lastBatch); + } + } + + /// @notice Internal function to publish a single batch and emit an event + /// @param batch The batch of bytecodes to publish + function _publishBatch(BytecodesSupplier bytecodesSupplier, bytes[] memory batch) internal { + vm.broadcast(); + bytecodesSupplier.publishBytecodes(batch); + } + + /// @notice Slices a bytes[][] array from start index to end index (exclusive) + /// @param array The original bytes[][] array + /// @param start The starting index (inclusive) + /// @param end The ending index (exclusive) + /// @return sliced The sliced bytes[][] array + function slice(bytes[] memory array, uint256 start, uint256 end) internal pure returns (bytes[] memory sliced) { + require(start <= end && end <= array.length, "Invalid slice indices"); + sliced = new bytes[](end - start); + for (uint256 i = start; i < end; i++) { + sliced[i - start] = array[i]; + } + } +} diff --git a/l1-contracts/deploy-scripts/upgrade/ChainUpgrade.s.sol b/l1-contracts/deploy-scripts/upgrade/ChainUpgrade.s.sol index 7df6863d3..4d99ae0db 100644 --- a/l1-contracts/deploy-scripts/upgrade/ChainUpgrade.s.sol +++ b/l1-contracts/deploy-scripts/upgrade/ChainUpgrade.s.sol @@ -27,19 +27,13 @@ contract ChainUpgrade is Script { address ownerAddress; uint256 chainChainId; address chainDiamondProxyAddress; - bool validiumMode; bool permanentRollup; // FIXME: From ecosystem, maybe move to a different struct - address expectedRollupL2DAValidator; - address expectedL2GatewayUpgrade; - address expectedValidiumL2DAValidator; - address permanentRollupRestriction; address bridgehubProxyAddress; address oldSharedBridgeProxyAddress; } struct Output { - address l2DAValidator; address accessControlRestriction; address chainAdmin; } @@ -63,18 +57,30 @@ contract ChainUpgrade is Script { initializeConfig(configPath, ecosystemInputPath, ecosystemOutputPath); checkCorrectOwnerAddress(); - // Preparation of chain consists of two parts: - // - Deploying l2 da validator - // - Deploying new chain admin - deployNewL2DAValidator(); - deployL2GatewayUpgrade(); + // Deploying of the new chain admin is not strictly needed + // but our existing tooling relies on the new impl of chain admin deployNewChainAdmin(); governanceMoveToNewChainAdmin(); + // This script does nothing, it only checks that the provided inputs are correct. + // It is just a wrapper to easily call `upgradeChain` + saveOutput(outputPath); } + function run() public { + // TODO: maybe make it read from 1 exact input file, + // for now doing it this way is just faster + + prepareChain( + "/script-config/gateway-upgrade-ecosystem.toml", + "/script-out/gateway-upgrade-ecosystem.toml", + "/script-config/gateway-upgrade-chain.toml", + "/script-out/gateway-upgrade-chain.toml" + ); + } + function upgradeChain(uint256 oldProtocolVersion, Diamond.DiamondCutData memory upgradeCutData) public { Utils.adminExecute( output.chainAdmin, @@ -101,17 +107,9 @@ contract ChainUpgrade is Script { config.ownerAddress = toml.readAddress("$.owner_address"); config.chainChainId = toml.readUint("$.chain.chain_id"); - config.validiumMode = toml.readBool("$.chain.validium_mode"); config.chainDiamondProxyAddress = toml.readAddress("$.chain.diamond_proxy_address"); config.permanentRollup = toml.readBool("$.chain.permanent_rollup"); - toml = vm.readFile(ecosystemOutputPath); - - config.expectedRollupL2DAValidator = toml.readAddress("$.contracts_config.expected_rollup_l2_da_validator"); - config.expectedValidiumL2DAValidator = toml.readAddress("$.contracts_config.expected_validium_l2_da_validator"); - config.expectedL2GatewayUpgrade = toml.readAddress("$.contracts_config.expected_l2_gateway_upgrade"); - config.permanentRollupRestriction = toml.readAddress("$.deployed_addresses.permanent_rollup_restriction"); - toml = vm.readFile(ecosystemInputPath); config.bridgehubProxyAddress = toml.readAddress("$.contracts.bridgehub_proxy_address"); @@ -125,51 +123,15 @@ contract ChainUpgrade is Script { require(currentAdminOwner == config.ownerAddress, "Only the owner of the chain admin can call this function"); } - function deployNewL2DAValidator() internal { - address expectedL2DAValidator = Utils.deployThroughL1Deterministic({ - // FIXME: for now this script only works with rollup chains - bytecode: L2ContractsBytecodesLib.readRollupL2DAValidatorBytecode(), - constructorargs: hex"", - create2salt: bytes32(0), - l2GasLimit: Utils.MAX_PRIORITY_TX_GAS, - factoryDeps: new bytes[](0), - chainId: config.chainChainId, - bridgehubAddress: config.bridgehubProxyAddress, - l1SharedBridgeProxy: config.oldSharedBridgeProxyAddress - }); - // FIXME: for now this script only works with rollup chains - require(expectedL2DAValidator == config.expectedRollupL2DAValidator, "Invalid L2DAValidator address"); - - output.l2DAValidator = expectedL2DAValidator; - } - - function deployL2GatewayUpgrade() internal { - address expectedGatewayUpgrade = Utils.deployThroughL1Deterministic({ - bytecode: L2ContractsBytecodesLib.readGatewayUpgradeBytecode(), - constructorargs: hex"", - create2salt: bytes32(0), - l2GasLimit: Utils.MAX_PRIORITY_TX_GAS, - factoryDeps: new bytes[](0), - chainId: config.chainChainId, - bridgehubAddress: config.bridgehubProxyAddress, - l1SharedBridgeProxy: config.oldSharedBridgeProxyAddress - }); - require(expectedGatewayUpgrade == config.expectedL2GatewayUpgrade, "Invalid L2Gateway address"); - } - function deployNewChainAdmin() internal { + vm.broadcast(config.ownerAddress); AccessControlRestriction accessControlRestriction = new AccessControlRestriction(0, config.ownerAddress); address[] memory restrictions; - if (config.permanentRollup) { - restrictions = new address[](2); - restrictions[0] = address(accessControlRestriction); - restrictions[1] = config.permanentRollupRestriction; - } else { - restrictions = new address[](1); - restrictions[0] = address(accessControlRestriction); - } + restrictions = new address[](1); + restrictions[0] = address(accessControlRestriction); + vm.broadcast(config.ownerAddress); ChainAdmin newChainAdmin = new ChainAdmin(restrictions); output.chainAdmin = address(newChainAdmin); output.accessControlRestriction = address(accessControlRestriction); @@ -201,7 +163,6 @@ contract ChainUpgrade is Script { } function saveOutput(string memory outputPath) internal { - vm.serializeAddress("root", "l2_da_validator_addr", output.l2DAValidator); vm.serializeAddress("root", "chain_admin_addr", output.chainAdmin); string memory toml = vm.serializeAddress("root", "access_control_restriction", output.accessControlRestriction); diff --git a/l1-contracts/deploy-scripts/upgrade/EcosystemUpgrade.s.sol b/l1-contracts/deploy-scripts/upgrade/EcosystemUpgrade.s.sol index 124d33294..235cf8455 100644 --- a/l1-contracts/deploy-scripts/upgrade/EcosystemUpgrade.s.sol +++ b/l1-contracts/deploy-scripts/upgrade/EcosystemUpgrade.s.sol @@ -63,11 +63,16 @@ import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol import {ProposedUpgrade} from "contracts/upgrades/BaseZkSyncUpgrade.sol"; import {L2CanonicalTransaction} from "contracts/common/Messaging.sol"; - -import {L2_FORCE_DEPLOYER_ADDR, L2_COMPLEX_UPGRADER_ADDR} from "contracts/common/L2ContractAddresses.sol"; +import {L2_FORCE_DEPLOYER_ADDR, L2_COMPLEX_UPGRADER_ADDR, L2_DEPLOYER_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IComplexUpgrader} from "contracts/state-transition/l2-deps/IComplexUpgrader.sol"; import {GatewayUpgradeEncodedInput} from "contracts/upgrades/GatewayUpgrade.sol"; import {TransitionaryOwner} from "contracts/governance/TransitionaryOwner.sol"; +import {SystemContractsProcessing} from "./SystemContractsProcessing.s.sol"; +import {BytecodePublisher} from "./BytecodePublisher.s.sol"; +import {BytecodesSupplier} from "contracts/upgrades/BytecodesSupplier.sol"; +import {GovernanceUpgradeTimer} from "contracts/upgrades/GovernanceUpgradeTimer.sol"; +import {L2WrappedBaseTokenStore} from "contracts/bridge/L2WrappedBaseTokenStore.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; struct FixedForceDeploymentsData { uint256 l1ChainId; @@ -82,8 +87,6 @@ struct FixedForceDeploymentsData { bytes32 messageRootBytecodeHash; address l2SharedBridgeLegacyImpl; address l2BridgedStandardERC20Impl; - address l2BridgeProxyOwnerAddress; - address l2BridgedStandardERC20ProxyOwnerAddress; } // A subset of the ones used for tests @@ -116,26 +119,20 @@ contract EcosystemUpgrade is Script { ExpectedL2Addresses expectedL2Addresses; address chainAdmin; address accessControlRestrictionAddress; - address permanentRollupRestriction; address validatorTimelock; address gatewayUpgrade; address create2Factory; address transitionaryOwner; + address upgradeTimer; + address bytecodesSupplier; + address l2WrappedBaseTokenStore; } struct ExpectedL2Addresses { address expectedRollupL2DAValidator; address expectedValidiumL2DAValidator; - address expectedL2GatewayUpgrade; address l2SharedBridgeLegacyImpl; address l2BridgedStandardERC20Impl; - // In reality, the following addresses need to be - // deployed only on a settlement layer, i.e. the Gateway. - address expectedL2ProxyAdminDeployer; - address expectedL2ProxyAdmin; - address expectedL2AdminFactory; - address expectedL2PermanentRestrictionImpl; - address expectedL2PermanentRestrictionProxy; } // solhint-disable-next-line gas-struct-packing @@ -145,6 +142,7 @@ contract EcosystemUpgrade is Script { } struct DataAvailabilityDeployedAddresses { + address rollupDAManager; address l1RollupDAValidator; address l1ValidiumDAValidator; } @@ -174,6 +172,10 @@ contract EcosystemUpgrade is Script { address deployerAddress; uint256 eraChainId; address ownerAddress; + // This is the address of the ecosystem admin. + // Note, that it is not the owner, but rather the address that is responsible + // for facilitating partially trusted, but not critical tasks. + address ecosystemAdminAddress; bool testnetVerifier; ContractsConfig contracts; TokensConfig tokens; @@ -193,7 +195,6 @@ contract EcosystemUpgrade is Script { bytes32 genesisRoot; uint256 genesisRollupLeafIndex; bytes32 genesisBatchCommitment; - uint256 latestProtocolVersion; bytes32 recursionNodeLevelVkHash; bytes32 recursionLeafLevelVkHash; bytes32 recursionCircuitsSetVksHash; @@ -215,8 +216,6 @@ contract EcosystemUpgrade is Script { address transparentProxyAdmin; address eraDiamondProxy; address blobVersionedHashRetriever; - address l2BridgeProxyOwnerAddress; - address l2BridgedStandardERC20ProxyOwnerAddress; } struct TokensConfig { @@ -227,6 +226,18 @@ contract EcosystemUpgrade is Script { GeneratedData internal generatedData; DeployedAddresses internal addresses; + uint256[] factoryDepsHashes; + + struct CachedBytecodeHashes { + bytes32 sharedL2LegacyBridgeBytecodeHash; + bytes32 erc20StandardImplBytecodeHash; + bytes32 rollupL2DAValidatorBytecodeHash; + bytes32 validiumL2DAValidatorBytecodeHash; + bytes32 transparentUpgradableProxyBytecodeHash; + } + + CachedBytecodeHashes internal cachedBytecodeHashes; + function prepareEcosystemContracts(string memory configPath, string memory outputPath) public { string memory root = vm.projectRoot(); configPath = string.concat(root, configPath); @@ -236,6 +247,10 @@ contract EcosystemUpgrade is Script { instantiateCreate2Factory(); + deployBytecodesSupplier(); + publishBytecodes(); + initializeExpectedL2Addresses(); + deployVerifier(); deployDefaultUpgrade(); deployGenesisUpgrade(); @@ -244,8 +259,6 @@ contract EcosystemUpgrade is Script { deployDAValidators(); deployValidatorTimelock(); - // TODO: restore - // deployChainAdmin(); deployBridgehubImplementation(); deployMessageRootContract(); @@ -259,15 +272,15 @@ contract EcosystemUpgrade is Script { deployCTMDeploymentTracker(); + // Important, this must come after the initializeExpectedL2Addresses initializeGeneratedData(); - initializeExpectedL2Addresses(); deployChainTypeManagerContract(); setChainTypeManagerInValidatorTimelock(); - deployPermanentRollupRestriction(); - deployTransitionaryOwner(); + deployL2WrappedBaseTokenStore(); + deployGovernanceUpgradeTimer(); updateOwners(); @@ -275,7 +288,10 @@ contract EcosystemUpgrade is Script { } function run() public { - console.log("Deploying L1 contracts"); + prepareEcosystemContracts( + "/script-config/gateway-upgrade-ecosystem.toml", + "/script-out/gateway-upgrade-ecosystem.toml" + ); } function provideAcceptOwnershipCalls() public returns (Call[] memory calls) { @@ -283,22 +299,22 @@ contract EcosystemUpgrade is Script { calls = new Call[](4); calls[0] = Call({ - target: addresses.permanentRollupRestriction, + target: addresses.validatorTimelock, data: abi.encodeCall(Ownable2StepUpgradeable.acceptOwnership, ()), value: 0 }); calls[1] = Call({ - target: addresses.validatorTimelock, + target: addresses.bridges.sharedBridgeProxy, data: abi.encodeCall(Ownable2StepUpgradeable.acceptOwnership, ()), value: 0 }); calls[2] = Call({ - target: addresses.bridges.sharedBridgeProxy, + target: addresses.bridgehub.ctmDeploymentTrackerProxy, data: abi.encodeCall(Ownable2StepUpgradeable.acceptOwnership, ()), value: 0 }); calls[3] = Call({ - target: addresses.bridgehub.ctmDeploymentTrackerProxy, + target: addresses.daAddresses.rollupDAManager, data: abi.encodeCall(Ownable2StepUpgradeable.acceptOwnership, ()), value: 0 }); @@ -325,10 +341,12 @@ contract EcosystemUpgrade is Script { function _composeUpgradeTx() internal returns (L2CanonicalTransaction memory transaction) { transaction = L2CanonicalTransaction({ - // FIXME: dont use hardcoded values + // TODO: dont use hardcoded values txType: 254, from: uint256(uint160(L2_FORCE_DEPLOYER_ADDR)), - to: uint256(uint160(address(L2_COMPLEX_UPGRADER_ADDR))), + // Note, that we actually do force deployments to the ContractDeployer and not complex upgrader. + // The implementation of the ComplexUpgrader will be deployed during one of the force deployments. + to: uint256(uint160(address(L2_DEPLOYER_SYSTEM_CONTRACT_ADDR))), gasLimit: 72_000_000, gasPerPubdataByteLimit: 800, maxFeePerGas: 0, @@ -341,7 +359,7 @@ contract EcosystemUpgrade is Script { data: new bytes(0), signature: new bytes(0), // All factory deps should've been published before - factoryDeps: new uint256[](0), + factoryDeps: factoryDepsHashes, paymasterInput: new bytes(0), // 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 @@ -354,7 +372,9 @@ contract EcosystemUpgrade is Script { } function getOldProtocolDeadline() public returns (uint256) { - return 7 days; + // Note, that it is this way by design, on stage2 it + // will be set to 0 + return type(uint256).max; } function getOldProtocolVersion() public returns (uint256) { @@ -366,7 +386,7 @@ contract EcosystemUpgrade is Script { uint256 PREVIOUS_PROTOCOL_VERSION = getOldProtocolVersion(); uint256 DEADLINE = getOldProtocolDeadline(); uint256 NEW_PROTOCOL_VERSION = getNewProtocolVersion(); - Call memory call = Call({ + Call memory ctmCall = Call({ target: config.contracts.stateTransitionManagerAddress, data: abi.encodeCall( ChainTypeManager.setNewVersionUpgrade, @@ -375,8 +395,16 @@ contract EcosystemUpgrade is Script { value: 0 }); - calls = new Call[](1); - calls[0] = call; + // The call that will start the timer till the end of the upgrade. + Call memory timerCall = Call({ + target: addresses.upgradeTimer, + data: abi.encodeCall(GovernanceUpgradeTimer.startTimer, ()), + value: 0 + }); + + calls = new Call[](2); + calls[0] = ctmCall; + calls[1] = timerCall; } function getChainUpgradeInfo() public returns (Diamond.DiamondCutData memory upgradeCutData) { @@ -417,34 +445,88 @@ contract EcosystemUpgrade is Script { recursionCircuitsSetVksHash: config.contracts.recursionCircuitsSetVksHash }); - // TODO: we should fill this one up completely, but it is straightforward - IL2ContractDeployer.ForceDeployment[] memory baseForceDeployments = new IL2ContractDeployer.ForceDeployment[]( - 0 + IL2ContractDeployer.ForceDeployment[] memory baseForceDeployments = SystemContractsProcessing + .getBaseForceDeployments(); + + // This upgrade has complex upgrade. We do not know whether its implementation has been deployed. + // We will do the following trick: + // - Deploy the upgrade implementation into the address of the complex upgrader. And execute the upgrade inside the constructor. + // - Deploy back the original bytecode. + // + // Also, we need to predeploy the bridges implementation + IL2ContractDeployer.ForceDeployment[] + memory additionalForceDeployments = new IL2ContractDeployer.ForceDeployment[](6); + additionalForceDeployments[0] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: cachedBytecodeHashes.sharedL2LegacyBridgeBytecodeHash, + newAddress: addresses.expectedL2Addresses.l2SharedBridgeLegacyImpl, + callConstructor: true, + value: 0, + input: "" + }); + additionalForceDeployments[1] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: cachedBytecodeHashes.erc20StandardImplBytecodeHash, + newAddress: addresses.expectedL2Addresses.l2BridgedStandardERC20Impl, + callConstructor: true, + value: 0, + input: "" + }); + additionalForceDeployments[2] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: cachedBytecodeHashes.rollupL2DAValidatorBytecodeHash, + newAddress: addresses.expectedL2Addresses.expectedRollupL2DAValidator, + callConstructor: true, + value: 0, + input: "" + }); + additionalForceDeployments[3] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: cachedBytecodeHashes.validiumL2DAValidatorBytecodeHash, + newAddress: addresses.expectedL2Addresses.expectedValidiumL2DAValidator, + callConstructor: true, + value: 0, + input: "" + }); + additionalForceDeployments[4] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readGatewayUpgradeBytecode()), + newAddress: L2_COMPLEX_UPGRADER_ADDR, + callConstructor: true, + value: 0, + input: "" + }); + // Getting the contract back to normal + additionalForceDeployments[5] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(Utils.readSystemContractsBytecode("ComplexUpgrader")), + newAddress: L2_COMPLEX_UPGRADER_ADDR, + callConstructor: false, + value: 0, + input: "" + }); + + IL2ContractDeployer.ForceDeployment[] memory forceDeployments = SystemContractsProcessing.mergeForceDeployments( + baseForceDeployments, + additionalForceDeployments ); + address ctmDeployer = addresses.bridgehub.ctmDeploymentTrackerProxy; GatewayUpgradeEncodedInput memory gateUpgradeInput = GatewayUpgradeEncodedInput({ - baseForceDeployments: baseForceDeployments, + forceDeployments: forceDeployments, + l2GatewayUpgradePosition: forceDeployments.length - 2, ctmDeployer: ctmDeployer, fixedForceDeploymentsData: generatedData.forceDeploymentsData, - l2GatewayUpgrade: addresses.expectedL2Addresses.expectedL2GatewayUpgrade, oldValidatorTimelock: config.contracts.oldValidatorTimelock, - newValidatorTimelock: addresses.validatorTimelock + newValidatorTimelock: addresses.validatorTimelock, + wrappedBaseTokenStore: addresses.l2WrappedBaseTokenStore }); bytes memory postUpgradeCalldata = abi.encode(gateUpgradeInput); ProposedUpgrade memory proposedUpgrade = ProposedUpgrade({ l2ProtocolUpgradeTx: _composeUpgradeTx(), - factoryDeps: new bytes[](0), bootloaderHash: config.contracts.bootloaderHash, defaultAccountHash: config.contracts.defaultAAHash, verifier: addresses.stateTransition.verifier, verifierParams: verifierParams, l1ContractsUpgradeCalldata: new bytes(0), postUpgradeCalldata: postUpgradeCalldata, - // FIXME: TBH, I am not sure if even should even put any time there, - // but we may upgradeTimestamp: 0, newProtocolVersion: getNewProtocolVersion() }); @@ -456,8 +538,19 @@ contract EcosystemUpgrade is Script { }); } + function getEcosystemAdmin() external returns (address) { + return config.ecosystemAdminAddress; + } + + function getStage1UpgradeCalls() public returns (Call[] memory calls) { + // Stage 1 of the upgrade: + // - accept all the ownerships of the contracts + // - set the new upgrade data for chains + update validator timelock. + calls = mergeCalls(provideAcceptOwnershipCalls(), provideSetNewVersionUpgradeCall()); + } + function getStage2UpgradeCalls() public returns (Call[] memory calls) { - calls = new Call[](9); + calls = new Call[](11); // We need to firstly update all the contracts calls[0] = Call({ @@ -488,6 +581,7 @@ contract EcosystemUpgrade is Script { data: abi.encodeCall( ProxyAdmin.upgrade, ( + // Note, that we do not need to run the initializer ITransparentUpgradeableProxy(payable(config.contracts.oldSharedBridgeProxyAddress)), addresses.bridges.l1NullifierImplementation ) @@ -546,6 +640,18 @@ contract EcosystemUpgrade is Script { data: abi.encodeCall(L1Nullifier.setL1AssetRouter, (addresses.bridges.sharedBridgeProxy)), value: 0 }); + calls[9] = Call({ + target: config.contracts.stateTransitionManagerAddress, + // Making the old protocol version no longer invalid + data: abi.encodeCall(ChainTypeManager.setProtocolVersionDeadline, (getOldProtocolVersion(), 0)), + value: 0 + }); + calls[10] = Call({ + target: addresses.upgradeTimer, + // Double checking that the deadline has passed. + data: abi.encodeCall(GovernanceUpgradeTimer.checkDeadline, ()), + value: 0 + }); } function initializeConfig(string memory configPath) internal { @@ -572,7 +678,6 @@ contract EcosystemUpgrade is Script { config.contracts.genesisRoot = toml.readBytes32("$.contracts.genesis_root"); config.contracts.genesisRollupLeafIndex = toml.readUint("$.contracts.genesis_rollup_leaf_index"); config.contracts.genesisBatchCommitment = toml.readBytes32("$.contracts.genesis_batch_commitment"); - config.contracts.latestProtocolVersion = toml.readUint("$.contracts.latest_protocol_version"); config.contracts.recursionNodeLevelVkHash = toml.readBytes32("$.contracts.recursion_node_level_vk_hash"); config.contracts.recursionLeafLevelVkHash = toml.readBytes32("$.contracts.recursion_leaf_level_vk_hash"); config.contracts.recursionCircuitsSetVksHash = toml.readBytes32("$.contracts.recursion_circuits_set_vks_hash"); @@ -603,14 +708,13 @@ contract EcosystemUpgrade is Script { config.contracts.eraDiamondProxy = toml.readAddress("$.contracts.era_diamond_proxy"); config.contracts.legacyErc20BridgeAddress = toml.readAddress("$.contracts.legacy_erc20_bridge_address"); config.contracts.oldValidatorTimelock = toml.readAddress("$.contracts.old_validator_timelock"); - // FIXME: value stored there is incorrect at the moment, figure out the correct value + // TODO: value stored there is incorrect at the moment, figure out the correct value config.contracts.blobVersionedHashRetriever = toml.readAddress("$.contracts.blob_versioned_hash_retriever"); - config.contracts.l2BridgeProxyOwnerAddress = toml.readAddress("$.contracts.l2_bridge_proxy_owner_address"); - config.contracts.l2BridgedStandardERC20ProxyOwnerAddress = toml.readAddress( - "$.contracts.l2_bridged_standard_erc20_proxy_owner_address" - ); config.tokens.tokenWethAddress = toml.readAddress("$.tokens.token_weth_address"); + + // TODO: maybe receive the address from the config + cross check + config.ecosystemAdminAddress = Bridgehub(config.contracts.bridgehubProxyAddress).admin(); } function initializeGeneratedData() internal { @@ -620,73 +724,27 @@ contract EcosystemUpgrade is Script { function initializeExpectedL2Addresses() internal { address aliasedGovernance = AddressAliasHelper.applyL1ToL2Alias(config.ownerAddress); - address expectedL2ProxyAdminDeployer = Utils.getL2AddressViaCreate2Factory( - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readProxyAdminDeployerBytecode()), - abi.encode(aliasedGovernance) - ); - address expectedL2ProxyAdmin = L2ContractHelper.computeCreate2Address( - expectedL2ProxyAdminDeployer, - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readProxyAdminBytecode()), - keccak256(hex"") - ); - - address permanentRestrictionImpl = Utils.getL2AddressViaCreate2Factory( - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readPermanentRestrictionBytecode()), - // Note that for L2 deployments the L2AdminFactory is 0. - abi.encode(L2_BRIDGEHUB_ADDRESS, address(0)) - ); - - address permanentRestrictionProxy = Utils.getL2AddressViaCreate2Factory( - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readTransparentUpgradeableProxyBytecode()), - abi.encode( - permanentRestrictionImpl, - expectedL2ProxyAdmin, - abi.encodeCall(PermanentRestriction.initialize, (aliasedGovernance)) - ) - ); - - address[] memory requiredL2Restrictions = new address[](1); - requiredL2Restrictions[0] = permanentRestrictionProxy; - addresses.expectedL2Addresses = ExpectedL2Addresses({ expectedRollupL2DAValidator: Utils.getL2AddressViaCreate2Factory( bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readRollupL2DAValidatorBytecode()), + cachedBytecodeHashes.rollupL2DAValidatorBytecodeHash, hex"" ), expectedValidiumL2DAValidator: Utils.getL2AddressViaCreate2Factory( bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readValidiumL2DAValidatorBytecode()), - hex"" - ), - expectedL2GatewayUpgrade: Utils.getL2AddressViaCreate2Factory( - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readGatewayUpgradeBytecode()), + cachedBytecodeHashes.validiumL2DAValidatorBytecodeHash, hex"" ), l2SharedBridgeLegacyImpl: Utils.getL2AddressViaCreate2Factory( bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readL2LegacySharedBridgeBytecode()), + cachedBytecodeHashes.sharedL2LegacyBridgeBytecodeHash, hex"" ), l2BridgedStandardERC20Impl: Utils.getL2AddressViaCreate2Factory( bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readStandardERC20Bytecode()), + cachedBytecodeHashes.erc20StandardImplBytecodeHash, hex"" - ), - expectedL2ProxyAdminDeployer: expectedL2ProxyAdminDeployer, - expectedL2ProxyAdmin: expectedL2ProxyAdmin, - expectedL2AdminFactory: Utils.getL2AddressViaCreate2Factory( - bytes32(0), - L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readL2AdminFactoryBytecode()), - abi.encode(requiredL2Restrictions) - ), - expectedL2PermanentRestrictionImpl: permanentRestrictionImpl, - expectedL2PermanentRestrictionProxy: permanentRestrictionProxy + ) }); } @@ -713,6 +771,71 @@ contract EcosystemUpgrade is Script { addresses.create2Factory = contractAddress; } + function deployBytecodesSupplier() internal { + address contractAddress = deployViaCreate2(type(BytecodesSupplier).creationCode); + console.log("BytecodesSupplier deployed at:", contractAddress); + addresses.bytecodesSupplier = contractAddress; + } + + function getFullListOfFactoryDependencies() internal returns (bytes[] memory factoryDeps) { + bytes[] memory basicDependencies = SystemContractsProcessing.getBaseListOfDependencies(); + + // This upgrade will also require to publish: + // - L2GatewayUpgrade + // - new L2 shared bridge legacy implementation + // - new bridged erc20 token implementation + // + // Also, not strictly necessary, but better for consistency with the new chains: + // - UpgradeableBeacon + // - BeaconProxy + + bytes[] memory upgradeSpecificDependencies = new bytes[](8); + upgradeSpecificDependencies[0] = L2ContractsBytecodesLib.readGatewayUpgradeBytecode(); + upgradeSpecificDependencies[1] = L2ContractsBytecodesLib.readL2LegacySharedBridgeBytecode(); + upgradeSpecificDependencies[2] = L2ContractsBytecodesLib.readStandardERC20Bytecode(); + + upgradeSpecificDependencies[3] = L2ContractsBytecodesLib.readUpgradeableBeaconBytecode(); + upgradeSpecificDependencies[4] = L2ContractsBytecodesLib.readBeaconProxyBytecode(); + + // We do not know whether the chain will be a rollup or a validium, just in case, we'll deploy + // both of the validators. + upgradeSpecificDependencies[5] = L2ContractsBytecodesLib.readRollupL2DAValidatorBytecode(); + upgradeSpecificDependencies[6] = L2ContractsBytecodesLib.readValidiumL2DAValidatorBytecode(); + + upgradeSpecificDependencies[7] = L2ContractsBytecodesLib + .readTransparentUpgradeableProxyBytecodeFromSystemContracts(); + + cachedBytecodeHashes = CachedBytecodeHashes({ + sharedL2LegacyBridgeBytecodeHash: L2ContractHelper.hashL2Bytecode(upgradeSpecificDependencies[1]), + erc20StandardImplBytecodeHash: L2ContractHelper.hashL2Bytecode(upgradeSpecificDependencies[2]), + rollupL2DAValidatorBytecodeHash: L2ContractHelper.hashL2Bytecode(upgradeSpecificDependencies[5]), + validiumL2DAValidatorBytecodeHash: L2ContractHelper.hashL2Bytecode(upgradeSpecificDependencies[6]), + transparentUpgradableProxyBytecodeHash: L2ContractHelper.hashL2Bytecode(upgradeSpecificDependencies[7]) + }); + + factoryDeps = SystemContractsProcessing.mergeBytesArrays(basicDependencies, upgradeSpecificDependencies); + factoryDeps = SystemContractsProcessing.deduplicateBytecodes(factoryDeps); + } + + function publishBytecodes() internal { + bytes[] memory allDeps = getFullListOfFactoryDependencies(); + BytecodePublisher.publishBytecodesInBatches(BytecodesSupplier(addresses.bytecodesSupplier), allDeps); + + uint256[] memory factoryDeps = new uint256[](allDeps.length); + + require(factoryDeps.length <= 64, "Too many deps"); + + for (uint256 i = 0; i < allDeps.length; i++) { + factoryDeps[i] = uint256(L2ContractHelper.hashL2Bytecode(allDeps[i])); + } + + // Double check for consistency: + require(bytes32(factoryDeps[0]) == config.contracts.bootloaderHash, "bootloader hash factory dep mismatch"); + require(bytes32(factoryDeps[1]) == config.contracts.defaultAAHash, "default aa hash factory dep mismatch"); + + factoryDepsHashes = factoryDeps; + } + function deployVerifier() internal { bytes memory code; if (config.testnetVerifier) { @@ -746,34 +869,24 @@ contract EcosystemUpgrade is Script { } function deployDAValidators() internal { - address contractAddress = deployViaCreate2(Utils.readRollupDAValidatorBytecode()); - console.log("L1RollupDAValidator deployed at:", contractAddress); - addresses.daAddresses.l1RollupDAValidator = contractAddress; + vm.broadcast(msg.sender); + address rollupDAManager = address(new RollupDAManager()); + addresses.daAddresses.rollupDAManager = rollupDAManager; - contractAddress = deployViaCreate2(type(ValidiumL1DAValidator).creationCode); - console.log("L1ValidiumDAValidator deployed at:", contractAddress); - addresses.daAddresses.l1ValidiumDAValidator = contractAddress; - } + address rollupDAValidator = deployViaCreate2(Utils.readRollupDAValidatorBytecode()); + console.log("L1RollupDAValidator deployed at:", rollupDAValidator); + addresses.daAddresses.l1RollupDAValidator = rollupDAValidator; - function deployPermanentRollupRestriction() internal { - bytes memory bytecode = abi.encodePacked( - type(PermanentRestriction).creationCode, - abi.encode(config.contracts.bridgehubProxyAddress, addresses.expectedL2Addresses.expectedL2AdminFactory) - ); - address implementationAddress = deployViaCreate2(bytecode); + address validiumDAValidator = deployViaCreate2(type(ValidiumL1DAValidator).creationCode); + console.log("L1ValidiumDAValidator deployed at:", validiumDAValidator); + addresses.daAddresses.l1ValidiumDAValidator = validiumDAValidator; - bytes memory proxyBytecode = abi.encodePacked( - type(TransparentUpgradeableProxy).creationCode, - abi.encode( - implementationAddress, - config.contracts.transparentProxyAdmin, - abi.encodeCall(PermanentRestriction.initialize, (config.deployerAddress)) - ) + vm.broadcast(msg.sender); + RollupDAManager(rollupDAManager).updateDAPair( + address(rollupDAValidator), + addresses.expectedL2Addresses.expectedRollupL2DAValidator, + true ); - - address proxyAddress = deployViaCreate2(proxyBytecode); - addresses.permanentRollupRestriction = proxyAddress; - // FIXME: supply restrictions } function deployValidatorTimelock() internal { @@ -862,16 +975,20 @@ contract EcosystemUpgrade is Script { function deployChainTypeManagerContract() internal { deployStateTransitionDiamondFacets(); deployChainTypeManagerImplementation(); - // registerChainTypeManager(); } function deployStateTransitionDiamondFacets() internal { - address executorFacet = deployViaCreate2(type(ExecutorFacet).creationCode); + address executorFacet = deployViaCreate2( + abi.encodePacked(type(ExecutorFacet).creationCode, abi.encode(config.l1ChainId)) + ); console.log("ExecutorFacet deployed at:", executorFacet); addresses.stateTransition.executorFacet = executorFacet; address adminFacet = deployViaCreate2( - abi.encodePacked(type(AdminFacet).creationCode, abi.encode(config.l1ChainId)) + abi.encodePacked( + type(AdminFacet).creationCode, + abi.encode(config.l1ChainId, addresses.daAddresses.rollupDAManager) + ) ); console.log("AdminFacet deployed at:", adminFacet); addresses.stateTransition.adminFacet = adminFacet; @@ -963,10 +1080,11 @@ contract EcosystemUpgrade is Script { } function setL1LegacyBridge() internal { - vm.broadcast(msg.sender); + vm.startBroadcast(config.deployerAddress); L1AssetRouter(addresses.bridges.sharedBridgeProxy).setL1Erc20Bridge( L1ERC20Bridge(config.contracts.legacyErc20BridgeAddress) ); + vm.stopBroadcast(); } function deployErc20BridgeImplementation() internal { @@ -996,14 +1114,20 @@ contract EcosystemUpgrade is Script { } function deployBridgedTokenBeacon() internal { - bytes memory bytecode = abi.encodePacked( - type(UpgradeableBeacon).creationCode, - // solhint-disable-next-line func-named-parameters - abi.encode(addresses.bridges.bridgedStandardERC20Implementation) - ); + // bytes memory bytecode = abi.encodePacked( + // type(UpgradeableBeacon).creationCode, + // // solhint-disable-next-line func-named-parameters + // abi.encode(addresses.bridges.bridgedStandardERC20Implementation) + // ); + + // Note, that the `msg.sender` will be set as the owner. + // This means that we can not use a naive create2factory. It may be replaced + // with a more advanced one, but CREATE from a hot wallet is fine too. + vm.startBroadcast(msg.sender); UpgradeableBeacon beacon = new UpgradeableBeacon(addresses.bridges.bridgedStandardERC20Implementation); - address contractAddress = address(beacon); beacon.transferOwnership(config.ownerAddress); + vm.stopBroadcast(); + address contractAddress = address(beacon); console.log("BridgedTokenBeacon deployed at:", contractAddress); addresses.bridges.bridgedTokenBeacon = contractAddress; } @@ -1060,11 +1184,43 @@ contract EcosystemUpgrade is Script { addresses.transitionaryOwner = deployViaCreate2(bytecode); } + function deployGovernanceUpgradeTimer() internal { + // Needed for easy server testing, in reality it will be different + uint256 INITIAL_DELAY = 0; + + uint256 MAX_ADDITIONAL_DELAY = 2 weeks; + + // It may make sense to have a separate admin there, but + // using the same as bridgehub is just as fine. + address bridgehubAdmin = Bridgehub(config.contracts.bridgehubProxyAddress).admin(); + + bytes memory bytecode = abi.encodePacked( + type(GovernanceUpgradeTimer).creationCode, + abi.encode(INITIAL_DELAY, MAX_ADDITIONAL_DELAY, config.ownerAddress, config.ecosystemAdminAddress) + ); + + addresses.upgradeTimer = deployViaCreate2(bytecode); + } + + function deployL2WrappedBaseTokenStore() internal { + bytes memory bytecode = abi.encodePacked( + type(L2WrappedBaseTokenStore).creationCode, + abi.encode(config.ownerAddress, config.ecosystemAdminAddress) + ); + + addresses.l2WrappedBaseTokenStore = deployViaCreate2(bytecode); + } + function _moveGovernanceToOwner(address target) internal { Ownable2StepUpgradeable(target).transferOwnership(addresses.transitionaryOwner); TransitionaryOwner(addresses.transitionaryOwner).claimOwnershipAndGiveToGovernance(target); } + function _moveGovernanceToEcosystemAdmin(address target) internal { + // Is agile enough to accept ownership quickly `config.ecosystemAdminAddress` + Ownable2StepUpgradeable(target).transferOwnership(config.ecosystemAdminAddress); + } + function updateOwners() internal { vm.startBroadcast(msg.sender); @@ -1074,7 +1230,8 @@ contract EcosystemUpgrade is Script { _moveGovernanceToOwner(addresses.validatorTimelock); _moveGovernanceToOwner(addresses.bridges.sharedBridgeProxy); _moveGovernanceToOwner(addresses.bridgehub.ctmDeploymentTrackerProxy); - _moveGovernanceToOwner(addresses.permanentRollupRestriction); + console.log("hi"); + _moveGovernanceToOwner(addresses.daAddresses.rollupDAManager); vm.stopBroadcast(); console.log("Owners updated"); @@ -1256,11 +1413,6 @@ contract EcosystemUpgrade is Script { "expected_validium_l2_da_validator", addresses.expectedL2Addresses.expectedValidiumL2DAValidator ); - vm.serializeAddress( - "contracts_config", - "expected_l2_gateway_upgrade", - addresses.expectedL2Addresses.expectedL2GatewayUpgrade - ); vm.serializeBytes("contracts_config", "diamond_cut_data", generatedData.diamondCutData); string memory contractsConfig = vm.serializeBytes( @@ -1276,7 +1428,6 @@ contract EcosystemUpgrade is Script { "access_control_restriction_addr", addresses.accessControlRestrictionAddress ); - vm.serializeAddress("deployed_addresses", "permanent_rollup_restriction", addresses.permanentRollupRestriction); vm.serializeString("deployed_addresses", "bridgehub", bridgehub); vm.serializeString("deployed_addresses", "bridges", bridges); vm.serializeString("deployed_addresses", "state_transition", stateTransition); @@ -1291,6 +1442,7 @@ contract EcosystemUpgrade is Script { "validium_l1_da_validator_addr", addresses.daAddresses.l1ValidiumDAValidator ); + vm.serializeAddress("deployed_addresses", "l1_bytecodes_supplier_addr", addresses.bytecodesSupplier); string memory deployedAddresses = vm.serializeAddress( "deployed_addresses", @@ -1305,6 +1457,11 @@ contract EcosystemUpgrade is Script { vm.serializeAddress("root", "deployer_addr", config.deployerAddress); vm.serializeString("root", "deployed_addresses", deployedAddresses); vm.serializeString("root", "contracts_config", contractsConfig); + + vm.serializeBytes("root", "governance_stage1_calls", abi.encode(getStage1UpgradeCalls())); + vm.serializeBytes("root", "governance_stage2_calls", abi.encode(getStage2UpgradeCalls())); + vm.serializeBytes("root", "chain_upgrade_diamond_cut", abi.encode(getChainUpgradeInfo())); + string memory toml = vm.serializeAddress("root", "owner_address", config.ownerAddress); vm.writeToml(toml, outputPath); @@ -1335,14 +1492,22 @@ contract EcosystemUpgrade is Script { ), messageRootBytecodeHash: L2ContractHelper.hashL2Bytecode(L2ContractsBytecodesLib.readMessageRootBytecode()), l2SharedBridgeLegacyImpl: addresses.expectedL2Addresses.l2SharedBridgeLegacyImpl, - l2BridgedStandardERC20Impl: addresses.expectedL2Addresses.l2BridgedStandardERC20Impl, - l2BridgeProxyOwnerAddress: config.contracts.l2BridgeProxyOwnerAddress, - l2BridgedStandardERC20ProxyOwnerAddress: config.contracts.l2BridgedStandardERC20ProxyOwnerAddress + l2BridgedStandardERC20Impl: addresses.expectedL2Addresses.l2BridgedStandardERC20Impl }); return abi.encode(data); } + function mergeCalls(Call[] memory a, Call[] memory b) internal pure returns (Call[] memory result) { + result = new Call[](a.length + b.length); + for (uint256 i = 0; i < a.length; i++) { + result[i] = a[i]; + } + for (uint256 i = 0; i < b.length; i++) { + result[a.length + i] = b[i]; + } + } + // add this to be excluded from coverage report function test() internal {} } diff --git a/l1-contracts/deploy-scripts/upgrade/FinalizeUpgrade.s.sol b/l1-contracts/deploy-scripts/upgrade/FinalizeUpgrade.s.sol new file mode 100644 index 000000000..00a730194 --- /dev/null +++ b/l1-contracts/deploy-scripts/upgrade/FinalizeUpgrade.s.sol @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +// solhint-disable no-console, gas-custom-errors + +import {Script, console2 as console} from "forge-std/Script.sol"; +import {stdToml} from "forge-std/StdToml.sol"; +import {Utils, L2_BRIDGEHUB_ADDRESS, L2_ASSET_ROUTER_ADDRESS, L2_NATIVE_TOKEN_VAULT_ADDRESS, L2_MESSAGE_ROOT_ADDRESS} from "../Utils.sol"; +import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; +import {L2ContractsBytecodesLib} from "../L2ContractsBytecodesLib.sol"; +import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; +import {IAdmin} from "contracts/state-transition/chain-interfaces/IAdmin.sol"; +import {AccessControlRestriction} from "contracts/governance/AccessControlRestriction.sol"; +import {ChainAdmin} from "contracts/governance/ChainAdmin.sol"; +import {Call} from "contracts/governance/Common.sol"; +import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; + +import {Bridgehub} from "contracts/bridgehub/Bridgehub.sol"; +import {L1NativeTokenVault} from "contracts/bridge/ntv/L1NativeTokenVault.sol"; +import {ETH_TOKEN_ADDRESS} from "contracts/common/Config.sol"; +import {IERC20} from "@openzeppelin/contracts-v4/token/ERC20/IERC20.sol"; + +/// @notice Script intended to help us finalize the governance upgrade +contract FinalizeUpgrade is Script { + using stdToml for string; + + string constant FINALIZE_UPGRADE_CONFIG_PATH = "/script-config/gateway-finalize-upgrade.toml"; + + struct Config { + address bridgehub; + address l1NativeTokenVault; + } + + Config config; + + function initChains(address bridgehub, uint256[] calldata chains) external { + // TODO: we can optimize it to be done in mutlicall, does not matter + + for (uint256 i = 0; i < chains.length; ++i) { + Bridgehub bh = Bridgehub(bridgehub); + + if (bh.baseTokenAssetId(chains[i]) == bytes32(0)) { + vm.broadcast(); + Bridgehub(bridgehub).setLegacyBaseTokenAssetId(chains[i]); + } + + if (bh.getZKChain(chains[i]) == address(0)) { + vm.broadcast(); + Bridgehub(bridgehub).setLegacyChainAddress(chains[i]); + } + } + } + + function initTokens( + address payable l1NativeTokenVault, + address[] calldata tokens, + uint256[] calldata chains + ) external { + // TODO: we can optimize it to be done in mutlicall, does not matter + + L1NativeTokenVault vault = L1NativeTokenVault(l1NativeTokenVault); + address nullifier = address(vault.L1_NULLIFIER()); + + for (uint256 i = 0; i < tokens.length; i++) { + uint256 tokenBalance; + if (tokens[i] != ETH_TOKEN_ADDRESS) { + uint256 balance = IERC20(tokens[i]).balanceOf(nullifier); + if (balance != 0) { + vm.broadcast(); + vault.transferFundsFromSharedBridge(tokens[i]); + } + + vm.broadcast(); + vault.registerToken(tokens[i]); + } else { + vm.broadcast(); + vault.registerEthToken(); + } + + // TODO: we need to reduce complexity of this one + for (uint256 j = 0; j < chains.length; j++) { + vm.broadcast(); + vault.updateChainBalancesFromSharedBridge(tokens[i], chains[j]); + } + } + } +} diff --git a/l1-contracts/deploy-scripts/upgrade/SystemContractsProcessing.s.sol b/l1-contracts/deploy-scripts/upgrade/SystemContractsProcessing.s.sol new file mode 100644 index 000000000..38475ad02 --- /dev/null +++ b/l1-contracts/deploy-scripts/upgrade/SystemContractsProcessing.s.sol @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import {Script, console2 as console} from "forge-std/Script.sol"; +import {Utils, L2_WETH_IMPL_ADDRESS, L2_BRIDGEHUB_ADDRESS, L2_ASSET_ROUTER_ADDRESS, L2_NATIVE_TOKEN_VAULT_ADDRESS, L2_MESSAGE_ROOT_ADDRESS} from "../Utils.sol"; +import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; +import {L2ContractsBytecodesLib} from "../L2ContractsBytecodesLib.sol"; +import {IL2ContractDeployer} from "contracts/common/interfaces/IL2ContractDeployer.sol"; + +// solhint-disable no-console, gas-custom-errors + +/// @notice Enum representing the programming language of the contract +enum Language { + Solidity, + Yul +} + +/// @notice Struct representing a system contract's details +struct SystemContract { + address addr; // Contract address + string codeName; // Name of the contract code + Language lang; // Programming language used +} + +/// @dev The number of built-in contracts that reside within the "system-contracts" folder +uint256 constant SYSTEM_CONTRACTS_COUNT = 27; +/// @dev The number of built-in contracts that reside within the `l1-contracts` folder +uint256 constant OTHER_BUILT_IN_CONTRACTS_COUNT = 5; + +library SystemContractsProcessing { + /// @notice Retrieves the entire list of system contracts as a memory array + /// @dev Note that it does not include all built-in contracts. Rather all those + /// that are based in the `system-contracts` folder. + /// @return An array of SystemContract structs containing all system contracts + function getSystemContracts() public pure returns (SystemContract[] memory) { + // Initialize the in-memory array + SystemContract[] memory systemContracts = new SystemContract[](SYSTEM_CONTRACTS_COUNT); + + // Populate the array with system contract details + // Populate the array with system contract details using named parameters + systemContracts[0] = SystemContract({ + addr: 0x0000000000000000000000000000000000000000, + codeName: "EmptyContract", + lang: Language.Solidity + }); + + systemContracts[1] = SystemContract({ + addr: 0x0000000000000000000000000000000000000001, + codeName: "Ecrecover", + lang: Language.Yul + }); + + systemContracts[2] = SystemContract({ + addr: 0x0000000000000000000000000000000000000002, + codeName: "SHA256", + lang: Language.Yul + }); + + systemContracts[3] = SystemContract({ + addr: 0x0000000000000000000000000000000000000006, + codeName: "EcAdd", + lang: Language.Yul + }); + + systemContracts[4] = SystemContract({ + addr: 0x0000000000000000000000000000000000000007, + codeName: "EcMul", + lang: Language.Yul + }); + + systemContracts[5] = SystemContract({ + addr: 0x0000000000000000000000000000000000000008, + codeName: "EcPairing", + lang: Language.Yul + }); + + systemContracts[6] = SystemContract({ + addr: 0x0000000000000000000000000000000000008001, + codeName: "EmptyContract", + lang: Language.Solidity + }); + + systemContracts[7] = SystemContract({ + addr: 0x0000000000000000000000000000000000008002, + codeName: "AccountCodeStorage", + lang: Language.Solidity + }); + + systemContracts[8] = SystemContract({ + addr: 0x0000000000000000000000000000000000008003, + codeName: "NonceHolder", + lang: Language.Solidity + }); + + systemContracts[9] = SystemContract({ + addr: 0x0000000000000000000000000000000000008004, + codeName: "KnownCodesStorage", + lang: Language.Solidity + }); + + systemContracts[10] = SystemContract({ + addr: 0x0000000000000000000000000000000000008005, + codeName: "ImmutableSimulator", + lang: Language.Solidity + }); + + systemContracts[11] = SystemContract({ + addr: 0x0000000000000000000000000000000000008006, + codeName: "ContractDeployer", + lang: Language.Solidity + }); + + systemContracts[12] = SystemContract({ + addr: 0x0000000000000000000000000000000000008008, + codeName: "L1Messenger", + lang: Language.Solidity + }); + + systemContracts[13] = SystemContract({ + addr: 0x0000000000000000000000000000000000008009, + codeName: "MsgValueSimulator", + lang: Language.Solidity + }); + + systemContracts[14] = SystemContract({ + addr: 0x000000000000000000000000000000000000800A, + codeName: "L2BaseToken", + lang: Language.Solidity + }); + + systemContracts[15] = SystemContract({ + addr: 0x000000000000000000000000000000000000800B, + codeName: "SystemContext", + lang: Language.Solidity + }); + + systemContracts[16] = SystemContract({ + addr: 0x000000000000000000000000000000000000800c, + codeName: "BootloaderUtilities", + lang: Language.Solidity + }); + + systemContracts[17] = SystemContract({ + addr: 0x000000000000000000000000000000000000800d, + codeName: "EventWriter", + lang: Language.Yul + }); + + systemContracts[18] = SystemContract({ + addr: 0x000000000000000000000000000000000000800E, + codeName: "Compressor", + lang: Language.Solidity + }); + + systemContracts[19] = SystemContract({ + addr: 0x000000000000000000000000000000000000800f, + codeName: "ComplexUpgrader", + lang: Language.Solidity + }); + + systemContracts[20] = SystemContract({ + addr: 0x0000000000000000000000000000000000008010, + codeName: "Keccak256", + lang: Language.Yul + }); + + systemContracts[21] = SystemContract({ + addr: 0x0000000000000000000000000000000000008012, + codeName: "CodeOracle", + lang: Language.Yul + }); + + systemContracts[22] = SystemContract({ + addr: 0x0000000000000000000000000000000000000100, + codeName: "P256Verify", + lang: Language.Yul + }); + + systemContracts[23] = SystemContract({ + addr: 0x0000000000000000000000000000000000008011, + codeName: "PubdataChunkPublisher", + lang: Language.Solidity + }); + + systemContracts[24] = SystemContract({ + addr: 0x0000000000000000000000000000000000010000, + codeName: "Create2Factory", + lang: Language.Solidity + }); + systemContracts[25] = SystemContract({ + addr: 0x0000000000000000000000000000000000010001, + codeName: "L2GenesisUpgrade", + lang: Language.Solidity + }); + systemContracts[26] = SystemContract({ + addr: 0x0000000000000000000000000000000000010006, + codeName: "SloadContract", + lang: Language.Solidity + }); + return systemContracts; + } + + /// @notice Deduplicates the array of bytecodes. + function deduplicateBytecodes(bytes[] memory input) internal returns (bytes[] memory output) { + // A more efficient way would be to sort + deduplicate, but + // there is no built-in sorting in Solidity + this function should be only + // used in scripts, so ineffiency is fine. + // We'll do it on O(N^2) + + // In O(N^2) we'll mark duplicated hashes as zeroes. + bytes32[] memory hashes = new bytes32[](input.length); + for (uint256 i = 0; i < input.length; i++) { + hashes[i] = keccak256(input[i]); + } + + uint256 toInclude = 0; + + for (uint256 i = 0; i < hashes.length; i++) { + if (hashes[i] != bytes32(0)) { + toInclude += 1; + } + + for (uint j = i + 1; j < hashes.length; j++) { + if (hashes[i] == hashes[j]) { + hashes[j] = bytes32(0); + } + } + } + + output = new bytes[](toInclude); + uint256 included = 0; + for (uint256 i = 0; i < input.length; i++) { + if (hashes[i] != bytes32(0)) { + output[included] = input[i]; + ++included; + } + } + + // Sanity check + require(included == toInclude, "Internal error: included != toInclude"); + } + + function getSystemContractsBytecodes() internal returns (bytes[] memory result) { + result = new bytes[](SYSTEM_CONTRACTS_COUNT); + + SystemContract[] memory systemContracts = getSystemContracts(); + for (uint256 i = 0; i < SYSTEM_CONTRACTS_COUNT; i++) { + if (systemContracts[i].lang == Language.Solidity) { + result[i] = Utils.readSystemContractsBytecode(systemContracts[i].codeName); + } else { + result[i] = Utils.readPrecompileBytecode(systemContracts[i].codeName); + } + } + } + + function getSystemContractsForceDeployments() + internal + returns (IL2ContractDeployer.ForceDeployment[] memory forceDeployments) + { + forceDeployments = new IL2ContractDeployer.ForceDeployment[](SYSTEM_CONTRACTS_COUNT); + + SystemContract[] memory systemContracts = getSystemContracts(); + bytes[] memory bytecodes = getSystemContractsBytecodes(); + for (uint256 i = 0; i < SYSTEM_CONTRACTS_COUNT; i++) { + forceDeployments[i] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[i]), + newAddress: systemContracts[i].addr, + callConstructor: false, + value: 0, + input: "" + }); + } + } + + function getOtherContractsBytecodes() internal view returns (bytes[] memory result) { + result = new bytes[](OTHER_BUILT_IN_CONTRACTS_COUNT); + + result[0] = L2ContractsBytecodesLib.readBridgehubBytecode(); + result[1] = L2ContractsBytecodesLib.readL2AssetRouterBytecode(); + result[2] = L2ContractsBytecodesLib.readL2NativeTokenVaultBytecode(); + result[3] = L2ContractsBytecodesLib.readMessageRootBytecode(); + result[4] = L2ContractsBytecodesLib.readL2WrappedBaseToken(); + } + + /// Note, that while proper initialization may require multiple steps, + /// those will be conducted inside a specialized upgrade. We still provide + /// these force deployments here for the sake of consistency + function getOtherBuiltinForceDeployments() + internal + returns (IL2ContractDeployer.ForceDeployment[] memory forceDeployments) + { + forceDeployments = new IL2ContractDeployer.ForceDeployment[](OTHER_BUILT_IN_CONTRACTS_COUNT); + bytes[] memory bytecodes = getOtherContractsBytecodes(); + + forceDeployments[0] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[0]), + newAddress: L2_BRIDGEHUB_ADDRESS, + callConstructor: false, + value: 0, + input: "" + }); + forceDeployments[1] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[1]), + newAddress: L2_ASSET_ROUTER_ADDRESS, + callConstructor: false, + value: 0, + input: "" + }); + forceDeployments[2] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[2]), + newAddress: L2_NATIVE_TOKEN_VAULT_ADDRESS, + callConstructor: false, + value: 0, + input: "" + }); + forceDeployments[3] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[3]), + newAddress: L2_MESSAGE_ROOT_ADDRESS, + callConstructor: false, + value: 0, + input: "" + }); + forceDeployments[4] = IL2ContractDeployer.ForceDeployment({ + bytecodeHash: L2ContractHelper.hashL2Bytecode(bytecodes[4]), + newAddress: L2_WETH_IMPL_ADDRESS, + callConstructor: false, + value: 0, + input: "" + }); + } + + function forceDeploymentsToHashes( + IL2ContractDeployer.ForceDeployment[] memory baseForceDeployments + ) internal returns (bytes32[] memory hashes) { + hashes = new bytes32[](baseForceDeployments.length); + for (uint256 i = 0; i < baseForceDeployments.length; i++) { + hashes[i] = baseForceDeployments[i].bytecodeHash; + } + } + + function mergeForceDeployments( + IL2ContractDeployer.ForceDeployment[] memory left, + IL2ContractDeployer.ForceDeployment[] memory right + ) internal returns (IL2ContractDeployer.ForceDeployment[] memory forceDeployments) { + forceDeployments = new IL2ContractDeployer.ForceDeployment[](left.length + right.length); + for (uint256 i = 0; i < left.length; i++) { + forceDeployments[i] = left[i]; + } + for (uint256 i = 0; i < right.length; i++) { + forceDeployments[left.length + i] = right[i]; + } + } + + function mergeBytesArrays(bytes[] memory left, bytes[] memory right) internal returns (bytes[] memory result) { + result = new bytes[](left.length + right.length); + for (uint256 i = 0; i < left.length; i++) { + result[i] = left[i]; + } + for (uint256 i = 0; i < right.length; i++) { + result[left.length + i] = right[i]; + } + } + + function getBaseForceDeployments() + internal + returns (IL2ContractDeployer.ForceDeployment[] memory forceDeployments) + { + IL2ContractDeployer.ForceDeployment[] memory otherForceDeployments = getOtherBuiltinForceDeployments(); + IL2ContractDeployer.ForceDeployment[] memory systemForceDeployments = getSystemContractsForceDeployments(); + + forceDeployments = mergeForceDeployments(systemForceDeployments, otherForceDeployments); + } + + function getBaseListOfDependencies() internal returns (bytes[] memory factoryDeps) { + // Note that it is *important* that these go first in this exact order, + // since the server will rely on it. + bytes[] memory bootloaderAndDefaultAABytecodes = new bytes[](2); + bootloaderAndDefaultAABytecodes[0] = Utils.getBatchBootloaderBytecodeHash(); + bootloaderAndDefaultAABytecodes[1] = Utils.readSystemContractsBytecode("DefaultAccount"); + + bytes[] memory systemBytecodes = getSystemContractsBytecodes(); + bytes[] memory otherBytecodes = getOtherContractsBytecodes(); + + factoryDeps = mergeBytesArrays( + mergeBytesArrays(bootloaderAndDefaultAABytecodes, systemBytecodes), + otherBytecodes + ); + } +} diff --git a/l1-contracts/foundry.toml b/l1-contracts/foundry.toml index b4dc2ca3b..f91b81c02 100644 --- a/l1-contracts/foundry.toml +++ b/l1-contracts/foundry.toml @@ -9,7 +9,9 @@ solc_version = "0.8.24" evm_version = "cancun" fs_permissions = [ { access = "read", path = "../system-contracts/bootloader/build/artifacts" }, - { access = "read", path = "../system-contracts/artifacts-zk/contracts-preprocessed" }, + { access = "read", path = "../system-contracts/artifacts-zk/" }, + { access = "read", path = "../system-contracts/contracts-preprocessed/precompiles/artifacts" }, + { access = "read", path = "../system-contracts/contracts-preprocessed/artifacts" }, { access = "read", path = "../l2-contracts/artifacts-zk/" }, { access = "read", path = "../l1-contracts/artifacts-zk/" }, { access = "read", path = "../da-contracts/" }, diff --git a/l1-contracts/package.json b/l1-contracts/package.json index 8a6896e86..a79300947 100644 --- a/l1-contracts/package.json +++ b/l1-contracts/package.json @@ -60,7 +60,7 @@ "test": "yarn workspace da-contracts build && hardhat test test/unit_tests/*.spec.ts --network hardhat", "test:foundry": "forge test --ffi --match-path 'test/foundry/l1/*' --no-match-test 'test_MainnetFork'", "test:zkfoundry": "forge script --sig 0x2dd0ebe3 DeployL1Script --ffi && forge test --zksync --match-path 'test/foundry/l2/*'", - "test:mainnet-upgrade-fork": "forge test --match-test test_MainnetFork --ffi --rpc-url $INFURA_MAINNET", + "test:mainnet-upgrade-fork": "forge test --match-test test_MainnetFork --ffi --rpc-url $INFURA_MAINNET --gas-limit 2000000000", "test:fork": "TEST_CONTRACTS_FORK=1 yarn run hardhat test test/unit_tests/*.fork.ts --network hardhat", "coverage:foundry": "forge coverage --ffi --match-path 'test/foundry/l1/*' --no-match-coverage 'contracts/(bridge/.*L2.*\\.sol|governance/L2AdminFactory\\.sol)' --no-match-test test_MainnetFork", "deploy-no-build": "ts-node scripts/deploy.ts", @@ -83,7 +83,8 @@ "upgrade-consistency-checker": "ts-node scripts/upgrade-consistency-checker.ts", "governance-accept-ownership": "ts-node scripts/governance-accept-ownership.ts", "sync-layer": "ts-node scripts/sync-layer.ts", - "size": "hardhat size-contracts" + "size": "hardhat size-contracts", + "errors-lint": "ts-node scripts/errors-lint.ts" }, "dependencies": { "dotenv": "^16.0.3", diff --git a/l1-contracts/script-config/artifacts/BeaconProxy.json b/l1-contracts/script-config/artifacts/BeaconProxy.json deleted file mode 100644 index 258780377..000000000 --- a/l1-contracts/script-config/artifacts/BeaconProxy.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "_format": "hh-zksolc-artifact-1", - "contractName": "BeaconProxy", - "sourceName": "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol", - "abi": [ - { - "inputs": [ - { - "internalType": "address", - "name": "beacon", - "type": "address" - }, - { - "internalType": "bytes", - "name": "data", - "type": "bytes" - } - ], - "stateMutability": "payable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "previousAdmin", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "newAdmin", - "type": "address" - } - ], - "name": "AdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "beacon", - "type": "address" - } - ], - "name": "BeaconUpgraded", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "implementation", - "type": "address" - } - ], - "name": "Upgraded", - "type": "event" - }, - { - "stateMutability": "payable", - "type": "fallback" - }, - { - "stateMutability": "payable", - "type": "receive" - } - ], - "bytecode": "0x0004000000000002000700000000000200000000030100190000006003300270000001020030019d0000010203300197000300000031035500020000000103550000008008000039000000400080043f00000001022001900000001c0000c13d000000000131034f0000010d02000041000000000202041a0000010b04000041000000800040043f00000106022001970000000004000414000000000303004b000000250000c13d000000040320008c000000ab0000c13d0000000103000031000000200230008c00000000040300190000002004008039000000d60000013d0000010302300041000001040220009c0000002c0000213d0000011d0100004100000000001004350000004101000039000000040010043f0000011e010000410000040400010430000000040320008c000001160000c13d0000000103000031000000200230008c00000000040300190000002004008039000001410000013d0000009f023000390000010502200197000000400020043f0000001f0230018f00000005043002720000003b0000613d00000000050000190000000506500210000000000761034f000000000707043b000000800660003900000000007604350000000105500039000000000645004b000000330000413d000000000502004b0000004a0000613d0000000504400210000000000141034f00000003022002100000008004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f00000000001404350000003f0130008c0000014a0000a13d000000800a00043d0000010601a0009c0000014a0000213d000000a00200043d000001070120009c0000014a0000213d0000001f012000390000010804000041000000000531004b000000000500001900000000050480190000010801100197000000000601004b0000000004008019000001080110009c000000000405c019000000000104004b0000014a0000c13d00000080012000390000000001010433000001070410009c0000001f0000213d0000003f04100039000000200700008a000000000474016f000000400900043d0000000004490019000000000594004b00000000050000190000000105004039000001070640009c0000001f0000213d00000001055001900000001f0000c13d0000008003300039000000400040043f0000000006190436000000a0022000390000000004210019000000000334004b0000014a0000213d000600000009001d000500000007001d000400000008001d000000000301004b000000820000613d000000000300001900000000046300190000000005230019000000000505043300000000005404350000002003300039000000000413004b0000007b0000413d000300000006001d000000000116001900000000000104350000010901000041000000000010043900070000000a001d0000000400a0044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000400a00043d000000000101043b000000000101004b000002200000c13d0000006401a000390000011b0200004100000000002104350000004401a000390000011c0200004100000000002104350000002401a0003900000025020000390000000000210435000001150100004100000000001a04350000000401a000390000002002000039000000000021043500000102010000410000010202a0009c000000000a0180190000004001a002100000011a011001c700000404000104300000010201000041000001020340009c0000000004018019000000c0014002100000011f011001c7040203f80000040f000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000000c30000613d00000000070000190000000508700210000000000981034f000000000909043b000000800880003900000000009804350000000107700039000000000867004b000000bb0000413d000000000705004b000000d20000613d0000000506600210000000000761034f00000003055002100000008006600039000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f000300000001035500000001022001900000014c0000613d0000009f02400039000000e00220018f000000400020043f000000200230008c0000014a0000413d000000800200043d000001060420009c0000014a0000213d000000020500036700000000040000310000001f0740018f0000000506400272000000eb0000613d00000000080000190000000509800210000000000a95034f000000000a0a043b0000000000a904350000000108800039000000000968004b000000e40000413d000000000807004b000000f90000613d00000003077002100000000506600210000000000806043300000000087801cf000000000878022f000000000565034f000000000505043b0000010007700089000000000575022f00000000057501cf000000000585019f00000000005604350000000005000414000000040620008c000001c40000c13d0000001f0430018f0000000502300272000001070000613d00000000050000190000000506500210000000000761034f000000000707043b00000000007604350000000105500039000000000625004b000001000000413d000000000504004b000001ed0000613d00000003044002100000000502200210000000000502043300000000054501cf000000000545022f000000000121034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000151019f0000000000120435000001ed0000013d0000010201000041000001020340009c0000000004018019000000c0014002100000011f011001c7040203f80000040f000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f00000005064002720000012e0000613d00000000070000190000000508700210000000000981034f000000000909043b000000800880003900000000009804350000000107700039000000000867004b000001260000413d000000000705004b0000013d0000613d0000000506600210000000000761034f00000003055002100000008006600039000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000001690000613d0000001f02400039000000600220018f00000080022001bf000000400020043f000000200230008c0000014a0000413d000000800200043d000001060420009c0000018c0000a13d00000000010000190000040400010430000000400200043d0000001f0430018f0000000505300272000001590000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000001510000413d000000000604004b000001680000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d000000400200043d0000001f0430018f0000000505300272000001760000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000016e0000413d000000000604004b000001850000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000010201000041000001020420009c000000000201801900000040012002100000006002300210000000000121019f0000040400010430000000020500036700000000040000310000001f0740018f0000000506400272000001990000613d00000000080000190000000509800210000000000a95034f000000000a0a043b0000000000a904350000000108800039000000000968004b000001920000413d000000000807004b000001a70000613d00000003077002100000000506600210000000000806043300000000087801cf000000000878022f000000000565034f000000000505043b0000010007700089000000000575022f00000000057501cf000000000585019f00000000005604350000000005000414000000040620008c000001ee0000c13d0000001f0430018f0000000502300272000001b50000613d00000000050000190000000506500210000000000761034f000000000707043b00000000007604350000000105500039000000000625004b000001ae0000413d000000000504004b000002170000613d00000003044002100000000502200210000000000502043300000000054501cf000000000545022f000000000121034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000151019f0000000000120435000002170000013d0000010201000041000001020350009c0000000005018019000001020340009c00000000040180190000006001400210000000c003500210000000000113019f040203fd0000040f0003000000010355000000000301001900000060033002700000001f0430018f000101020030019d00000102033001970000000505300272000001dd0000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000001d60000413d000000000604004b000001eb0000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f000000000015043500000001012001900000021c0000613d000002170000013d0000010201000041000001020350009c0000000005018019000001020340009c00000000040180190000006001400210000000c003500210000000000113019f040203fd0000040f0003000000010355000000000301001900000060033002700000001f0430018f000101020030019d00000102033001970000000505300272000002070000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000002000000413d000000000604004b000002150000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f000000000015043500000001012001900000021e0000613d0000010201000041000001020230009c00000000030180190000006001300210000004030001042e00000060013002100000040400010430000000600130021000000404000104300000010b0100004100000000001a0435000000000100041400000007020000290000010602200197000000040320008c000700000002001d0000022d0000c13d0000000103000031000000200130008c000000000403001900000020040080390000025e0000013d0000010204000041000001020310009c00000000010480190000010203a0009c00000000040a40190000004003400210000000c001100210000000000131019f0000010c011001c700020000000a001d040203f80000040f000000020a000029000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f00000005064002720000024b0000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000002430000413d000000000705004b0000025a0000613d0000000506600210000000000761034f00000000066a00190000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000002950000613d0000001f01400039000000600210018f0000000001a20019000000000221004b00000000020000190000000102004039000001070410009c0000001f0000213d00000001022001900000001f0000c13d000000400010043f000000200130008c0000014a0000413d00000000010a0433000001060210009c0000014a0000213d00000109020000410000000000200439000000040010044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000400200043d000200000002001d000000000101043b000000000101004b000002b20000c13d0000000203000029000000640130003900000118020000410000000000210435000000440130003900000119020000410000000000210435000000240130003900000030020000390000000000210435000001150100004100000000001304350000000401300039000000200200003900000000002104350000010201000041000001020230009c000000000301801900000040013002100000011a011001c70000040400010430000000400200043d0000001f0430018f0000000505300272000002a20000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000029a0000413d000000000604004b000001850000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d0000010d01000041000000000201041a0000010e022001970000000705000029000000000252019f000000000021041b00000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010f011001c70000800d0200003900000002030000390000011004000041040203f30000040f000000010120019000000006010000290000014a0000613d0000000001010433000000000101004b000002cd0000c13d0000002001000039000001000010044300000120000004430000011701000041000004030001042e0000010b010000410000000202000029000000000012043500000000010004140000000702000029000000040220008c000002d90000c13d0000000103000031000000200130008c000000000403001900000020040080390000030b0000013d0000010202000041000001020310009c00000000010280190000000204000029000001020340009c00000000020440190000004002200210000000c001100210000000000121019f0000010c011001c70000000702000029040203f80000040f000000020a000029000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000002f80000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000002f00000413d000000000705004b000003070000613d0000000506600210000000000761034f00000002066000290000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000003380000613d0000001f01400039000000600110018f0000000202100029000000000112004b00000000010000190000000101004039000700000002001d000001070220009c00000006040000290000001f0000213d00000001011001900000001f0000c13d0000000701000029000000400010043f000000200130008c0000014a0000413d00000002010000290000000001010433000200000001001d000001060110009c0000014a0000213d0000000701000029000001110110009c0000001f0000213d00000007050000290000006001500039000000400010043f000000400150003900000112020000410000000000210435000000270100003900000000021504360000011301000041000100000002001d0000000000120435000000000204043300000000010004140000000204000029000000040440008c000003550000c13d0000000102000039000001070130009c00000005050000290000001f0000213d0000036d0000013d000000400200043d0000001f0430018f0000000505300272000003450000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000033d0000413d000000000604004b000003540000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d00000102030000410000000305000029000001020450009c00000000050380190000004004500210000001020520009c00000000020380190000006002200210000000000242019f000001020410009c0000000001038019000000c001100210000000000121019f0000000202000029040203fd0000040f0000006004000039000000010220018f00030000000103550000006001100270000101020010019d000001020310019800000004090000290000000505000029000003960000613d0000003f01300039000000000151016f000000400400043d0000000001140019000000000541004b00000000050000190000000105004039000001070610009c0000001f0000213d00000001055001900000001f0000c13d000000400010043f0000001f0130018f000000000934043600000003050003670000000503300272000003870000613d000000000600001900000005076002100000000008790019000000000775034f000000000707043b00000000007804350000000106600039000000000736004b0000037f0000413d000000000601004b000003960000613d0000000503300210000000000535034f00000000033900190000000301100210000000000603043300000000061601cf000000000616022f000000000505043b0000010001100089000000000515022f00000000011501cf000000000161019f00000000001304350000000001040433000000000202004b000003b60000c13d000000000201004b000003dc0000c13d000000400400043d000600000004001d0000011501000041000000000014043500000004014000390000002002000039000000000021043500000007010000290000000003010433000700000003001d0000002401400039000000000031043500000044024000390000000101000029040203e50000040f00000007010000290000001f01100039000000050110017f00000044011000390000010202000041000001020310009c00000000010280190000000604000029000001020340009c00000000040280190000004002400210000003e20000013d000000000101004b000002c80000c13d000001090100004100000000001004390000000201000029000000040010044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000000101043b000000000101004b000002c80000c13d000000400100043d00000044021000390000011403000041000000000032043500000024021000390000001d030000390000000000320435000001150200004100000000002104350000000402100039000000200300003900000000003204350000010202000041000001020310009c0000000001028019000000400110021000000116011001c70000040400010430000000000001042f0000010202000041000001020310009c0000000001028019000001020390009c000000000902801900000040029002100000006001100210000000000121019f0000040400010430000000000403004b000003ef0000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000003e80000413d00000000012300190000000000010435000000000001042d000000000001042f000003f6002104210000000102000039000000000001042d0000000002000019000000000001042d000003fb002104230000000102000039000000000001042d0000000002000019000000000001042d00000400002104250000000102000039000000000001042d0000000002000019000000000001042d0000040200000432000004030001042e000004040001043000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000009fffffffffffffffffffffffffffffffffffffffffffffffff000000000000007f00000000000000000000000000000000000000000000000000000001ffffffe0000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000ffffffffffffffff80000000000000000000000000000000000000000000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b8302000002000000000000000000000000000000240000000000000000000000005c60da1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000a3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50ffffffffffffffffffffffff000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e000000000000000000000000000000000000000000000000ffffffffffffff9f206661696c656400000000000000000000000000000000000000000000000000416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000008c379a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000020000000000000000000000000000004000000100000000000000000073206e6f74206120636f6e747261637400000000000000000000000000000000455243313936373a20626561636f6e20696d706c656d656e746174696f6e206900000000000000000000000000000000000000840000000000000000000000007472616374000000000000000000000000000000000000000000000000000000455243313936373a206e657720626561636f6e206973206e6f74206120636f6e4e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000000000000000000000000000000000000000000004000000800000000000000000d32177e88b033622e0bc848f24ab73d0795ed87730981120fcdf94fbc134fa5d", - "deployedBytecode": "0x0004000000000002000700000000000200000000030100190000006003300270000001020030019d0000010203300197000300000031035500020000000103550000008008000039000000400080043f00000001022001900000001c0000c13d000000000131034f0000010d02000041000000000202041a0000010b04000041000000800040043f00000106022001970000000004000414000000000303004b000000250000c13d000000040320008c000000ab0000c13d0000000103000031000000200230008c00000000040300190000002004008039000000d60000013d0000010302300041000001040220009c0000002c0000213d0000011d0100004100000000001004350000004101000039000000040010043f0000011e010000410000040400010430000000040320008c000001160000c13d0000000103000031000000200230008c00000000040300190000002004008039000001410000013d0000009f023000390000010502200197000000400020043f0000001f0230018f00000005043002720000003b0000613d00000000050000190000000506500210000000000761034f000000000707043b000000800660003900000000007604350000000105500039000000000645004b000000330000413d000000000502004b0000004a0000613d0000000504400210000000000141034f00000003022002100000008004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f00000000001404350000003f0130008c0000014a0000a13d000000800a00043d0000010601a0009c0000014a0000213d000000a00200043d000001070120009c0000014a0000213d0000001f012000390000010804000041000000000531004b000000000500001900000000050480190000010801100197000000000601004b0000000004008019000001080110009c000000000405c019000000000104004b0000014a0000c13d00000080012000390000000001010433000001070410009c0000001f0000213d0000003f04100039000000200700008a000000000474016f000000400900043d0000000004490019000000000594004b00000000050000190000000105004039000001070640009c0000001f0000213d00000001055001900000001f0000c13d0000008003300039000000400040043f0000000006190436000000a0022000390000000004210019000000000334004b0000014a0000213d000600000009001d000500000007001d000400000008001d000000000301004b000000820000613d000000000300001900000000046300190000000005230019000000000505043300000000005404350000002003300039000000000413004b0000007b0000413d000300000006001d000000000116001900000000000104350000010901000041000000000010043900070000000a001d0000000400a0044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000400a00043d000000000101043b000000000101004b000002200000c13d0000006401a000390000011b0200004100000000002104350000004401a000390000011c0200004100000000002104350000002401a0003900000025020000390000000000210435000001150100004100000000001a04350000000401a000390000002002000039000000000021043500000102010000410000010202a0009c000000000a0180190000004001a002100000011a011001c700000404000104300000010201000041000001020340009c0000000004018019000000c0014002100000011f011001c7040203f80000040f000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000000c30000613d00000000070000190000000508700210000000000981034f000000000909043b000000800880003900000000009804350000000107700039000000000867004b000000bb0000413d000000000705004b000000d20000613d0000000506600210000000000761034f00000003055002100000008006600039000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f000300000001035500000001022001900000014c0000613d0000009f02400039000000e00220018f000000400020043f000000200230008c0000014a0000413d000000800200043d000001060420009c0000014a0000213d000000020500036700000000040000310000001f0740018f0000000506400272000000eb0000613d00000000080000190000000509800210000000000a95034f000000000a0a043b0000000000a904350000000108800039000000000968004b000000e40000413d000000000807004b000000f90000613d00000003077002100000000506600210000000000806043300000000087801cf000000000878022f000000000565034f000000000505043b0000010007700089000000000575022f00000000057501cf000000000585019f00000000005604350000000005000414000000040620008c000001c40000c13d0000001f0430018f0000000502300272000001070000613d00000000050000190000000506500210000000000761034f000000000707043b00000000007604350000000105500039000000000625004b000001000000413d000000000504004b000001ed0000613d00000003044002100000000502200210000000000502043300000000054501cf000000000545022f000000000121034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000151019f0000000000120435000001ed0000013d0000010201000041000001020340009c0000000004018019000000c0014002100000011f011001c7040203f80000040f000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f00000005064002720000012e0000613d00000000070000190000000508700210000000000981034f000000000909043b000000800880003900000000009804350000000107700039000000000867004b000001260000413d000000000705004b0000013d0000613d0000000506600210000000000761034f00000003055002100000008006600039000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000001690000613d0000001f02400039000000600220018f00000080022001bf000000400020043f000000200230008c0000014a0000413d000000800200043d000001060420009c0000018c0000a13d00000000010000190000040400010430000000400200043d0000001f0430018f0000000505300272000001590000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000001510000413d000000000604004b000001680000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d000000400200043d0000001f0430018f0000000505300272000001760000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000016e0000413d000000000604004b000001850000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000010201000041000001020420009c000000000201801900000040012002100000006002300210000000000121019f0000040400010430000000020500036700000000040000310000001f0740018f0000000506400272000001990000613d00000000080000190000000509800210000000000a95034f000000000a0a043b0000000000a904350000000108800039000000000968004b000001920000413d000000000807004b000001a70000613d00000003077002100000000506600210000000000806043300000000087801cf000000000878022f000000000565034f000000000505043b0000010007700089000000000575022f00000000057501cf000000000585019f00000000005604350000000005000414000000040620008c000001ee0000c13d0000001f0430018f0000000502300272000001b50000613d00000000050000190000000506500210000000000761034f000000000707043b00000000007604350000000105500039000000000625004b000001ae0000413d000000000504004b000002170000613d00000003044002100000000502200210000000000502043300000000054501cf000000000545022f000000000121034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000151019f0000000000120435000002170000013d0000010201000041000001020350009c0000000005018019000001020340009c00000000040180190000006001400210000000c003500210000000000113019f040203fd0000040f0003000000010355000000000301001900000060033002700000001f0430018f000101020030019d00000102033001970000000505300272000001dd0000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000001d60000413d000000000604004b000001eb0000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f000000000015043500000001012001900000021c0000613d000002170000013d0000010201000041000001020350009c0000000005018019000001020340009c00000000040180190000006001400210000000c003500210000000000113019f040203fd0000040f0003000000010355000000000301001900000060033002700000001f0430018f000101020030019d00000102033001970000000505300272000002070000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000002000000413d000000000604004b000002150000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f000000000015043500000001012001900000021e0000613d0000010201000041000001020230009c00000000030180190000006001300210000004030001042e00000060013002100000040400010430000000600130021000000404000104300000010b0100004100000000001a0435000000000100041400000007020000290000010602200197000000040320008c000700000002001d0000022d0000c13d0000000103000031000000200130008c000000000403001900000020040080390000025e0000013d0000010204000041000001020310009c00000000010480190000010203a0009c00000000040a40190000004003400210000000c001100210000000000131019f0000010c011001c700020000000a001d040203f80000040f000000020a000029000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f00000005064002720000024b0000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000002430000413d000000000705004b0000025a0000613d0000000506600210000000000761034f00000000066a00190000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000002950000613d0000001f01400039000000600210018f0000000001a20019000000000221004b00000000020000190000000102004039000001070410009c0000001f0000213d00000001022001900000001f0000c13d000000400010043f000000200130008c0000014a0000413d00000000010a0433000001060210009c0000014a0000213d00000109020000410000000000200439000000040010044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000400200043d000200000002001d000000000101043b000000000101004b000002b20000c13d0000000203000029000000640130003900000118020000410000000000210435000000440130003900000119020000410000000000210435000000240130003900000030020000390000000000210435000001150100004100000000001304350000000401300039000000200200003900000000002104350000010201000041000001020230009c000000000301801900000040013002100000011a011001c70000040400010430000000400200043d0000001f0430018f0000000505300272000002a20000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000029a0000413d000000000604004b000001850000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d0000010d01000041000000000201041a0000010e022001970000000705000029000000000252019f000000000021041b00000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010f011001c70000800d0200003900000002030000390000011004000041040203f30000040f000000010120019000000006010000290000014a0000613d0000000001010433000000000101004b000002cd0000c13d0000002001000039000001000010044300000120000004430000011701000041000004030001042e0000010b010000410000000202000029000000000012043500000000010004140000000702000029000000040220008c000002d90000c13d0000000103000031000000200130008c000000000403001900000020040080390000030b0000013d0000010202000041000001020310009c00000000010280190000000204000029000001020340009c00000000020440190000004002200210000000c001100210000000000121019f0000010c011001c70000000702000029040203f80000040f000000020a000029000000000301001900000060033002700000010203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000002f80000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000002f00000413d000000000705004b000003070000613d0000000506600210000000000761034f00000002066000290000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000003380000613d0000001f01400039000000600110018f0000000202100029000000000112004b00000000010000190000000101004039000700000002001d000001070220009c00000006040000290000001f0000213d00000001011001900000001f0000c13d0000000701000029000000400010043f000000200130008c0000014a0000413d00000002010000290000000001010433000200000001001d000001060110009c0000014a0000213d0000000701000029000001110110009c0000001f0000213d00000007050000290000006001500039000000400010043f000000400150003900000112020000410000000000210435000000270100003900000000021504360000011301000041000100000002001d0000000000120435000000000204043300000000010004140000000204000029000000040440008c000003550000c13d0000000102000039000001070130009c00000005050000290000001f0000213d0000036d0000013d000000400200043d0000001f0430018f0000000505300272000003450000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b0000033d0000413d000000000604004b000003540000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001850000013d00000102030000410000000305000029000001020450009c00000000050380190000004004500210000001020520009c00000000020380190000006002200210000000000242019f000001020410009c0000000001038019000000c001100210000000000121019f0000000202000029040203fd0000040f0000006004000039000000010220018f00030000000103550000006001100270000101020010019d000001020310019800000004090000290000000505000029000003960000613d0000003f01300039000000000151016f000000400400043d0000000001140019000000000541004b00000000050000190000000105004039000001070610009c0000001f0000213d00000001055001900000001f0000c13d000000400010043f0000001f0130018f000000000934043600000003050003670000000503300272000003870000613d000000000600001900000005076002100000000008790019000000000775034f000000000707043b00000000007804350000000106600039000000000736004b0000037f0000413d000000000601004b000003960000613d0000000503300210000000000535034f00000000033900190000000301100210000000000603043300000000061601cf000000000616022f000000000505043b0000010001100089000000000515022f00000000011501cf000000000161019f00000000001304350000000001040433000000000202004b000003b60000c13d000000000201004b000003dc0000c13d000000400400043d000600000004001d0000011501000041000000000014043500000004014000390000002002000039000000000021043500000007010000290000000003010433000700000003001d0000002401400039000000000031043500000044024000390000000101000029040203e50000040f00000007010000290000001f01100039000000050110017f00000044011000390000010202000041000001020310009c00000000010280190000000604000029000001020340009c00000000040280190000004002400210000003e20000013d000000000101004b000002c80000c13d000001090100004100000000001004390000000201000029000000040010044300000102010000410000000002000414000001020320009c0000000002018019000000c0012002100000010a011001c70000800202000039040203f80000040f0000000102200190000003db0000613d000000000101043b000000000101004b000002c80000c13d000000400100043d00000044021000390000011403000041000000000032043500000024021000390000001d030000390000000000320435000001150200004100000000002104350000000402100039000000200300003900000000003204350000010202000041000001020310009c0000000001028019000000400110021000000116011001c70000040400010430000000000001042f0000010202000041000001020310009c0000000001028019000001020390009c000000000902801900000040029002100000006001100210000000000121019f0000040400010430000000000403004b000003ef0000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000003e80000413d00000000012300190000000000010435000000000001042d000000000001042f000003f6002104210000000102000039000000000001042d0000000002000019000000000001042d000003fb002104230000000102000039000000000001042d0000000002000019000000000001042d00000400002104250000000102000039000000000001042d0000000002000019000000000001042d0000040200000432000004030001042e000004040001043000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000009fffffffffffffffffffffffffffffffffffffffffffffffff000000000000007f00000000000000000000000000000000000000000000000000000001ffffffe0000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000ffffffffffffffff80000000000000000000000000000000000000000000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b8302000002000000000000000000000000000000240000000000000000000000005c60da1b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000a3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50ffffffffffffffffffffffff000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000001cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e000000000000000000000000000000000000000000000000ffffffffffffff9f206661696c656400000000000000000000000000000000000000000000000000416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000008c379a0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000020000000000000000000000000000004000000100000000000000000073206e6f74206120636f6e747261637400000000000000000000000000000000455243313936373a20626561636f6e20696d706c656d656e746174696f6e206900000000000000000000000000000000000000840000000000000000000000007472616374000000000000000000000000000000000000000000000000000000455243313936373a206e657720626561636f6e206973206e6f74206120636f6e4e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000000000000000000000000000000000000000000004000000800000000000000000d32177e88b033622e0bc848f24ab73d0795ed87730981120fcdf94fbc134fa5d", - "linkReferences": {}, - "deployedLinkReferences": {}, - "factoryDeps": {} -} diff --git a/l1-contracts/script-config/artifacts/L2SharedBridge.json b/l1-contracts/script-config/artifacts/L2SharedBridge.json deleted file mode 100644 index a74e5c9ad..000000000 --- a/l1-contracts/script-config/artifacts/L2SharedBridge.json +++ /dev/null @@ -1,262 +0,0 @@ -{ - "_format": "hh-zksolc-artifact-1", - "contractName": "L2SharedBridge", - "sourceName": "contracts/bridge/L2SharedBridge.sol", - "abi": [ - { - "inputs": [ - { - "internalType": "uint256", - "name": "_eraChainId", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "l1Sender", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "l2Receiver", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "l2Token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "FinalizeDeposit", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint8", - "name": "version", - "type": "uint8" - } - ], - "name": "Initialized", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "l2Sender", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "l1Receiver", - "type": "address" - }, - { - "indexed": true, - "internalType": "address", - "name": "l2Token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "amount", - "type": "uint256" - } - ], - "name": "WithdrawalInitiated", - "type": "event" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "_l1Sender", - "type": "address" - }, - { - "internalType": "address", - "name": "_l2Receiver", - "type": "address" - }, - { - "internalType": "address", - "name": "_l1Token", - "type": "address" - }, - { - "internalType": "uint256", - "name": "_amount", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "_data", - "type": "bytes" - } - ], - "name": "finalizeDeposit", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "_l1SharedBridge", - "type": "address" - }, - { - "internalType": "address", - "name": "_l1Bridge", - "type": "address" - }, - { - "internalType": "bytes32", - "name": "_l2TokenProxyBytecodeHash", - "type": "bytes32" - }, - { - "internalType": "address", - "name": "_aliasedOwner", - "type": "address" - } - ], - "name": "initialize", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "l1Bridge", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "l1SharedBridge", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "l2TokenAddress", - "type": "address" - } - ], - "name": "l1TokenAddress", - "outputs": [ - { - "internalType": "address", - "name": "l1TokenAddress", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "_l1Token", - "type": "address" - } - ], - "name": "l2TokenAddress", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "l2TokenBeacon", - "outputs": [ - { - "internalType": "contract UpgradeableBeacon", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "_l1Receiver", - "type": "address" - }, - { - "internalType": "address", - "name": "_l2Token", - "type": "address" - }, - { - "internalType": "uint256", - "name": "_amount", - "type": "uint256" - } - ], - "name": "withdraw", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "bytecode": "0x0004000000000002001000000000000200000000030100190000006004300270000001a20340019700030000003103550002000000010355000001a20040019d00000001022001900000001d0000c13d0000008002000039000000400020043f000000040230008c000000400000413d000000000201043b000000e002200270000001ab0420009c000000420000213d000001b10420009c0000008a0000213d000001b40120009c000000c10000613d000001b50120009c000000400000c13d0000000001000416000000000101004b000000400000c13d0000000401000039000001d90000013d0000000002000416000000000202004b000000400000c13d000000bf02300039000001a302200197000000400020043f0000001f0230018f00000005043002720000002f0000613d00000000050000190000000506500210000000000761034f000000000707043b000000a00660003900000000007604350000000105500039000000000645004b000000270000413d000000000502004b0000003e0000613d0000000504400210000000000141034f0000000302200210000000a004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f0000000000140435000000200130008c000000640000813d00000000010000190000068300010430000001ac0420009c000000940000213d000001af0420009c000000c60000613d000001b00220009c000000400000c13d0000000002000416000000000202004b000000400000c13d000000040230008a000000600220008c000000400000413d0000000402100370000000000402043b000001b60240009c000000400000213d0000002402100370000000000302043b000001b60230009c000000400000213d0000004401100370000000000201043b000000000102004b000001de0000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000001501000039000000a40010043f000001c501000041000000c40010043f000001c6010000410000068300010430000000a00100043d000000800010043f000000000200041a0000ff0003200190000000ac0000c13d000000ff0320018f000000ff0330008c000000820000613d000000ff012001bf000000000010041b000000ff01000039000000400200043d0000000000120435000001a2010000410000000003000414000001a20430009c0000000003018019000001a20420009c00000000020180190000004001200210000000c002300210000000000112019f000001a8011001c70000800d020000390000000103000039000001a904000041068106770000040f0000000101200190000000400000613d000000800100043d000001400000044300000160001004430000002001000039000001000010044300000001010000390000012000100443000001aa01000041000006820001042e000001b20420009c000001a50000613d000001b30120009c000000400000c13d0000000001000416000000000101004b000000400000c13d000000000100041a0000001001100270000001da0000013d000001ad0420009c000001c90000613d000001ae0220009c000000400000c13d0000000002000416000000000202004b000000400000c13d000000040230008a000000200220008c000000400000413d0000000401100370000000000101043b000001b60210009c000000400000213d068106050000040f000001b601100197000000400200043d0000000000120435000001a201000041000001a20320009c00000000020180190000004001200210000001b7011001c7000006820001042e000000400100043d0000006402100039000001a40300004100000000003204350000004402100039000001a5030000410000000000320435000000240210003900000027030000390000000000320435000001a6020000410000000000210435000000040210003900000020030000390000000000320435000001a202000041000001a20310009c00000000010280190000004001100210000001a7011001c700000683000104300000000001000416000000000101004b000000400000c13d0000000101000039000001d90000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000a00220008c000000400000413d0000000402100370000000000802043b000001b60280009c000000400000213d0000002402100370000000000902043b000001b60290009c000000400000213d0000004402100370000000000a02043b000001b602a0009c000000400000213d0000008402100370000000000202043b000001bd0420009c000000400000213d0000002304200039000001c705000041000000000634004b00000000060000190000000006058019000001c704400197000000000704004b0000000005008019000001c70440009c000000000506c019000000000405004b000000400000c13d0000000404200039000000000441034f000000000504043b000001bd0450009c000000400000213d001000240020003d0000001002500029000000000232004b000000400000213d000b00000005001d000f0000000a001d000e00000009001d000c00000008001d0000006401100370000000000101043b000d00000001001d0000000001000411000001c801100041000001b6011001970000000402000039000000000202041a000001b602200197000000000221004b000001050000613d000000000200041a0000001002200270000001b602200197000000000121004b000002c10000c13d0000000101000039000800000001001d000000000101041a000001b601100197000000a00010043f0000004001000039000900000001001d000000c00010043f000000e00000043f0000006001000039000a00000001001d000000800010043f0000010001000039000000400010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ca011001c700008010020000390681067c0000040f00000001022001900000000f05000029000000400000613d0000000202000039000700000002001d000000000202041a000000000301043b000000400100043d000000a004100039000000000034043500000080031000390000000000230435000000600210003900000000005204350000004002100039000000000300041000000000003204350000002002100039000001cb030000410000000000320435000000a0030000390000000000310435000001cc0310009c000002170000213d000000c003100039000000400030043f000001a204000041000001a20320009c000000000204801900000040022002100000000001010433000001a20310009c00000000010480190000006001100210000000000121019f0000000002000414000001a20320009c0000000002048019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000000101043b000500000001001d000001b601100197000600000001001d00000000001004350000000301000039000400000001001d000000200010043f0000000001000414000001a20210009c000001a201008041000000c001100210000001be011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000000101043b000000000101041a000001b601100198000003ad0000c13d00000000010004140000000702000029000000000402041a0000000802000029000000000202041a000000400300043d000000400530003900000009060000290000000000650435000001b602200197000000200530003900000000002504350000000a02000029000000000023043500000060023000390000000000020435000001c00230009c000002170000213d0000008002300039000000400020043f000000a005300039000001cf060000410000000000650435000000e4053000390000000a060000290000000000650435000000c4053000390000000000450435000000a4043000390000000f0500002900000000005404350000010405300039000000000403043300000000004504350000012405300039000000000604004b0000018a0000613d000000000600001900000000075600190000002006600039000000000836001900000000080804330000000000870435000000000746004b000001830000413d000000000354001900000000000304350000001f03400039000a0020000000920000000a0330017f00000084043000390000000000420435000000c3033000390000000a0430017f0000000003240019000000000443004b00000000040000190000000104004039000001bd0530009c000002170000213d0000000104400190000002170000c13d000000400030043f0000000004020433000001d00540009c0000045f0000413d0000004401300039000001dc02000041000000000021043500000024013000390000000802000039000002b50000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000800220008c000000400000413d0000000402100370000000000202043b000001b60320009c000000400000213d0000002403100370000000000603043b000001b60360009c000000400000213d0000006403100370000000000503043b000001b60350009c000000400000213d000000000300041a0000fffe043001900000021d0000c13d000001e00330019700000102033001bf000000000030041b0000004401100370000000000401043b000000000102004b000002290000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f501000041000000610000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000200220008c000000400000413d0000000401100370000000000101043b000001b60210009c000000400000213d00000000001004350000000301000039000000200010043f00000040020000390000000001000019068106610000040f000000000101041a000001b601100197000000800010043f000001b801000041000006820001042e000f00000002001d000e00000004001d000001b9010000410000000000100439001000000003001d0000000400300443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000001004000029000000400000613d000000400500043d00000024015000390000000f020000290000000000210435000001bb0100004100000000001504350000000001000411000d00000001001d000001b601100197000000040250003900000000001204350000000001000414000000040240008c000002150000613d000001a202000041000001a20310009c0000000001028019000001a20350009c00000000020540190000004002200210000000c001100210000000000121019f000001bc011001c70000000002040019000c00000005001d068106770000040f0000000c05000029000000100400002900000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000002640000613d000001bd0150009c000002400000a13d000001f00100004100000000001004350000004101000039000000040010043f000001ef010000410000068300010430000001a601000041000000800010043f0000002001000039000000840010043f0000002e01000039000000a40010043f000001dd01000041000000c40010043f000001de01000041000000e40010043f000001df010000410000068300010430000000000104004b000002330000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f401000041000000610000013d001000000006001d000f00000004001d000e00000005001d000000000105004b000002870000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f301000041000000610000013d000000400050043f00000000004004350000000301000039000000200010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001be011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000400200043d0000002403200039000000000101043b000000000101041a000001b601100198000002c90000c13d000001a6010000410000000000120435000000040120003900000020040000390000000000410435000000020100003900000000001304350000004401200039000001c3030000410000000000310435000001a201000041000001a20320009c00000000020180190000004001200210000001c4011001c70000068300010430000000400200043d0000001f0430018f0000000505300272000002710000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000002690000413d000000000604004b000002800000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001a201000041000001a20420009c000000000201801900000040012002100000006002300210000000000121019f0000068300010430000001e1013001970000001002200210000001e202200197000000000121019f000000000010041b000001e3010000410000000000100439000000000100041200000004001004430000002400000443000001a2030000410000000001000414000001a20210009c0000000001038019000000c001100210000001e4011001c700008005020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000d00000001001d000001e50100004100000000001004390000000001000414000001a20210009c000001a201008041000000c001100210000001e6011001c70000800b020000390681067c0000040f00000001022001900000059c0000613d000000400200043d000c00000002001d000000000101043b0000000d0110006c0000034d0000c13d000000100100006b0000038f0000c13d0000000c030000290000004401300039000001f2020000410000000000210435000000240130003900000003020000390000000000210435000001a6010000410000000000130435000000040130003900000020020000390000000000210435000001a201000041000001a20230009c00000000030180190000004001300210000001c4011001c70000068300010430000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001c901000041000000610000013d0000002004200039000001bf0500004100000000005404350000000e04000029000000600440021000000000004304350000006001100210000000380320003900000000001304350000004c012000390000000f0300002900000000003104350000004c010000390000000000120435000001c00120009c000002170000213d0000008003200039000000400030043f000001c101000041000c00000003001d0000000000130435000000840120003900000020030000390000000000310435000000a40320003900000000010204330000000000130435000000c403200039000000000401004b000002ef0000613d000000000400001900000000053400190000002004400039000000000624001900000000060604330000000000650435000000000514004b000002e80000413d000000000231001900000000000204350000001f01100039000000200200008a000000000121016f000001a2020000410000000c04000029000001a20340009c0000000003020019000000000304401900000040033002100000004401100039000001a20410009c00000000010280190000006001100210000000000131019f0000000003000414000001a20430009c0000000003028019000000c002300210000000000112019f0000800802000039068106770000040f0000000c0a00002900000000030100190000006003300270000001a203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000003190000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000003110000413d000000000705004b000003280000613d0000000506600210000000000761034f0000000c066000290000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000003720000613d0000001f01400039000000600210018f0000000c01200029000000000221004b00000000020000190000000102004039000001bd0410009c00000010070000290000000e05000029000002170000213d0000000102200190000002170000c13d000000400010043f000000200230008c000000400000413d0000000f020000290000000000210435000001a2020000410000000003000414000001a20430009c0000000003028019000001a20410009c00000000010280190000004001100210000000c002300210000000000112019f000001a8011001c7000001b6065001970000800d020000390000000403000039000001c2040000410000000d05000029000003a80000013d0000000c01000029000001e70110009c000002170000813d0000000c040000290000002401400039000001e8020000410000000000210435000000440140003900000000020004140000006003000039001000000003001d0000000000310435000001e90100004100000000001404350000006401400039000000000001043500000004014000390000000000010435000001a201000041000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000121019f000001ea011001c70000800602000039068106770000040f0000000102200190000003fc0000613d000000000201043b000000000102004b000004380000c13d00000003010003670000000102000031000004010000013d000000400200043d0000001f0430018f00000005053002720000037f0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000003770000413d000000000604004b0000038e0000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d0000000401000039000000000201041a000001d90220019700000010022001af000000000021041b000001f101000041000000000200041a000000000112016f000000000010041b00000002010000390000000c040000290000000000140435000001a2010000410000000002000414000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000112019f000001a8011001c70000800d020000390000000103000039000001a904000041068106770000040f0000000101200190000000400000613d0000000001000019000006820001042e0000000f0110006c000004260000c13d000001b901000041000000000010043900000006010000290000000400100443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000e02000029000000400000613d000000400400043d00000024014000390000000d030000290000000000310435000001da010000410000000000140435000001b602200197001000000004001d0000000401400039000f00000002001d000000000021043500000000010004140000000602000029000000040220008c000003e30000613d000001a202000041000001a20310009c00000000010280190000001004000029000001a20340009c00000000020440190000004002200210000000c001100210000000000121019f000001bc011001c70000000602000029068106770000040f00000000030100190000006003300270000101a20030019d000001a203300197000300000001035500000001022001900000059d0000613d0000001001000029000001bd0110009c000002170000213d0000001004000029000000400040043f0000000d010000290000000000140435000001a2010000410000000002000414000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000112019f000001a8011001c70000000c02000029000001b6052001970000800d020000390000000403000039000001db040000410000000f060000290000000607000029000003a80000013d000300000001035500000000020100190000006002200270000101a20020019d000001a202200197000000400300043d0000001f0420018f00000005052002720000040e0000613d000000000600001900000005076002100000000008730019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000004060000413d000000000604004b0000041d0000613d0000000505500210000000000151034f00000000055300190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001a201000041000001a20430009c0000000003018019000001a20420009c000000000201801900000060012002100000004002300210000000000112019f0000068300010430000000400100043d0000004402100039000001ce030000410000000000320435000000240210003900000007030000290000000000320435000001a6020000410000000000210435000000040210003900000020030000390000000000320435000001a202000041000001a20310009c00000000010280190000004001100210000001c4011001c70000068300010430000000400100043d000001eb0310009c000002170000213d000001b602200197000000840310003900000000002304350000002402100039000001ec0300004100000000003204350000006402100039000000000300041400000020040000390000000000420435000000440210003900000010040000290000000000420435000001e902000041000000000021043500000004021000390000000000020435000001a202000041000001a20430009c0000000003028019000001a20410009c00000000010280190000004001100210000000c002300210000000000121019f000001ed011001c70000800602000039068106770000040f00000001022001900000053c0000613d000000000101043b000000000201004b0000055e0000c13d00000003010003670000000102000031000005410000013d000000c001100210000001d1011001970000004002200210000001d202200041000001d302200197000000000121019f0000006002400210000001d402200197000000000121019f000001d5011001c700008006020000390000000003000019000000000400001900000000050000190000000006000019068106770000040f000300000001035500000000030100190000006003300270000101a20030019d000001a2053001970000003f03500039000001a306300197000000400400043d0000000003460019000000000663004b00000000060000190000000106004039000001bd0730009c000002170000213d0000000106600190000002170000c13d000000400030043f00000000035404360000001f0650003900000005066002720000048f0000613d0000000007000031000000020770036700000000080000190000000509800210000000000a930019000000000997034f000000000909043b00000000009a04350000000108800039000000000968004b000004870000413d000000000600004b000004910000613d0000001f0650018f00000005055002720000049d0000613d000000000700001900000005087002100000000009830019000000000881034f000000000808043b00000000008904350000000107700039000000000857004b000004950000413d000000000706004b000004ac0000613d0000000505500210000000000151034f00000000055300190000000306600210000000000705043300000000076701cf000000000767022f000000000101043b0000010006600089000000000161022f00000000016101cf000000000171019f00000000001504350000000101200190000005ba0000613d0000000001040433000001c702000041000000200410008c00000000040000190000000004024019000001c701100197000000000501004b000000000200a019000001c70110009c000000000204c019000000000102004b000000400000c13d0000000001030433000800000001001d000001b60110009c000000400000213d000001b901000041000000000010043900000008010000290000000400100443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000f020000290000000b04000029000000400000613d000000400300043d000001d701000041000000000013043500000024053000390000000901000029000300000005001d00000000001504350000000401300039000200000001001d00000000002104350000001f0240018f0000006401300039000900000003001d0000004403300039000100000003001d0000000000430435000000100300002900000002033003670000000504400272000004ee0000613d000000000500001900000005065002100000000007610019000000000663034f000000000606043b00000000006704350000000105500039000000000645004b000004e60000413d000000000502004b000004fd0000613d0000000504400210000000000343034f00000000044100190000000302200210000000000504043300000000052501cf000000000525022f000000000303043b0000010002200089000000000323022f00000000022301cf000000000252019f00000000002404350000000b01100029000000000001043500000000010004140000000802000029000000040220008c0000051e0000613d0000000b020000290000001f022000390000000a0220017f000001a2030000410000000905000029000001a20450009c0000000004030019000000000405401900000040044002100000006402200039000001a20520009c00000000020380190000006002200210000000000224019f000001a20410009c0000000001038019000000c001100210000000000121019f0000000802000029068106770000040f00000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000005db0000613d0000000901000029000001bd0110009c000002170000213d0000000901000029000000400010043f0000000802000029000000050120014f000001b601100198000005f80000c13d000000060100002900000000001004350000000401000029000000200010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001be011001c700008010020000390681067c0000040f00000001022001900000000f03000029000000400000613d000000000101043b000000000201041a000001d902200197000000000232019f000000000021041b000003af0000013d000300000001035500000000020100190000006002200270000101a20020019d000001a202200197000000400300043d0000001f0420018f00000005052002720000054e0000613d000000000600001900000005076002100000000008730019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005460000413d000000000604004b0000055d0000613d0000000505500210000000000151034f00000000055300190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000041d0000013d000001b6031001970000000101000039000000000201041a000001d902200197000000000232019f000000000021041b00000002010000390000000f02000029000000000021041b000001b9010000410000000000100439001000000003001d0000000400300443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000e02000029000000400000613d000000400300043d000001ee010000410000000000130435000c00000003001d0000000401300039000000000021043500000000010004140000001002000029000000040220008c000005960000613d000001a202000041000001a20310009c00000000010280190000000c04000029000001a20340009c00000000020440190000004002200210000000c001100210000000000121019f000001ef011001c70000001002000029068106770000040f00000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000005be0000613d0000000c01000029000001bd0110009c000002170000213d0000000c01000029000000400010043f000003940000013d000000000001042f000000400200043d0000001f0430018f0000000505300272000005aa0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005a20000413d000000000604004b000005b90000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000000400100043d0000004402100039000001d603000041000004290000013d000000400200043d0000001f0430018f0000000505300272000005cb0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005c30000413d000000000604004b000002800000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000000400200043d0000001f0430018f0000000505300272000005e80000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005e00000413d000000000604004b000005f70000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000001a60100004100000009030000290000000000130435000000200100003900000002020000290000000000120435000000070100002900000003020000290000000000120435000001d80100004100000001020000290000000000120435000002bb0000013d0001000000000002000100000001001d0000000101000039000000000301041a000000400100043d00000040021000390000004004000039000000000042043500000060020000390000000002210436000001b603300197000000000032043500000060031000390000000000030435000001f60310009c000006580000813d0000008003100039000000400030043f000001a203000041000001a20420009c000000000203801900000040022002100000000001010433000001a20410009c00000000010380190000006001100210000000000121019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f00000001022001900000065e0000613d0000000202000039000000000202041a000000000301043b000000400100043d000000a0041000390000000000340435000000800310003900000000002304350000000102000029000001b602200197000000600310003900000000002304350000004002100039000000000300041000000000003204350000002002100039000001cb030000410000000000320435000000a0030000390000000000310435000001cc0310009c000006580000213d000000c003100039000000400030043f000001a203000041000001a20420009c000000000203801900000040022002100000000001010433000001a20410009c00000000010380190000006001100210000000000121019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f00000001022001900000065e0000613d000000000101043b000001b601100197000000000001042d000001f00100004100000000001004350000004101000039000000040010043f000001ef01000041000006830001043000000000010000190000068300010430000000000001042f000001a203000041000001a20410009c00000000010380190000004001100210000001a20420009c00000000020380190000006002200210000000000112019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f0000000102200190000006750000613d000000000101043b000000000001042d000000000100001900000683000104300000067a002104210000000102000039000000000001042d0000000002000019000000000001042d0000067f002104230000000102000039000000000001042d0000000002000019000000000001042d0000068100000432000006820001042e0000068300010430000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000000000000000000000000000000000000000000001ffffffe0616c697a696e6700000000000000000000000000000000000000000000000000496e697469616c697a61626c653a20636f6e747261637420697320696e69746908c379a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008400000000000000000000000002000000000000000000000000000000000000200000000000000000000000007f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498000000020000000000000000000000000000008000000100000000000000000000000000000000000000000000000000000000000000000000000000cfe7af7b00000000000000000000000000000000000000000000000000000000f54266a100000000000000000000000000000000000000000000000000000000f54266a200000000000000000000000000000000000000000000000000000000f5f1516800000000000000000000000000000000000000000000000000000000cfe7af7c00000000000000000000000000000000000000000000000000000000d9caed1200000000000000000000000000000000000000000000000000000000a31ee5af00000000000000000000000000000000000000000000000000000000a31ee5b000000000000000000000000000000000000000000000000000000000b852ad36000000000000000000000000000000000000000000000000000000006dde720900000000000000000000000000000000000000000000000000000000969b53da000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000008000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b83020000020000000000000000000000000000002400000000000000000000000074f4f547000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffff020000000000000000000000000000000000004000000000000000000000000011a2ccc100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7f62f84b24000000000000000000000000000000000000000000000000000000002fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b079680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064000000000000000000000000416d6f756e742063616e6e6f74206265207a65726f000000000000000000000000000000000000000000000000000000000000640000008000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000eeeeffffffffffffffffffffffffffffffffeeef6d710000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000060000000a000000000000000002020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494000000000000000000000000000000000000000000000000ffffffffffffff3f020000000000000000000000000000000000000000000000000000000000000067670000000000000000000000000000000000000000000000000000000000003cda335100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000ffffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffff00000000000000000000000001000000000000000000000000000000000000000000000000000000000000006d6b00000000000000000000000000000000000000000000000000000000000095f11a40000000000000000000000000000000000000000000000000000000006d74000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff00000000000000000000000000000000000000008c2a993e00000000000000000000000000000000000000000000000000000000b84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f634f766572666c6f77000000000000000000000000000000000000000000000000496e697469616c697a61626c653a20636f6e747261637420697320616c726561647920696e697469616c697a65640000000000000000000000000000000000000000000000000000000000000000000000000084000000800000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ffffffffffffffffffff0000000000000000000000000000000000000000010200000000000000000000ffffffffffffffffffffffffffffffffffffffff0000310ab089e4439a4c15d089f94afb7896ff553aecb10793d0ab882de59d99a32e02000002000000000000000000000000000000440000000000000000000000009a8a0592ac89c5ad3bc6df8224c17b485976f597df104ee20d0df415241f670b0200000200000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7c010004751688ab9322961547058fd0f36d3edf69880b64cbb2857041d33f4a133cda33511d41a8a5431b1770c5bc0ddd62e1cd30555d16659b89c0d60f4f9f570200000000000000000000000000000000000084000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7b010000691fa4f751f8312bc555242f18ed78cdc9aabc0ea77d7d5a675ee8ac6f02000000000000000000000000000000000000a4000000000000000000000000f2fde38b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000004e487b7100000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff6266320000000000000000000000000000000000000000000000000000000000736600000000000000000000000000000000000000000000000000000000000064660000000000000000000000000000000000000000000000000000000000006266000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff800000000000000000000000000000000000000000000000000000000000000000f5cf0be6820df44d868e986d4d5cafabd5702ac45d181a5ac4eb5ed59a001b03", - "deployedBytecode": "0x0004000000000002001000000000000200000000030100190000006004300270000001a20340019700030000003103550002000000010355000001a20040019d00000001022001900000001d0000c13d0000008002000039000000400020043f000000040230008c000000400000413d000000000201043b000000e002200270000001ab0420009c000000420000213d000001b10420009c0000008a0000213d000001b40120009c000000c10000613d000001b50120009c000000400000c13d0000000001000416000000000101004b000000400000c13d0000000401000039000001d90000013d0000000002000416000000000202004b000000400000c13d000000bf02300039000001a302200197000000400020043f0000001f0230018f00000005043002720000002f0000613d00000000050000190000000506500210000000000761034f000000000707043b000000a00660003900000000007604350000000105500039000000000645004b000000270000413d000000000502004b0000003e0000613d0000000504400210000000000141034f0000000302200210000000a004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f0000000000140435000000200130008c000000640000813d00000000010000190000068300010430000001ac0420009c000000940000213d000001af0420009c000000c60000613d000001b00220009c000000400000c13d0000000002000416000000000202004b000000400000c13d000000040230008a000000600220008c000000400000413d0000000402100370000000000402043b000001b60240009c000000400000213d0000002402100370000000000302043b000001b60230009c000000400000213d0000004401100370000000000201043b000000000102004b000001de0000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000001501000039000000a40010043f000001c501000041000000c40010043f000001c6010000410000068300010430000000a00100043d000000800010043f000000000200041a0000ff0003200190000000ac0000c13d000000ff0320018f000000ff0330008c000000820000613d000000ff012001bf000000000010041b000000ff01000039000000400200043d0000000000120435000001a2010000410000000003000414000001a20430009c0000000003018019000001a20420009c00000000020180190000004001200210000000c002300210000000000112019f000001a8011001c70000800d020000390000000103000039000001a904000041068106770000040f0000000101200190000000400000613d000000800100043d000001400000044300000160001004430000002001000039000001000010044300000001010000390000012000100443000001aa01000041000006820001042e000001b20420009c000001a50000613d000001b30120009c000000400000c13d0000000001000416000000000101004b000000400000c13d000000000100041a0000001001100270000001da0000013d000001ad0420009c000001c90000613d000001ae0220009c000000400000c13d0000000002000416000000000202004b000000400000c13d000000040230008a000000200220008c000000400000413d0000000401100370000000000101043b000001b60210009c000000400000213d068106050000040f000001b601100197000000400200043d0000000000120435000001a201000041000001a20320009c00000000020180190000004001200210000001b7011001c7000006820001042e000000400100043d0000006402100039000001a40300004100000000003204350000004402100039000001a5030000410000000000320435000000240210003900000027030000390000000000320435000001a6020000410000000000210435000000040210003900000020030000390000000000320435000001a202000041000001a20310009c00000000010280190000004001100210000001a7011001c700000683000104300000000001000416000000000101004b000000400000c13d0000000101000039000001d90000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000a00220008c000000400000413d0000000402100370000000000802043b000001b60280009c000000400000213d0000002402100370000000000902043b000001b60290009c000000400000213d0000004402100370000000000a02043b000001b602a0009c000000400000213d0000008402100370000000000202043b000001bd0420009c000000400000213d0000002304200039000001c705000041000000000634004b00000000060000190000000006058019000001c704400197000000000704004b0000000005008019000001c70440009c000000000506c019000000000405004b000000400000c13d0000000404200039000000000441034f000000000504043b000001bd0450009c000000400000213d001000240020003d0000001002500029000000000232004b000000400000213d000b00000005001d000f0000000a001d000e00000009001d000c00000008001d0000006401100370000000000101043b000d00000001001d0000000001000411000001c801100041000001b6011001970000000402000039000000000202041a000001b602200197000000000221004b000001050000613d000000000200041a0000001002200270000001b602200197000000000121004b000002c10000c13d0000000101000039000800000001001d000000000101041a000001b601100197000000a00010043f0000004001000039000900000001001d000000c00010043f000000e00000043f0000006001000039000a00000001001d000000800010043f0000010001000039000000400010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ca011001c700008010020000390681067c0000040f00000001022001900000000f05000029000000400000613d0000000202000039000700000002001d000000000202041a000000000301043b000000400100043d000000a004100039000000000034043500000080031000390000000000230435000000600210003900000000005204350000004002100039000000000300041000000000003204350000002002100039000001cb030000410000000000320435000000a0030000390000000000310435000001cc0310009c000002170000213d000000c003100039000000400030043f000001a204000041000001a20320009c000000000204801900000040022002100000000001010433000001a20310009c00000000010480190000006001100210000000000121019f0000000002000414000001a20320009c0000000002048019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000000101043b000500000001001d000001b601100197000600000001001d00000000001004350000000301000039000400000001001d000000200010043f0000000001000414000001a20210009c000001a201008041000000c001100210000001be011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000000101043b000000000101041a000001b601100198000003ad0000c13d00000000010004140000000702000029000000000402041a0000000802000029000000000202041a000000400300043d000000400530003900000009060000290000000000650435000001b602200197000000200530003900000000002504350000000a02000029000000000023043500000060023000390000000000020435000001c00230009c000002170000213d0000008002300039000000400020043f000000a005300039000001cf060000410000000000650435000000e4053000390000000a060000290000000000650435000000c4053000390000000000450435000000a4043000390000000f0500002900000000005404350000010405300039000000000403043300000000004504350000012405300039000000000604004b0000018a0000613d000000000600001900000000075600190000002006600039000000000836001900000000080804330000000000870435000000000746004b000001830000413d000000000354001900000000000304350000001f03400039000a0020000000920000000a0330017f00000084043000390000000000420435000000c3033000390000000a0430017f0000000003240019000000000443004b00000000040000190000000104004039000001bd0530009c000002170000213d0000000104400190000002170000c13d000000400030043f0000000004020433000001d00540009c0000045f0000413d0000004401300039000001dc02000041000000000021043500000024013000390000000802000039000002b50000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000800220008c000000400000413d0000000402100370000000000202043b000001b60320009c000000400000213d0000002403100370000000000603043b000001b60360009c000000400000213d0000006403100370000000000503043b000001b60350009c000000400000213d000000000300041a0000fffe043001900000021d0000c13d000001e00330019700000102033001bf000000000030041b0000004401100370000000000401043b000000000102004b000002290000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f501000041000000610000013d0000000002000416000000000202004b000000400000c13d000000040230008a000000200220008c000000400000413d0000000401100370000000000101043b000001b60210009c000000400000213d00000000001004350000000301000039000000200010043f00000040020000390000000001000019068106610000040f000000000101041a000001b601100197000000800010043f000001b801000041000006820001042e000f00000002001d000e00000004001d000001b9010000410000000000100439001000000003001d0000000400300443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000001004000029000000400000613d000000400500043d00000024015000390000000f020000290000000000210435000001bb0100004100000000001504350000000001000411000d00000001001d000001b601100197000000040250003900000000001204350000000001000414000000040240008c000002150000613d000001a202000041000001a20310009c0000000001028019000001a20350009c00000000020540190000004002200210000000c001100210000000000121019f000001bc011001c70000000002040019000c00000005001d068106770000040f0000000c05000029000000100400002900000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000002640000613d000001bd0150009c000002400000a13d000001f00100004100000000001004350000004101000039000000040010043f000001ef010000410000068300010430000001a601000041000000800010043f0000002001000039000000840010043f0000002e01000039000000a40010043f000001dd01000041000000c40010043f000001de01000041000000e40010043f000001df010000410000068300010430000000000104004b000002330000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f401000041000000610000013d001000000006001d000f00000004001d000e00000005001d000000000105004b000002870000c13d000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001f301000041000000610000013d000000400050043f00000000004004350000000301000039000000200010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001be011001c700008010020000390681067c0000040f0000000102200190000000400000613d000000400200043d0000002403200039000000000101043b000000000101041a000001b601100198000002c90000c13d000001a6010000410000000000120435000000040120003900000020040000390000000000410435000000020100003900000000001304350000004401200039000001c3030000410000000000310435000001a201000041000001a20320009c00000000020180190000004001200210000001c4011001c70000068300010430000000400200043d0000001f0430018f0000000505300272000002710000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000002690000413d000000000604004b000002800000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001a201000041000001a20420009c000000000201801900000040012002100000006002300210000000000121019f0000068300010430000001e1013001970000001002200210000001e202200197000000000121019f000000000010041b000001e3010000410000000000100439000000000100041200000004001004430000002400000443000001a2030000410000000001000414000001a20210009c0000000001038019000000c001100210000001e4011001c700008005020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000d00000001001d000001e50100004100000000001004390000000001000414000001a20210009c000001a201008041000000c001100210000001e6011001c70000800b020000390681067c0000040f00000001022001900000059c0000613d000000400200043d000c00000002001d000000000101043b0000000d0110006c0000034d0000c13d000000100100006b0000038f0000c13d0000000c030000290000004401300039000001f2020000410000000000210435000000240130003900000003020000390000000000210435000001a6010000410000000000130435000000040130003900000020020000390000000000210435000001a201000041000001a20230009c00000000030180190000004001300210000001c4011001c70000068300010430000001a601000041000000800010043f0000002001000039000000840010043f0000000201000039000000a40010043f000001c901000041000000610000013d0000002004200039000001bf0500004100000000005404350000000e04000029000000600440021000000000004304350000006001100210000000380320003900000000001304350000004c012000390000000f0300002900000000003104350000004c010000390000000000120435000001c00120009c000002170000213d0000008003200039000000400030043f000001c101000041000c00000003001d0000000000130435000000840120003900000020030000390000000000310435000000a40320003900000000010204330000000000130435000000c403200039000000000401004b000002ef0000613d000000000400001900000000053400190000002004400039000000000624001900000000060604330000000000650435000000000514004b000002e80000413d000000000231001900000000000204350000001f01100039000000200200008a000000000121016f000001a2020000410000000c04000029000001a20340009c0000000003020019000000000304401900000040033002100000004401100039000001a20410009c00000000010280190000006001100210000000000131019f0000000003000414000001a20430009c0000000003028019000000c002300210000000000112019f0000800802000039068106770000040f0000000c0a00002900000000030100190000006003300270000001a203300197000000200430008c000000000403001900000020040080390000001f0540018f0000000506400272000003190000613d0000000007000019000000050870021000000000098a0019000000000881034f000000000808043b00000000008904350000000107700039000000000867004b000003110000413d000000000705004b000003280000613d0000000506600210000000000761034f0000000c066000290000000305500210000000000806043300000000085801cf000000000858022f000000000707043b0000010005500089000000000757022f00000000055701cf000000000585019f0000000000560435000100000003001f00030000000103550000000102200190000003720000613d0000001f01400039000000600210018f0000000c01200029000000000221004b00000000020000190000000102004039000001bd0410009c00000010070000290000000e05000029000002170000213d0000000102200190000002170000c13d000000400010043f000000200230008c000000400000413d0000000f020000290000000000210435000001a2020000410000000003000414000001a20430009c0000000003028019000001a20410009c00000000010280190000004001100210000000c002300210000000000112019f000001a8011001c7000001b6065001970000800d020000390000000403000039000001c2040000410000000d05000029000003a80000013d0000000c01000029000001e70110009c000002170000813d0000000c040000290000002401400039000001e8020000410000000000210435000000440140003900000000020004140000006003000039001000000003001d0000000000310435000001e90100004100000000001404350000006401400039000000000001043500000004014000390000000000010435000001a201000041000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000121019f000001ea011001c70000800602000039068106770000040f0000000102200190000003fc0000613d000000000201043b000000000102004b000004380000c13d00000003010003670000000102000031000004010000013d000000400200043d0000001f0430018f00000005053002720000037f0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000003770000413d000000000604004b0000038e0000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d0000000401000039000000000201041a000001d90220019700000010022001af000000000021041b000001f101000041000000000200041a000000000112016f000000000010041b00000002010000390000000c040000290000000000140435000001a2010000410000000002000414000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000112019f000001a8011001c70000800d020000390000000103000039000001a904000041068106770000040f0000000101200190000000400000613d0000000001000019000006820001042e0000000f0110006c000004260000c13d000001b901000041000000000010043900000006010000290000000400100443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000e02000029000000400000613d000000400400043d00000024014000390000000d030000290000000000310435000001da010000410000000000140435000001b602200197001000000004001d0000000401400039000f00000002001d000000000021043500000000010004140000000602000029000000040220008c000003e30000613d000001a202000041000001a20310009c00000000010280190000001004000029000001a20340009c00000000020440190000004002200210000000c001100210000000000121019f000001bc011001c70000000602000029068106770000040f00000000030100190000006003300270000101a20030019d000001a203300197000300000001035500000001022001900000059d0000613d0000001001000029000001bd0110009c000002170000213d0000001004000029000000400040043f0000000d010000290000000000140435000001a2010000410000000002000414000001a20320009c0000000002018019000001a20340009c00000000040180190000004001400210000000c002200210000000000112019f000001a8011001c70000000c02000029000001b6052001970000800d020000390000000403000039000001db040000410000000f060000290000000607000029000003a80000013d000300000001035500000000020100190000006002200270000101a20020019d000001a202200197000000400300043d0000001f0420018f00000005052002720000040e0000613d000000000600001900000005076002100000000008730019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000004060000413d000000000604004b0000041d0000613d0000000505500210000000000151034f00000000055300190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000001a201000041000001a20430009c0000000003018019000001a20420009c000000000201801900000060012002100000004002300210000000000112019f0000068300010430000000400100043d0000004402100039000001ce030000410000000000320435000000240210003900000007030000290000000000320435000001a6020000410000000000210435000000040210003900000020030000390000000000320435000001a202000041000001a20310009c00000000010280190000004001100210000001c4011001c70000068300010430000000400100043d000001eb0310009c000002170000213d000001b602200197000000840310003900000000002304350000002402100039000001ec0300004100000000003204350000006402100039000000000300041400000020040000390000000000420435000000440210003900000010040000290000000000420435000001e902000041000000000021043500000004021000390000000000020435000001a202000041000001a20430009c0000000003028019000001a20410009c00000000010280190000004001100210000000c002300210000000000121019f000001ed011001c70000800602000039068106770000040f00000001022001900000053c0000613d000000000101043b000000000201004b0000055e0000c13d00000003010003670000000102000031000005410000013d000000c001100210000001d1011001970000004002200210000001d202200041000001d302200197000000000121019f0000006002400210000001d402200197000000000121019f000001d5011001c700008006020000390000000003000019000000000400001900000000050000190000000006000019068106770000040f000300000001035500000000030100190000006003300270000101a20030019d000001a2053001970000003f03500039000001a306300197000000400400043d0000000003460019000000000663004b00000000060000190000000106004039000001bd0730009c000002170000213d0000000106600190000002170000c13d000000400030043f00000000035404360000001f0650003900000005066002720000048f0000613d0000000007000031000000020770036700000000080000190000000509800210000000000a930019000000000997034f000000000909043b00000000009a04350000000108800039000000000968004b000004870000413d000000000600004b000004910000613d0000001f0650018f00000005055002720000049d0000613d000000000700001900000005087002100000000009830019000000000881034f000000000808043b00000000008904350000000107700039000000000857004b000004950000413d000000000706004b000004ac0000613d0000000505500210000000000151034f00000000055300190000000306600210000000000705043300000000076701cf000000000767022f000000000101043b0000010006600089000000000161022f00000000016101cf000000000171019f00000000001504350000000101200190000005ba0000613d0000000001040433000001c702000041000000200410008c00000000040000190000000004024019000001c701100197000000000501004b000000000200a019000001c70110009c000000000204c019000000000102004b000000400000c13d0000000001030433000800000001001d000001b60110009c000000400000213d000001b901000041000000000010043900000008010000290000000400100443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000f020000290000000b04000029000000400000613d000000400300043d000001d701000041000000000013043500000024053000390000000901000029000300000005001d00000000001504350000000401300039000200000001001d00000000002104350000001f0240018f0000006401300039000900000003001d0000004403300039000100000003001d0000000000430435000000100300002900000002033003670000000504400272000004ee0000613d000000000500001900000005065002100000000007610019000000000663034f000000000606043b00000000006704350000000105500039000000000645004b000004e60000413d000000000502004b000004fd0000613d0000000504400210000000000343034f00000000044100190000000302200210000000000504043300000000052501cf000000000525022f000000000303043b0000010002200089000000000323022f00000000022301cf000000000252019f00000000002404350000000b01100029000000000001043500000000010004140000000802000029000000040220008c0000051e0000613d0000000b020000290000001f022000390000000a0220017f000001a2030000410000000905000029000001a20450009c0000000004030019000000000405401900000040044002100000006402200039000001a20520009c00000000020380190000006002200210000000000224019f000001a20410009c0000000001038019000000c001100210000000000121019f0000000802000029068106770000040f00000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000005db0000613d0000000901000029000001bd0110009c000002170000213d0000000901000029000000400010043f0000000802000029000000050120014f000001b601100198000005f80000c13d000000060100002900000000001004350000000401000029000000200010043f000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001be011001c700008010020000390681067c0000040f00000001022001900000000f03000029000000400000613d000000000101043b000000000201041a000001d902200197000000000232019f000000000021041b000003af0000013d000300000001035500000000020100190000006002200270000101a20020019d000001a202200197000000400300043d0000001f0420018f00000005052002720000054e0000613d000000000600001900000005076002100000000008730019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005460000413d000000000604004b0000055d0000613d0000000505500210000000000151034f00000000055300190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000041d0000013d000001b6031001970000000101000039000000000201041a000001d902200197000000000232019f000000000021041b00000002010000390000000f02000029000000000021041b000001b9010000410000000000100439001000000003001d0000000400300443000001a2010000410000000002000414000001a20320009c0000000002018019000000c001200210000001ba011001c700008002020000390681067c0000040f00000001022001900000059c0000613d000000000101043b000000000101004b0000000e02000029000000400000613d000000400300043d000001ee010000410000000000130435000c00000003001d0000000401300039000000000021043500000000010004140000001002000029000000040220008c000005960000613d000001a202000041000001a20310009c00000000010280190000000c04000029000001a20340009c00000000020440190000004002200210000000c001100210000000000121019f000001ef011001c70000001002000029068106770000040f00000000030100190000006003300270000101a20030019d000001a20330019700030000000103550000000102200190000005be0000613d0000000c01000029000001bd0110009c000002170000213d0000000c01000029000000400010043f000003940000013d000000000001042f000000400200043d0000001f0430018f0000000505300272000005aa0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005a20000413d000000000604004b000005b90000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000000400100043d0000004402100039000001d603000041000004290000013d000000400200043d0000001f0430018f0000000505300272000005cb0000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005c30000413d000000000604004b000002800000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000000400200043d0000001f0430018f0000000505300272000005e80000613d000000000600001900000005076002100000000008720019000000000771034f000000000707043b00000000007804350000000106600039000000000756004b000005e00000413d000000000604004b000005f70000613d0000000505500210000000000151034f00000000055200190000000304400210000000000605043300000000064601cf000000000646022f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f0000000000150435000002800000013d000001a60100004100000009030000290000000000130435000000200100003900000002020000290000000000120435000000070100002900000003020000290000000000120435000001d80100004100000001020000290000000000120435000002bb0000013d0001000000000002000100000001001d0000000101000039000000000301041a000000400100043d00000040021000390000004004000039000000000042043500000060020000390000000002210436000001b603300197000000000032043500000060031000390000000000030435000001f60310009c000006580000813d0000008003100039000000400030043f000001a203000041000001a20420009c000000000203801900000040022002100000000001010433000001a20410009c00000000010380190000006001100210000000000121019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f00000001022001900000065e0000613d0000000202000039000000000202041a000000000301043b000000400100043d000000a0041000390000000000340435000000800310003900000000002304350000000102000029000001b602200197000000600310003900000000002304350000004002100039000000000300041000000000003204350000002002100039000001cb030000410000000000320435000000a0030000390000000000310435000001cc0310009c000006580000213d000000c003100039000000400030043f000001a203000041000001a20420009c000000000203801900000040022002100000000001010433000001a20410009c00000000010380190000006001100210000000000121019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f00000001022001900000065e0000613d000000000101043b000001b601100197000000000001042d000001f00100004100000000001004350000004101000039000000040010043f000001ef01000041000006830001043000000000010000190000068300010430000000000001042f000001a203000041000001a20410009c00000000010380190000004001100210000001a20420009c00000000020380190000006002200210000000000112019f0000000002000414000001a20420009c0000000002038019000000c002200210000000000112019f000001cd011001c700008010020000390681067c0000040f0000000102200190000006750000613d000000000101043b000000000001042d000000000100001900000683000104300000067a002104210000000102000039000000000001042d0000000002000019000000000001042d0000067f002104230000000102000039000000000001042d0000000002000019000000000001042d0000068100000432000006820001042e0000068300010430000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffff00000000000000000000000000000000000000000000000000000001ffffffe0616c697a696e6700000000000000000000000000000000000000000000000000496e697469616c697a61626c653a20636f6e747261637420697320696e69746908c379a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008400000000000000000000000002000000000000000000000000000000000000200000000000000000000000007f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498000000020000000000000000000000000000008000000100000000000000000000000000000000000000000000000000000000000000000000000000cfe7af7b00000000000000000000000000000000000000000000000000000000f54266a100000000000000000000000000000000000000000000000000000000f54266a200000000000000000000000000000000000000000000000000000000f5f1516800000000000000000000000000000000000000000000000000000000cfe7af7c00000000000000000000000000000000000000000000000000000000d9caed1200000000000000000000000000000000000000000000000000000000a31ee5af00000000000000000000000000000000000000000000000000000000a31ee5b000000000000000000000000000000000000000000000000000000000b852ad36000000000000000000000000000000000000000000000000000000006dde720900000000000000000000000000000000000000000000000000000000969b53da000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000200000008000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b83020000020000000000000000000000000000002400000000000000000000000074f4f547000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000044000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffff020000000000000000000000000000000000004000000000000000000000000011a2ccc100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7f62f84b24000000000000000000000000000000000000000000000000000000002fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b079680000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000064000000000000000000000000416d6f756e742063616e6e6f74206265207a65726f000000000000000000000000000000000000000000000000000000000000640000008000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000eeeeffffffffffffffffffffffffffffffffeeef6d710000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000060000000a000000000000000002020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494000000000000000000000000000000000000000000000000ffffffffffffff3f020000000000000000000000000000000000000000000000000000000000000067670000000000000000000000000000000000000000000000000000000000003cda335100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000ffffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000ffffffff000000000000000000000000000000000000000000000000ffffffff00000000000000000000000001000000000000000000000000000000000000000000000000000000000000006d6b00000000000000000000000000000000000000000000000000000000000095f11a40000000000000000000000000000000000000000000000000000000006d74000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff00000000000000000000000000000000000000008c2a993e00000000000000000000000000000000000000000000000000000000b84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f634f766572666c6f77000000000000000000000000000000000000000000000000496e697469616c697a61626c653a20636f6e747261637420697320616c726561647920696e697469616c697a65640000000000000000000000000000000000000000000000000000000000000000000000000084000000800000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000ffffffffffffffffffff0000000000000000000000000000000000000000010200000000000000000000ffffffffffffffffffffffffffffffffffffffff0000310ab089e4439a4c15d089f94afb7896ff553aecb10793d0ab882de59d99a32e02000002000000000000000000000000000000440000000000000000000000009a8a0592ac89c5ad3bc6df8224c17b485976f597df104ee20d0df415241f670b0200000200000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7c010004751688ab9322961547058fd0f36d3edf69880b64cbb2857041d33f4a133cda33511d41a8a5431b1770c5bc0ddd62e1cd30555d16659b89c0d60f4f9f570200000000000000000000000000000000000084000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff7b010000691fa4f751f8312bc555242f18ed78cdc9aabc0ea77d7d5a675ee8ac6f02000000000000000000000000000000000000a4000000000000000000000000f2fde38b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000004e487b7100000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff6266320000000000000000000000000000000000000000000000000000000000736600000000000000000000000000000000000000000000000000000000000064660000000000000000000000000000000000000000000000000000000000006266000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffff800000000000000000000000000000000000000000000000000000000000000000f5cf0be6820df44d868e986d4d5cafabd5702ac45d181a5ac4eb5ed59a001b03", - "linkReferences": {}, - "deployedLinkReferences": {}, - "factoryDeps": { - "0x010000691fa4f751f8312bc555242f18ed78cdc9aabc0ea77d7d5a675ee8ac6f": "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol:UpgradeableBeacon", - "0x010004751688ab9322961547058fd0f36d3edf69880b64cbb2857041d33f4a13": "contracts/bridge/L2StandardERC20.sol:L2StandardERC20" - } -} diff --git a/l1-contracts/script-config/artifacts/TransparentUpgradeableProxy.json b/l1-contracts/script-config/artifacts/TransparentUpgradeableProxy.json deleted file mode 100644 index c8880c120..000000000 --- a/l1-contracts/script-config/artifacts/TransparentUpgradeableProxy.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_format": "hh-zksolc-artifact-1", - "contractName": "TransparentUpgradeableProxy", - "sourceName": "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol", - "abi": [ - { - "inputs": [ - { - "internalType": "address", - "name": "_logic", - "type": "address" - }, - { - "internalType": "address", - "name": "admin_", - "type": "address" - }, - { - "internalType": "bytes", - "name": "_data", - "type": "bytes" - } - ], - "stateMutability": "payable", - "type": "constructor" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "previousAdmin", - "type": "address" - }, - { - "indexed": false, - "internalType": "address", - "name": "newAdmin", - "type": "address" - } - ], - "name": "AdminChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "beacon", - "type": "address" - } - ], - "name": "BeaconUpgraded", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "implementation", - "type": "address" - } - ], - "name": "Upgraded", - "type": "event" - }, - { - "stateMutability": "payable", - "type": "fallback" - }, - { - "stateMutability": "payable", - "type": "receive" - } - ], - "bytecode": "0x00020000000000020008000000000002000000000301001900000060033002700000012c0330019700010000003103550000008008000039000000400080043f00000001022001900000001e0000c13d000000000431034f00000000050004110000013d02000041000000000702041a0000013002700197000000000603004b000000270000c13d000000000325004b0000010c0000c13d000000000101043b0000014101100197000001420310009c0000001b0000613d000001430310009c000002c20000613d000001440310009c000002680000c13d00000000010004160000000001000019000004ac000104300000012d023000410000012e0220009c0000005f0000213d000001520100004100000000001004350000004101000039000000040010043f0000015301000041000004ac00010430000000000525004b0000012d0000c13d000000000401043b0000014104400197000001420540009c000001670000c13d0000000002000416000000000202004b000002c20000c13d000000240230008c000002c20000413d0000000401100370000000000201043b000001300120009c000002c20000213d000000a001000039000000400010043f000000800000043f00000133010000410000000000100439000800000002001d00000004002004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000002a80000c13d000000400100043d00000064021000390000015403000041000000000032043500000044021000390000015503000041000000000032043500000024021000390000002d0300003900000000003204350000013c0200004100000000002104350000000402100039000000200300003900000000003204350000012c020000410000012c0310009c000000000102801900000040011002100000014c011001c7000004ac000104300000009f023000390000012f02200197000000400020043f0000001f0230018f00000005043002720000006e0000613d00000000050000190000000506500210000000000761034f000000000707043b000000800660003900000000007604350000000105500039000000000645004b000000660000413d000000000502004b0000007d0000613d0000000504400210000000000141034f00000003022002100000008004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f00000000001404350000005f0130008c000002c20000a13d000000800900043d000001300190009c000002c20000213d000000a00700043d000001300170009c000002c20000213d000000c00200043d000001310120009c000002c20000213d0000001f012000390000013204000041000000000531004b000000000500001900000000050480190000013201100197000000000601004b0000000004008019000001320110009c000000000405c019000000000104004b000002c20000c13d00000080012000390000000001010433000001310410009c000000210000213d0000003f04100039000000200a00008a0000000004a4016f000000400b00043d00000000044b00190000000005b4004b00000000050000190000000105004039000001310640009c000000210000213d0000000105500190000000210000c13d0000008003300039000000400040043f00000000061b0436000000a0022000390000000004210019000000000334004b000002c20000213d00060000000b001d00050000000a001d000700000007001d000300000008001d000000000301004b000000b90000613d000000000300001900000000046300190000000005230019000000000505043300000000005404350000002003300039000000000413004b000000b20000413d000400000006001d0000000001160019000000000001043500000133010000410000000000100439000800000009001d00000004009004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000004a0000613d000000080100002900000130051001970000013501000041000000000201041a0000013602200197000000000252019f000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f0000000803000029000000010120019000000007020000290000000605000029000002c20000613d0000000001050433000000000101004b000003770000c13d0000013d01000041000000000301041a0000013004200197000000400100043d0000002002100039000800000004001d0000000000420435000700000003001d000001300230019700000000002104350000012c0200004100000000030004140000012c0430009c00000000030280190000012c0410009c00000000010280190000004001100210000000c002300210000000000112019f0000013e011001c70000800d0200003900000001030000390000013f0400004104aa049b0000040f0000000101200190000002c20000613d000000080100006b0000025a0000613d0000000701000029000001360110019700000008011001af0000013d02000041000000000012041b0000002001000039000001000010044300000120000004430000014001000041000004ab0001042e0000013501000041000000000201041a00000000010004140000013002200197000000040320008c000001e90000c13d00000000030000310000001f0230018f00000005013002720000011e0000613d00000000050000190000000506500210000000000764034f000000000707043b00000000007604350000000105500039000000000615004b000001170000413d000000000502004b0000020e0000613d00000003022002100000000501100210000000000501043300000000052501cf000000000525022f000000000414034f000000000404043b0000010002200089000000000424022f00000000022401cf000000000252019f00000000002104350000020e0000013d0000001f0530018f0000013502000041000000000202041a000001300220019700000005063002720000013b0000613d00000000070000190000000508700210000000000981034f000000000909043b00000000009804350000000107700039000000000867004b000001340000413d000000000705004b000001490000613d00000003055002100000000506600210000000000706043300000000075701cf000000000757022f000000000161034f000000000101043b0000010005500089000000000151022f00000000015101cf000000000171019f00000000001604350000000001000414000000040520008c0000020f0000c13d00000000030000310000001f0230018f0000000501300272000001580000613d00000000050000190000000506500210000000000764034f000000000707043b00000000007604350000000105500039000000000615004b000001510000413d000000000502004b000002360000613d00000003022002100000000501100210000000000501043300000000052501cf000000000525022f000000000414034f000000000404043b0000010002200089000000000424022f00000000022401cf000000000252019f0000000000210435000002360000013d000001430540009c0000023b0000c13d000000440230008c000002c20000413d0000000402100370000000000802043b000001300280009c000002c20000213d0000002402100370000000000402043b000001310240009c000002c20000213d00000023024000390000013205000041000000000632004b000000000600001900000000060580190000013202200197000000000702004b0000000005008019000001320220009c000000000506c019000000000205004b000002c20000c13d0000000405400039000000000251034f000000000202043b000001310620009c000000210000213d000000bf06200039000000200900008a000000000696016f000001310760009c000000210000213d000000400060043f000000800020043f00000000042400190000002404400039000000000334004b000002c20000213d0000002003500039000000000131034f0000001f0320018f00000005042002720000019d0000613d00000000050000190000000506500210000000000761034f000000000707043b000000a00660003900000000007604350000000105500039000000000645004b000001950000413d000700000009001d000000000503004b000001ad0000613d0000000504400210000000000141034f0000000303300210000000a004400039000000000504043300000000053501cf000000000535022f000000000101043b0000010003300089000000000131022f00000000013101cf000000000151019f0000000000140435000000a001200039000000000001043500000133010000410000000000100439000800000008001d00000004008004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000004a0000613d0000013501000041000000000201041a000001360220019700000008022001af0000000805000029000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f00000008030000290000000101200190000002c20000613d000000400100043d000600000001001d000001390110009c000000210000213d00000006040000290000006001400039000000400010043f00000040014000390000013a02000041000000000021043500000020014000390000013b02000041000000000021043500000027010000390000000000140435000000800200043d0000000001000414000000040330008c0000040d0000c13d000000010200003900000000040000310000041d0000013d0000012c030000410000012c0410009c0000000001038019000000c00110021004aa04a50000040f0001000000010355000000000301001900000060033002700000001f0430018f0000012c0030019d0000012c033001970000000505300272000001fe0000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000001f70000413d000000000604004b0000020c0000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000000101200190000002640000613d000002360000013d0000012c040000410000012c0510009c0000000001048019000000c0011002100000006003300210000000000131019f04aa04a50000040f0001000000010355000000000301001900000060033002700000001f0430018f0000012c0030019d0000012c033001970000000505300272000002260000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b0000021f0000413d000000000604004b000002340000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000000101200190000002660000613d0000012c010000410000012c0230009c00000000030180190000006001300210000004ab0001042e000001440540009c0000026e0000c13d0000000004000416000000000404004b000002c20000c13d000000240330008c000002c20000413d0000000401100370000000000401043b000001300140009c000002c20000213d000000800020043f000000a00040043f0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000148011001c70000800d020000390000000103000039000700000004001d0000013f04000041000800000007001d04aa049b0000040f000000070400002900000008030000290000000101200190000002c20000613d000000000104004b000002c40000c13d000000400100043d00000064021000390000014a03000041000000000032043500000044021000390000014b03000041000000000032043500000024021000390000002603000039000000530000013d0000006001300210000004ac000104300000006001300210000004ac00010430000001450310009c000002750000c13d0000000001000416000000000101004b000002c20000c13d0000027d0000013d000001450140009c000002840000c13d0000000001000416000000000101004b000002c20000c13d000000a00020043f0000028d0000013d000001460110009c0000029a0000c13d0000000001000416000000000101004b000002c20000c13d0000013501000041000000000101041a0000013002100197000000a00020043f0000002001000039000000800010043f000000c001000039000000400010043f0000015a01000041000004ab0001042e000001460140009c0000029a0000c13d0000000001000416000000000101004b000002c20000c13d0000013501000041000000000101041a0000013001100197000000a00010043f0000002001000039000000800010043f000000c001000039000000400010043f000000800100003900000147020000410000015003000041000001500410009c000000000103801900000040011002100000015101100041000000000121019f000004ab0001042e0000013c01000041000000800010043f0000002001000039000000840010043f0000004201000039000000a40010043f0000015601000041000000c40010043f0000015701000041000000e40010043f0000015801000041000001040010043f0000015901000041000004ac000104300000013501000041000000000201041a000001360220019700000008022001af0000000805000029000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f00000008080000290000000101200190000002c20000613d000000800100043d000000000101004b000002d00000c13d000000400100043d000001490210009c000000210000213d000002cb0000013d0000000001000019000004ac000104300000013601300197000000000114019f0000013d02000041000000000012041b000000400100043d000001490210009c000000210000213d0000002002100039000000400020043f00000000000104350000000002000019000002930000013d000000400900043d000001390190009c000000210000213d0000006001900039000000400010043f00000040019000390000013a02000041000000000021043500000020019000390000013b02000041000000000021043500000027010000390000000000190435000000800200043d0000000001000414000000040380008c000002e40000c13d00000001020000390000000004000031000002f70000013d0000012c030000410000012c0410009c00000000010380190000012c0420009c00000000020380190000006002200210000000c001100210000000000121019f0000014d011001c70000000002080019000700000009001d04aa04a50000040f00000007090000290000000808000029000000010220018f000100000001035500000060011002700000012c0010019d0000012c0410019700000060030000390000008001000039000000000504004b000003230000c13d0000000003030433000000000202004b000003530000c13d000000000203004b0000038c0000c13d000000400100043d0000013c0200004100000000002104350000000402100039000000200300003900000000003204350000000002090433000000240310003900000000002304350000004403100039000000000402004b000003140000613d000000000400001900000000053400190000002004400039000000000694001900000000060604330000000000650435000000000524004b0000030d0000413d0000001f04200039000000200500008a000000000454016f0000000002320019000000000002043500000044024000390000012c030000410000012c0420009c00000000020380190000012c0410009c000000000103801900000040011002100000006002200210000000000112019f000004ac00010430000001310140009c000000210000213d0000003f01400039000000200300008a000000000131016f000000400300043d0000000001130019000000000531004b00000000050000190000000105004039000001310610009c000000210000213d0000000105500190000000210000c13d000000000a090019000000400010043f0000001f0540018f000000000143043600000001060003670000000504400272000003410000613d000000000700001900000005087002100000000009810019000000000886034f000000000808043b00000000008904350000000107700039000000000847004b000003390000413d000000000705004b000000080800002900000000090a0019000002fb0000613d0000000504400210000000000646034f00000000044100190000000305500210000000000704043300000000075701cf000000000757022f000000000606043b0000010005500089000000000656022f00000000055601cf000000000575019f0000000000540435000002fb0000013d000000000103004b000002be0000c13d0000013301000041000000000010043900000004008004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000002be0000c13d000000400100043d00000044021000390000014e03000041000000000032043500000024021000390000001d0300003900000000003204350000013c0200004100000000002104350000000402100039000000200300003900000000003204350000012c020000410000012c0310009c000000000102801900000040011002100000014f011001c7000004ac00010430000000400400043d000001390140009c000000210000213d0000006001400039000000400010043f00000040014000390000013a0200004100000000002104350000002701000039000200000004001d00000000021404360000013b01000041000100000002001d000000000012043500000000020504330000000001000414000000040330008c000003950000c13d00000001020000390000000003000031000003a90000013d0000012c020000410000012c0430009c00000000030280190000012c0410009c000000000102801900000040011002100000006002300210000000000112019f000004ac000104300000012c0300004100000004050000290000012c0450009c000000000503801900000040045002100000012c0520009c00000000020380190000006002200210000000000242019f0000012c0410009c0000000001038019000000c001100210000000000112019f000000080200002904aa04a50000040f000000010220018f000100000001035500000060011002700000012c0010019d0000012c031001970000006001000039000000000403004b000003c90000c13d0000000001010433000000000202004b000003f70000c13d000000000201004b000004830000c13d000000400400043d000800000004001d0000013c01000041000000000014043500000004014000390000002002000039000000000021043500000002010000290000000003010433000700000003001d000000240140003900000000003104350000004402400039000000010100002904aa048d0000040f00000007010000290000001f01100039000000050110017f00000044011000390000012c020000410000012c0310009c00000000010280190000000804000029000004870000013d000001310130009c0000000504000029000000210000213d0000003f01300039000000000441016f000000400100043d0000000004410019000000000514004b00000000050000190000000105004039000001310640009c000000210000213d0000000105500190000000210000c13d000000400040043f0000001f0430018f000000000931043600000001050003670000000503300272000003e60000613d000000000600001900000005076002100000000008790019000000000775034f000000000707043b00000000007804350000000106600039000000000736004b000003de0000413d000300000009001d000000000604004b000003ac0000613d0000000503300210000000000535034f00000003033000290000000304400210000000000603043300000000064601cf000000000646022f000000000505043b0000010004400089000000000545022f00000000044501cf000000000464019f0000000000430435000003ac0000013d000000000101004b00000007020000290000000803000029000000e60000c13d0000013301000041000000000010043900000004003004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000000702000029000000e60000c13d000003650000013d0000012c030000410000012c0410009c00000000010380190000012c0420009c00000000020380190000006002200210000000c001100210000000000121019f0000014d011001c7000000080200002904aa04a50000040f000000010220018f000100000001035500000060011002700000012c0010019d0000012c0410019700000060030000390000008001000039000000000504004b0000043e0000c13d0000000003030433000000000202004b0000046b0000c13d000000000203004b0000038c0000c13d000000400100043d0000013c02000041000000000021043500000004021000390000002003000039000000000032043500000006070000290000000002070433000000240310003900000000002304350000004403100039000000000402004b0000043b0000613d000000000400001900000000053400190000002004400039000000000674001900000000060604330000000000650435000000000524004b000004340000413d0000001f042000390000000705000029000003160000013d000001310140009c0000000703000029000000210000213d0000003f01400039000000000131016f000000400300043d0000000001130019000000000531004b00000000050000190000000105004039000001310610009c000000210000213d0000000105500190000000210000c13d000000400010043f0000001f0540018f0000000001430436000000010600036700000005044002720000045b0000613d000000000700001900000005087002100000000009810019000000000886034f000000000808043b00000000008904350000000107700039000000000847004b000004530000413d000000000705004b000004210000613d0000000504400210000000000646034f00000000044100190000000305500210000000000704043300000000075701cf000000000757022f000000000606043b0000010005500089000000000656022f00000000055601cf000000000575019f0000000000540435000004210000013d000000000103004b0000047e0000c13d00000133010000410000000000100439000000080100002900000004001004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000003650000613d000000400100043d000001490210009c000000210000213d000002cb0000013d000000000001042f0000012c020000410000012c0310009c000000000102801900000003040000290000012c0340009c000000000402801900000040024002100000006001100210000000000121019f000004ac00010430000000000403004b000004970000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000004900000413d00000000012300190000000000010435000000000001042d000000000001042f0000049e002104210000000102000039000000000001042d0000000002000019000000000001042d000004a3002104230000000102000039000000000001042d0000000002000019000000000001042d000004a8002104250000000102000039000000000001042d0000000002000019000000000001042d000004aa00000432000004ab0001042e000004ac0001043000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000009fffffffffffffffffffffffffffffffffffffffffffffffff000000000000007f00000000000000000000000000000000000000000000000000000001ffffffe0000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000ffffffffffffffff80000000000000000000000000000000000000000000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200000200000000000000000000000000000024000000000000000000000000360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcffffffffffffffffffffffff00000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000bc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b000000000000000000000000000000000000000000000000ffffffffffffff9f206661696c656400000000000000000000000000000000000000000000000000416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c08c379a000000000000000000000000000000000000000000000000000000000b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d610302000000000000000000000000000000000000400000000000000000000000007e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f0000000200000000000000000000000000000040000001000000000000000000ffffffff000000000000000000000000000000000000000000000000000000003659cfe6000000000000000000000000000000000000000000000000000000004f1ef286000000000000000000000000000000000000000000000000000000008f28397000000000000000000000000000000000000000000000000000000000f851a440000000000000000000000000000000000000000000000000000000005c60da1b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000200000000000000000000000000000000000040000000800000000000000000000000000000000000000000000000000000000000000000ffffffffffffffdf6464726573730000000000000000000000000000000000000000000000000000455243313936373a206e65772061646d696e20697320746865207a65726f206100000000000000000000000000000000000000840000000000000000000000000000000000000000000000000000000000000000000000a00000000000000000416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffdf00000000000000000000000000000000000000000000002000000000000000004e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000006f74206120636f6e747261637400000000000000000000000000000000000000455243313936373a206e657720696d706c656d656e746174696f6e206973206e5472616e73706172656e745570677261646561626c6550726f78793a2061646d696e2063616e6e6f742066616c6c6261636b20746f2070726f78792074617267657400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a40000008000000000000000000000000000000000000000000000000000000020000000a0000000000000000000000000000000000000000000000000000000000000000000000000000000007444ff0b02dc9864c7dbf97ccd7719c286d6972190eeb0285ea9e04a713977c0", - "deployedBytecode": "0x00020000000000020008000000000002000000000301001900000060033002700000012c0330019700010000003103550000008008000039000000400080043f00000001022001900000001e0000c13d000000000431034f00000000050004110000013d02000041000000000702041a0000013002700197000000000603004b000000270000c13d000000000325004b0000010c0000c13d000000000101043b0000014101100197000001420310009c0000001b0000613d000001430310009c000002c20000613d000001440310009c000002680000c13d00000000010004160000000001000019000004ac000104300000012d023000410000012e0220009c0000005f0000213d000001520100004100000000001004350000004101000039000000040010043f0000015301000041000004ac00010430000000000525004b0000012d0000c13d000000000401043b0000014104400197000001420540009c000001670000c13d0000000002000416000000000202004b000002c20000c13d000000240230008c000002c20000413d0000000401100370000000000201043b000001300120009c000002c20000213d000000a001000039000000400010043f000000800000043f00000133010000410000000000100439000800000002001d00000004002004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000002a80000c13d000000400100043d00000064021000390000015403000041000000000032043500000044021000390000015503000041000000000032043500000024021000390000002d0300003900000000003204350000013c0200004100000000002104350000000402100039000000200300003900000000003204350000012c020000410000012c0310009c000000000102801900000040011002100000014c011001c7000004ac000104300000009f023000390000012f02200197000000400020043f0000001f0230018f00000005043002720000006e0000613d00000000050000190000000506500210000000000761034f000000000707043b000000800660003900000000007604350000000105500039000000000645004b000000660000413d000000000502004b0000007d0000613d0000000504400210000000000141034f00000003022002100000008004400039000000000504043300000000052501cf000000000525022f000000000101043b0000010002200089000000000121022f00000000012101cf000000000151019f00000000001404350000005f0130008c000002c20000a13d000000800900043d000001300190009c000002c20000213d000000a00700043d000001300170009c000002c20000213d000000c00200043d000001310120009c000002c20000213d0000001f012000390000013204000041000000000531004b000000000500001900000000050480190000013201100197000000000601004b0000000004008019000001320110009c000000000405c019000000000104004b000002c20000c13d00000080012000390000000001010433000001310410009c000000210000213d0000003f04100039000000200a00008a0000000004a4016f000000400b00043d00000000044b00190000000005b4004b00000000050000190000000105004039000001310640009c000000210000213d0000000105500190000000210000c13d0000008003300039000000400040043f00000000061b0436000000a0022000390000000004210019000000000334004b000002c20000213d00060000000b001d00050000000a001d000700000007001d000300000008001d000000000301004b000000b90000613d000000000300001900000000046300190000000005230019000000000505043300000000005404350000002003300039000000000413004b000000b20000413d000400000006001d0000000001160019000000000001043500000133010000410000000000100439000800000009001d00000004009004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000004a0000613d000000080100002900000130051001970000013501000041000000000201041a0000013602200197000000000252019f000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f0000000803000029000000010120019000000007020000290000000605000029000002c20000613d0000000001050433000000000101004b000003770000c13d0000013d01000041000000000301041a0000013004200197000000400100043d0000002002100039000800000004001d0000000000420435000700000003001d000001300230019700000000002104350000012c0200004100000000030004140000012c0430009c00000000030280190000012c0410009c00000000010280190000004001100210000000c002300210000000000112019f0000013e011001c70000800d0200003900000001030000390000013f0400004104aa049b0000040f0000000101200190000002c20000613d000000080100006b0000025a0000613d0000000701000029000001360110019700000008011001af0000013d02000041000000000012041b0000002001000039000001000010044300000120000004430000014001000041000004ab0001042e0000013501000041000000000201041a00000000010004140000013002200197000000040320008c000001e90000c13d00000000030000310000001f0230018f00000005013002720000011e0000613d00000000050000190000000506500210000000000764034f000000000707043b00000000007604350000000105500039000000000615004b000001170000413d000000000502004b0000020e0000613d00000003022002100000000501100210000000000501043300000000052501cf000000000525022f000000000414034f000000000404043b0000010002200089000000000424022f00000000022401cf000000000252019f00000000002104350000020e0000013d0000001f0530018f0000013502000041000000000202041a000001300220019700000005063002720000013b0000613d00000000070000190000000508700210000000000981034f000000000909043b00000000009804350000000107700039000000000867004b000001340000413d000000000705004b000001490000613d00000003055002100000000506600210000000000706043300000000075701cf000000000757022f000000000161034f000000000101043b0000010005500089000000000151022f00000000015101cf000000000171019f00000000001604350000000001000414000000040520008c0000020f0000c13d00000000030000310000001f0230018f0000000501300272000001580000613d00000000050000190000000506500210000000000764034f000000000707043b00000000007604350000000105500039000000000615004b000001510000413d000000000502004b000002360000613d00000003022002100000000501100210000000000501043300000000052501cf000000000525022f000000000414034f000000000404043b0000010002200089000000000424022f00000000022401cf000000000252019f0000000000210435000002360000013d000001430540009c0000023b0000c13d000000440230008c000002c20000413d0000000402100370000000000802043b000001300280009c000002c20000213d0000002402100370000000000402043b000001310240009c000002c20000213d00000023024000390000013205000041000000000632004b000000000600001900000000060580190000013202200197000000000702004b0000000005008019000001320220009c000000000506c019000000000205004b000002c20000c13d0000000405400039000000000251034f000000000202043b000001310620009c000000210000213d000000bf06200039000000200900008a000000000696016f000001310760009c000000210000213d000000400060043f000000800020043f00000000042400190000002404400039000000000334004b000002c20000213d0000002003500039000000000131034f0000001f0320018f00000005042002720000019d0000613d00000000050000190000000506500210000000000761034f000000000707043b000000a00660003900000000007604350000000105500039000000000645004b000001950000413d000700000009001d000000000503004b000001ad0000613d0000000504400210000000000141034f0000000303300210000000a004400039000000000504043300000000053501cf000000000535022f000000000101043b0000010003300089000000000131022f00000000013101cf000000000151019f0000000000140435000000a001200039000000000001043500000133010000410000000000100439000800000008001d00000004008004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000004a0000613d0000013501000041000000000201041a000001360220019700000008022001af0000000805000029000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f00000008030000290000000101200190000002c20000613d000000400100043d000600000001001d000001390110009c000000210000213d00000006040000290000006001400039000000400010043f00000040014000390000013a02000041000000000021043500000020014000390000013b02000041000000000021043500000027010000390000000000140435000000800200043d0000000001000414000000040330008c0000040d0000c13d000000010200003900000000040000310000041d0000013d0000012c030000410000012c0410009c0000000001038019000000c00110021004aa04a50000040f0001000000010355000000000301001900000060033002700000001f0430018f0000012c0030019d0000012c033001970000000505300272000001fe0000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b000001f70000413d000000000604004b0000020c0000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000000101200190000002640000613d000002360000013d0000012c040000410000012c0510009c0000000001048019000000c0011002100000006003300210000000000131019f04aa04a50000040f0001000000010355000000000301001900000060033002700000001f0430018f0000012c0030019d0000012c033001970000000505300272000002260000613d00000000060000190000000507600210000000000871034f000000000808043b00000000008704350000000106600039000000000756004b0000021f0000413d000000000604004b000002340000613d00000003044002100000000505500210000000000605043300000000064601cf000000000646022f000000000151034f000000000101043b0000010004400089000000000141022f00000000014101cf000000000161019f00000000001504350000000101200190000002660000613d0000012c010000410000012c0230009c00000000030180190000006001300210000004ab0001042e000001440540009c0000026e0000c13d0000000004000416000000000404004b000002c20000c13d000000240330008c000002c20000413d0000000401100370000000000401043b000001300140009c000002c20000213d000000800020043f000000a00040043f0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000148011001c70000800d020000390000000103000039000700000004001d0000013f04000041000800000007001d04aa049b0000040f000000070400002900000008030000290000000101200190000002c20000613d000000000104004b000002c40000c13d000000400100043d00000064021000390000014a03000041000000000032043500000044021000390000014b03000041000000000032043500000024021000390000002603000039000000530000013d0000006001300210000004ac000104300000006001300210000004ac00010430000001450310009c000002750000c13d0000000001000416000000000101004b000002c20000c13d0000027d0000013d000001450140009c000002840000c13d0000000001000416000000000101004b000002c20000c13d000000a00020043f0000028d0000013d000001460110009c0000029a0000c13d0000000001000416000000000101004b000002c20000c13d0000013501000041000000000101041a0000013002100197000000a00020043f0000002001000039000000800010043f000000c001000039000000400010043f0000015a01000041000004ab0001042e000001460140009c0000029a0000c13d0000000001000416000000000101004b000002c20000c13d0000013501000041000000000101041a0000013001100197000000a00010043f0000002001000039000000800010043f000000c001000039000000400010043f000000800100003900000147020000410000015003000041000001500410009c000000000103801900000040011002100000015101100041000000000121019f000004ab0001042e0000013c01000041000000800010043f0000002001000039000000840010043f0000004201000039000000a40010043f0000015601000041000000c40010043f0000015701000041000000e40010043f0000015801000041000001040010043f0000015901000041000004ac000104300000013501000041000000000201041a000001360220019700000008022001af0000000805000029000000000021041b0000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000137011001c70000800d020000390000000203000039000001380400004104aa049b0000040f00000008080000290000000101200190000002c20000613d000000800100043d000000000101004b000002d00000c13d000000400100043d000001490210009c000000210000213d000002cb0000013d0000000001000019000004ac000104300000013601300197000000000114019f0000013d02000041000000000012041b000000400100043d000001490210009c000000210000213d0000002002100039000000400020043f00000000000104350000000002000019000002930000013d000000400900043d000001390190009c000000210000213d0000006001900039000000400010043f00000040019000390000013a02000041000000000021043500000020019000390000013b02000041000000000021043500000027010000390000000000190435000000800200043d0000000001000414000000040380008c000002e40000c13d00000001020000390000000004000031000002f70000013d0000012c030000410000012c0410009c00000000010380190000012c0420009c00000000020380190000006002200210000000c001100210000000000121019f0000014d011001c70000000002080019000700000009001d04aa04a50000040f00000007090000290000000808000029000000010220018f000100000001035500000060011002700000012c0010019d0000012c0410019700000060030000390000008001000039000000000504004b000003230000c13d0000000003030433000000000202004b000003530000c13d000000000203004b0000038c0000c13d000000400100043d0000013c0200004100000000002104350000000402100039000000200300003900000000003204350000000002090433000000240310003900000000002304350000004403100039000000000402004b000003140000613d000000000400001900000000053400190000002004400039000000000694001900000000060604330000000000650435000000000524004b0000030d0000413d0000001f04200039000000200500008a000000000454016f0000000002320019000000000002043500000044024000390000012c030000410000012c0420009c00000000020380190000012c0410009c000000000103801900000040011002100000006002200210000000000112019f000004ac00010430000001310140009c000000210000213d0000003f01400039000000200300008a000000000131016f000000400300043d0000000001130019000000000531004b00000000050000190000000105004039000001310610009c000000210000213d0000000105500190000000210000c13d000000000a090019000000400010043f0000001f0540018f000000000143043600000001060003670000000504400272000003410000613d000000000700001900000005087002100000000009810019000000000886034f000000000808043b00000000008904350000000107700039000000000847004b000003390000413d000000000705004b000000080800002900000000090a0019000002fb0000613d0000000504400210000000000646034f00000000044100190000000305500210000000000704043300000000075701cf000000000757022f000000000606043b0000010005500089000000000656022f00000000055601cf000000000575019f0000000000540435000002fb0000013d000000000103004b000002be0000c13d0000013301000041000000000010043900000004008004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000002be0000c13d000000400100043d00000044021000390000014e03000041000000000032043500000024021000390000001d0300003900000000003204350000013c0200004100000000002104350000000402100039000000200300003900000000003204350000012c020000410000012c0310009c000000000102801900000040011002100000014f011001c7000004ac00010430000000400400043d000001390140009c000000210000213d0000006001400039000000400010043f00000040014000390000013a0200004100000000002104350000002701000039000200000004001d00000000021404360000013b01000041000100000002001d000000000012043500000000020504330000000001000414000000040330008c000003950000c13d00000001020000390000000003000031000003a90000013d0000012c020000410000012c0430009c00000000030280190000012c0410009c000000000102801900000040011002100000006002300210000000000112019f000004ac000104300000012c0300004100000004050000290000012c0450009c000000000503801900000040045002100000012c0520009c00000000020380190000006002200210000000000242019f0000012c0410009c0000000001038019000000c001100210000000000112019f000000080200002904aa04a50000040f000000010220018f000100000001035500000060011002700000012c0010019d0000012c031001970000006001000039000000000403004b000003c90000c13d0000000001010433000000000202004b000003f70000c13d000000000201004b000004830000c13d000000400400043d000800000004001d0000013c01000041000000000014043500000004014000390000002002000039000000000021043500000002010000290000000003010433000700000003001d000000240140003900000000003104350000004402400039000000010100002904aa048d0000040f00000007010000290000001f01100039000000050110017f00000044011000390000012c020000410000012c0310009c00000000010280190000000804000029000004870000013d000001310130009c0000000504000029000000210000213d0000003f01300039000000000441016f000000400100043d0000000004410019000000000514004b00000000050000190000000105004039000001310640009c000000210000213d0000000105500190000000210000c13d000000400040043f0000001f0430018f000000000931043600000001050003670000000503300272000003e60000613d000000000600001900000005076002100000000008790019000000000775034f000000000707043b00000000007804350000000106600039000000000736004b000003de0000413d000300000009001d000000000604004b000003ac0000613d0000000503300210000000000535034f00000003033000290000000304400210000000000603043300000000064601cf000000000646022f000000000505043b0000010004400089000000000545022f00000000044501cf000000000464019f0000000000430435000003ac0000013d000000000101004b00000007020000290000000803000029000000e60000c13d0000013301000041000000000010043900000004003004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b0000000702000029000000e60000c13d000003650000013d0000012c030000410000012c0410009c00000000010380190000012c0420009c00000000020380190000006002200210000000c001100210000000000121019f0000014d011001c7000000080200002904aa04a50000040f000000010220018f000100000001035500000060011002700000012c0010019d0000012c0410019700000060030000390000008001000039000000000504004b0000043e0000c13d0000000003030433000000000202004b0000046b0000c13d000000000203004b0000038c0000c13d000000400100043d0000013c02000041000000000021043500000004021000390000002003000039000000000032043500000006070000290000000002070433000000240310003900000000002304350000004403100039000000000402004b0000043b0000613d000000000400001900000000053400190000002004400039000000000674001900000000060604330000000000650435000000000524004b000004340000413d0000001f042000390000000705000029000003160000013d000001310140009c0000000703000029000000210000213d0000003f01400039000000000131016f000000400300043d0000000001130019000000000531004b00000000050000190000000105004039000001310610009c000000210000213d0000000105500190000000210000c13d000000400010043f0000001f0540018f0000000001430436000000010600036700000005044002720000045b0000613d000000000700001900000005087002100000000009810019000000000886034f000000000808043b00000000008904350000000107700039000000000847004b000004530000413d000000000705004b000004210000613d0000000504400210000000000646034f00000000044100190000000305500210000000000704043300000000075701cf000000000757022f000000000606043b0000010005500089000000000656022f00000000055601cf000000000575019f0000000000540435000004210000013d000000000103004b0000047e0000c13d00000133010000410000000000100439000000080100002900000004001004430000012c0100004100000000020004140000012c0320009c0000000002018019000000c00120021000000134011001c7000080020200003904aa04a00000040f0000000102200190000004820000613d000000000101043b000000000101004b000003650000613d000000400100043d000001490210009c000000210000213d000002cb0000013d000000000001042f0000012c020000410000012c0310009c000000000102801900000003040000290000012c0340009c000000000402801900000040024002100000006001100210000000000121019f000004ac00010430000000000403004b000004970000613d000000000400001900000000052400190000000006140019000000000606043300000000006504350000002004400039000000000534004b000004900000413d00000000012300190000000000010435000000000001042d000000000001042f0000049e002104210000000102000039000000000001042d0000000002000019000000000001042d000004a3002104230000000102000039000000000001042d0000000002000019000000000001042d000004a8002104250000000102000039000000000001042d0000000002000019000000000001042d000004aa00000432000004ab0001042e000004ac0001043000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000009fffffffffffffffffffffffffffffffffffffffffffffffff000000000000007f00000000000000000000000000000000000000000000000000000001ffffffe0000000000000000000000000ffffffffffffffffffffffffffffffffffffffff000000000000000000000000000000000000000000000000ffffffffffffffff80000000000000000000000000000000000000000000000000000000000000001806aa1896bbf26568e884a7374b41e002500962caba6a15023a8d90e8508b830200000200000000000000000000000000000024000000000000000000000000360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbcffffffffffffffffffffffff00000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000bc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b000000000000000000000000000000000000000000000000ffffffffffffff9f206661696c656400000000000000000000000000000000000000000000000000416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c08c379a000000000000000000000000000000000000000000000000000000000b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d610302000000000000000000000000000000000000400000000000000000000000007e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f0000000200000000000000000000000000000040000001000000000000000000ffffffff000000000000000000000000000000000000000000000000000000003659cfe6000000000000000000000000000000000000000000000000000000004f1ef286000000000000000000000000000000000000000000000000000000008f28397000000000000000000000000000000000000000000000000000000000f851a440000000000000000000000000000000000000000000000000000000005c60da1b0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000200000000000000000000000000000000000040000000800000000000000000000000000000000000000000000000000000000000000000ffffffffffffffdf6464726573730000000000000000000000000000000000000000000000000000455243313936373a206e65772061646d696e20697320746865207a65726f206100000000000000000000000000000000000000840000000000000000000000000000000000000000000000000000000000000000000000a00000000000000000416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffdf00000000000000000000000000000000000000000000002000000000000000004e487b710000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000240000000000000000000000006f74206120636f6e747261637400000000000000000000000000000000000000455243313936373a206e657720696d706c656d656e746174696f6e206973206e5472616e73706172656e745570677261646561626c6550726f78793a2061646d696e2063616e6e6f742066616c6c6261636b20746f2070726f78792074617267657400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a40000008000000000000000000000000000000000000000000000000000000020000000a0000000000000000000000000000000000000000000000000000000000000000000000000000000007444ff0b02dc9864c7dbf97ccd7719c286d6972190eeb0285ea9e04a713977c0", - "linkReferences": {}, - "deployedLinkReferences": {}, - "factoryDeps": {} -} diff --git a/l1-contracts/scripts/errors-lint.ts b/l1-contracts/scripts/errors-lint.ts new file mode 100644 index 000000000..9c34444b7 --- /dev/null +++ b/l1-contracts/scripts/errors-lint.ts @@ -0,0 +1,220 @@ +import { Command } from "commander"; +import * as fs from "fs"; +import * as path from "path"; +import { ethers } from "ethers"; + +// Constant arrays +const FILES_WITH_CUSTOM_ERRORS = [ + "contracts/common/L1ContractErrors.sol", + "contracts/bridge/L1BridgeContractErrors.sol", + "contracts/bridgehub/L1BridgehubErrors.sol", + "contracts/state-transition/L1StateTransitionErrors.sol", + "contracts/upgrades/ZkSyncUpgradeErrors.sol", + "deploy-scripts/ZkSyncScriptErrors.sol", + "../l2-contracts/contracts/errors/L2ContractErrors.sol", + "../system-contracts/contracts/SystemContractErrors.sol", + "../da-contracts/contracts/DAContractsErrors.sol", +]; // Replace with your file paths +const CONTRACTS_DIRECTORIES = [ + "contracts", + "deploy-scripts", + "test/foundry", + "../l2-contracts/contracts", + "../system-contracts/contracts", + "../da-contracts/contracts", +]; // Replace with your directories + +// Function to extract the error signature +function getErrorSignature(errorString: string): string { + errorString = errorString.trim(); + const parenIndex = errorString.indexOf("("); + + if (parenIndex === -1) { + throw new Error("No '(' in error"); + } else { + const errorName = errorString.substring(0, parenIndex).trim(); + const paramsString = errorString.substring(parenIndex + 1, errorString.lastIndexOf(")")).trim(); + + const params = paramsString + .split(",") + .map((param) => { + const typeMatch = param.trim().match(/^(\w+(\[\])*)\s*(\w*)$/); + if (typeMatch) { + return typeMatch[1]; + } else { + return ""; + } + }) + .filter((paramType) => paramType !== ""); + + return `${errorName}(${params.join(",")})`; + } +} + +// Function to process each file +function processFile(filePath: string, fix: boolean, collectedErrors: Set): boolean { + const fileContent = fs.readFileSync(filePath, "utf8"); + const lines = fileContent.split(/\r?\n/); + let modified = false; + const newLines = []; + let lineNumber = 0; + + while (lineNumber < lines.length) { + const line = lines[lineNumber]; + const errorMatch = line.match(/^\s*error\s+(.+);\s*$/); + + if (errorMatch) { + const errorString = errorMatch[1].trim(); + + // Get the error signature + const signature = getErrorSignature(errorString); + + const errorName = signature.substring(0, signature.indexOf("(")); + collectedErrors.add(errorName); + + // Calculate the selector + const hash = ethers.utils.id(signature); + const selector = hash.substring(0, 10); + + // Check the line above + const previousLine = newLines[newLines.length - 1]; + const selectorComment = `// ${selector}`; + + if (!previousLine || previousLine.trim() !== selectorComment) { + if (fix) { + // We allow fixing incorrect signature + if (previousLine.startsWith("//")) { + newLines[newLines.length - 1] = selectorComment; + } else { + // Insert the selector line + newLines.push(selectorComment); + } + modified = true; + } else { + throw new Error(`Missing selector comment above error at ${filePath}:${lineNumber + 1}`); + } + } + // Push the current line + newLines.push(line); + } else { + // Not an error line, just copy + newLines.push(line); + } + lineNumber++; + } + + if (fix && modified) { + // Write back to file + const newContent = newLines.join("\n"); + fs.writeFileSync(filePath, newContent, "utf8"); + } + + return modified; +} + +// Recursively collects all custom error usages from the given contract directories.s +function collectErrorUsages(directories: string[], usedErrors: Set) { + // Iterate over each directory provided in the directories array + for (const dir of directories) { + // Resolve the directory path to an absolute path + const absoluteDir = path.resolve(dir); + + // Check if the directory exists and is indeed a directory + if (fs.existsSync(absoluteDir) && fs.lstatSync(absoluteDir).isDirectory()) { + // Read all entries (files and subdirectories) within the directory + const files = fs.readdirSync(absoluteDir); + + // Iterate over each entry in the directory + for (const file of files) { + // Construct the full path of the current entry + const fullPath = path.join(absoluteDir, file); + + // Check if the current entry is a directory + if (fs.lstatSync(fullPath).isDirectory()) { + // If it is a directory, recursively call collectErrorUsages on this subdirectory + collectErrorUsages([fullPath], usedErrors); + } + // Check if the current entry is a Solidity file (ends with .sol) + else if (file.endsWith(".sol")) { + // Read the content of the Solidity file as a string + const fileContent = fs.readFileSync(fullPath, "utf8"); + + // Regular expression to match 'revert ' patterns in the file + const revertRegex = /revert\s+([A-Za-z0-9_]+)/g; + + let match; + // Use a loop to find all matches of the pattern in the file content + while ((match = revertRegex.exec(fileContent)) !== null) { + // match[1] contains the captured error name after 'revert' + const errorName = match[1]; + // Add the error name to the usedErrors set + usedErrors.add(errorName); + } + } + // If the entry is neither a directory nor a Solidity file, it is ignored + } + } + // If the path does not exist or is not a directory, it is ignored + } +} + +async function main() { + // Initialize the command parser + const program = new Command(); + + program + .option("--fix", "Fix the errors by inserting missing selectors") + .option("--check", "Check if the selectors are present without modifying files") + .parse(process.argv); + + const options = program.opts(); + + // Validate arguments + if ((!options.fix && !options.check) || (options.fix && options.check)) { + console.error("Error: You must provide either --fix or --check, but not both."); + process.exit(1); + } + + // Main execution + let hasErrors = false; + const declaredErrors = new Set(); + const usedErrors = new Set(); + + for (const filePath of FILES_WITH_CUSTOM_ERRORS) { + const absolutePath = path.resolve(filePath); + const result = processFile(absolutePath, options.fix, declaredErrors); + + if (result && options.check) { + hasErrors = true; + } + } + + if (options.check && hasErrors) { + console.error("Some errors were found."); + process.exit(1); + } + + if (options.check) { + collectErrorUsages(CONTRACTS_DIRECTORIES, usedErrors); + + // Find declared errors that are never used + const unusedErrors = [...declaredErrors].filter((error) => !usedErrors.has(error)); + + if (unusedErrors.length > 0) { + for (const error of unusedErrors) { + console.error(`Error "${error}" is declared but never used.`); + } + process.exit(1); + } + } + + if (options.check && !hasErrors) { + console.log("All files are correct."); + } + + if (options.fix) { + console.log("All files have been processed and fixed."); + } +} + +main(); diff --git a/l1-contracts/selectors b/l1-contracts/selectors new file mode 100644 index 000000000..1fecf6de9 --- /dev/null +++ b/l1-contracts/selectors @@ -0,0 +1,6096 @@ +Listing selectors for contracts in the project... +IAssetRouterBase ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ + +IL1AssetRouter ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_WETH_TOKEN() | 0x41c841c3 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes) | 0x1346ca3b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes,bytes32,uint256,uint256,uint16,bytes32[]) | 0x3601e63e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2Transaction(uint256,bytes32,bytes32) | 0x8eb7db57 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDeposit(uint256,address,uint256,bytes) | 0xca408c23 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDepositBaseToken(uint256,bytes32,address,uint256) | 0xc4879440 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositLegacyErc20Bridge(address,address,address,uint256,uint256,uint256,address) | 0x9e6ea417 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint256,uint16,bytes,bytes32[]) | 0xc87325f1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getDepositCalldata(address,bytes32,bytes) | 0x2ff0b2ea | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256,uint256) | 0x8f31f052 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetDeploymentTracker(bytes32,address) | 0xc0a16dda | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNativeTokenVault(address) | 0x0f3fa211 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferFundsToNTV(bytes32,uint256,address) | 0x57d4ca5c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetDeploymentTrackerSet(bytes32,address,bytes32) | 0x14c1bae9bcc3777747463b66a36584aa75e4ded1aa38089f447beecb125a2175 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositFinalized(uint256,bytes32,bytes32) | 0xe4def01b981193a97a9e81230d7b9f31812ceaf23f864a828a82c687911cb2df | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubMintData(bytes) | 0x31a15cb4f69820f57afabeaff74feae31dc25875c07c952ba742a3acf8690f91 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDepositAssetRouter(uint256,bytes32,bytes) | 0x4250817d22c13fba8067153d85ccd9706326ac2bd14d5c3898c8b1bccc440658 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | LegacyDepositInitiated(uint256,bytes32,address,address,address,uint256) | 0xa1846a4248529db592da99da276f761d9f37a84d0f3d4e83819b869759000700 | ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IL2AssetRouter ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDepositLegacyBridge(address,address,address,uint256,bytes) | 0x54b2e69c | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1AssetRouter() | 0x6d9860e1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddress(uint256,bytes32,address) | 0xda556bdc | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(bytes32,bytes) | 0x4a2e35ba | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdrawLegacyBridge(address,address,uint256,address) | 0x7ac3a553 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiatedAssetRouter(uint256,address,bytes32,bytes) | 0x55362fc62473cb1255e770af5d5e02ba6ee5bc7ed6969c30eb11ca31b92384dc | ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ + +IAssetHandler ++----------+-----------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================+ +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | ++----------+-----------------------------------------------------+--------------------------------------------------------------------+ + +IBridgedStandardToken ++----------+-----------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================+ +| Function | assetId() | 0x44de240a | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(address,uint256) | 0x74f4f547 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(address,uint256) | 0x8c2a993e | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | l1Address() | 0xc2eeeebd | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | originToken() | 0x13096a41 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(address,uint256) | 0x9b5b9a05e4726d8bb959f1440e05c6b8109443f2083bc4e386237d7654526553 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | ++----------+-----------------------------------------------+--------------------------------------------------------------------+ + +IL1AssetDeploymentTracker ++----------+----------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================================+ +| Function | bridgeCheckCounterpartAddress(uint256,bytes32,address,address) | 0x9cc395d0 | ++----------+----------------------------------------------------------------+------------+ + +IL1AssetHandler ++----------+------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================================+ +| Function | bridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xc2e90293 | ++----------+------------------------------------------------------------+------------+ + +IL1BaseTokenAssetHandler ++----------+-----------------------+------------+ +| Type | Signature | Selector | ++===============================================+ +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | ++----------+-----------------------+------------+ + +IL1ERC20Bridge ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==============================================================================================================================================================+ +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NATIVE_TOKEN_VAULT() | 0x293e8520 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(address,address,bytes32,uint256,uint256,uint16,bytes32[]) | 0x19fa7f62 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256) | 0x933999fb | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256,address) | 0xe8b99b1b | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositAmount(address,address,bytes32) | 0x01eae183 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x11a2ccc1 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256) | 0x4bed8212 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDeposit(address,address,uint256) | 0xbe066dc591f4a444f75176d387c3e6c775e5706d9ea9a91d11eb49030c66cf60 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositInitiated(bytes32,address,address,address,uint256) | 0xdd341179f4edc78148d894d0213a96d212af2cbaf223d19ef6d483bdd47ab81d | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalFinalized(address,address,uint256) | 0xac1b18083978656d557d6e91c88203585cfda1031bdb14538327121ef140d383 | ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IL1Nullifier ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes,bytes32,uint256,uint256,uint16,bytes32[]) | 0x3601e63e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2TransactionForwarded(uint256,bytes32,bytes32) | 0x4bc2c8c0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,address) | 0x9cd45184 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(uint256,address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0xc0991525 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDepositLegacyErc20Bridge(address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0x8fbb3711 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositHappened(uint256,bytes32) | 0x9fa8826b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit((uint256,uint256,uint256,address,uint16,bytes,bytes32[])) | 0x74beea82 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256,uint256) | 0x8f31f052 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1NativeTokenVault() | 0x6f513211 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | legacyBridge() | 0x6e9d7899 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nullifyChainBalanceByNTV(uint256,address) | 0x5de097b1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1AssetRouter(address) | 0x780ce114 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1NativeTokenVault(address) | 0xb7cc6f46 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferTokenToNTV(address) | 0x40a434d5 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositFinalized(uint256,bytes32,bytes32) | 0xe4def01b981193a97a9e81230d7b9f31812ceaf23f864a828a82c687911cb2df | ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IL1SharedBridgeLegacy ++----------+--------------------------+------------+ +| Type | Signature | Selector | ++==================================================+ +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | ++----------+--------------------------+------------+ + +IL2Bridge ++----------+-----------------------------------------+------------+ +| Type | Signature | Selector | ++=================================================================+ +| Function | finalizeDeposit(bytes32,bytes) | 0xca65fe79 | +|----------+-----------------------------------------+------------| +| Function | l1Bridge() | 0x969b53da | +|----------+-----------------------------------------+------------| +| Function | setAssetHandlerAddress(bytes32,address) | 0x3f704d2a | +|----------+-----------------------------------------+------------| +| Function | withdraw(bytes32,bytes) | 0x4a2e35ba | ++----------+-----------------------------------------+------------+ + +IL2SharedBridgeLegacy ++----------+--------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==================================================================================================================================+ +| Function | deployBeaconProxy(bytes32) | 0x07168226 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | l1Bridge() | 0x969b53da | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | l1SharedBridge() | 0xb852ad36 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | l1TokenAddress(address) | 0xf54266a2 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | sendMessageToL1(bytes) | 0xff21c125 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(address,address,uint256) | 0xd9caed12 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | ++----------+--------------------------------------------------+--------------------------------------------------------------------+ + +IL2SharedBridgeLegacyFunctions ++----------+--------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++========================================================================================================================================+ +| Function | finalizeDeposit(address,address,address,uint256,bytes) | 0xcfe7af7c | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiated(address,address,address,uint256) | 0x2fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b0 | ++----------+--------------------------------------------------------+--------------------------------------------------------------------+ + +IL2WrappedBaseToken ++----------+---------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=================================================================================================================+ +| Function | deposit() | 0xd0e30db0 | +|----------+---------------------------------+--------------------------------------------------------------------| +| Function | depositTo(address) | 0xb760faf9 | +|----------+---------------------------------+--------------------------------------------------------------------| +| Function | withdraw(uint256) | 0x2e1a7d4d | +|----------+---------------------------------+--------------------------------------------------------------------| +| Function | withdrawTo(address,uint256) | 0x205c2878 | +|----------+---------------------------------+--------------------------------------------------------------------| +| Event | Initialize(string,string,uint8) | 0xc21caeb4e8f73861400d4c0870ad3e468ddb4e45225da3832ce1da5561f1f61e | ++----------+---------------------------------+--------------------------------------------------------------------+ + +IWETH9 ++----------+-------------------+------------+ +| Type | Signature | Selector | ++===========================================+ +| Function | deposit() | 0xd0e30db0 | +|----------+-------------------+------------| +| Function | withdraw(uint256) | 0x2e1a7d4d | ++----------+-------------------+------------+ + +IL1NativeTokenVault ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeCheckCounterpartAddress(uint256,bytes32,address,address) | 0x9cc395d0 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,bytes32) | 0x3345359b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerEthToken() | 0xcb6da609 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | TokenBeaconUpdated(address) | 0x5ed5e4f58bf9a324a38beaa1177fb96fcb7bf3a5f4c4585ebb78c4a8c0249d0f | ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ + +IL2NativeTokenVault ++----------+------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++======================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | L2TokenBeaconUpdated(address,bytes32) | 0x01fd5911e6d04aec6b21f19752502ad7f3e9876279643c8fa7a4d30c88a29fb2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiated(address,address,address,uint256) | 0x2fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b0 | ++----------+------------------------------------------------------+--------------------------------------------------------------------+ + +INativeTokenVault ++----------+-----------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | ++----------+-----------------------------------------------+--------------------------------------------------------------------+ + +IBridgehub ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================+ +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addChainTypeManager(address) | 0xff5a62a1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addTokenAssetId(bytes32) | 0x1c50cfea | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetIdIsRegistered(bytes32) | 0xe0ab6368 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseToken(uint256) | 0x59ec65a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenAssetId(uint256) | 0xe52db4ca | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xc2e90293 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManager(uint256) | 0x9d5bd3da | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManagerIsRegistered(address) | 0xb93c9366 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,address,bytes32,uint256,address,bytes,bytes[]) | 0xf113c88b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromAddress(address) | 0x70fccb52 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromChainId(uint256) | 0x24358c61 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdToAddress(bytes32) | 0x07621f84 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardTransactionOnGateway(uint256,bytes32,uint64) | 0x524c0cfa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChainChainIDs() | 0x68b8d331 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChains() | 0x49707f31 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1CtmDeployer() | 0xcbe83612 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256,uint256) | 0x71623274 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | messageRoot() | 0xd4b9f4fa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | migrationPaused() | 0x2a641114 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(uint256,bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xb292f5f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0xe6d9923b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,uint256,(uint16,address,bytes),bytes32[]) | 0x99c16d1a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerAlreadyDeployedZKChain(uint256,address) | 0xb5662c5d | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | removeChainTypeManager(address) | 0x332b96dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionDirect((uint256,uint256,address,uint256,bytes,uint256,uint256,bytes[],address)) | 0xd52471c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionTwoBridges((uint256,uint256,uint256,uint256,uint256,address,address,uint256,bytes)) | 0x24fd57fb | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAddresses(address,address,address) | 0x363bf964 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddress(bytes32,address) | 0x3f704d2a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyBaseTokenAssetId(uint256) | 0xca8f93f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyChainAddress(uint256) | 0xd92f86a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | settlementLayer(uint256) | 0x671a7131 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | sharedBridge() | 0x38720778 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | whitelistedSettlementLayers(uint256) | 0xe9420f8c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetRegistered(bytes32,address,bytes32,address) | 0x8f09d7694a9ae17acec5cf132d594d7eee23572f7fe132396ce72b1afbf7ef20 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BaseTokenAssetIdRegistered(bytes32) | 0x3df150949161462acf3be30521d7da9e533b247327a254e55dd01875897a6df3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerAdded(address) | 0x2eae91be1021e05cc8076387b0182458ae474ae44ee44cc59aefda6ca53c1f42 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerRemoved(address) | 0x4e04a497739580efe78a7ee09cdabe6f6fe90965c683292a519102ce5193b68a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationFinalized(uint256,bytes32,address) | 0xb0cc16029b506b2a262b52711e71db4fcd1cb078bd4bb86c7ba82cd3be2eadd3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationStarted(uint256,bytes32,uint256) | 0xc60eb6d595da5361c68f60aa7c8286b8f73c3a99e9db1818e146c522f512496f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChain(uint256,address,address) | 0x1e9125bc72db22c58abff6821d7333551967e26454b419ffa958e4cb8ef47600 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | SettlementLayerRegistered(uint256,bool) | 0x02629feb109d94b16a367231d248ba81c462f51ce5b984835f150f1c9f49ed25 | ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +ICTMDeploymentTracker ++----------+----------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------+------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+----------------------------------------------------------------+------------| +| Function | bridgeCheckCounterpartAddress(uint256,bytes32,address,address) | 0x9cc395d0 | +|----------+----------------------------------------------------------------+------------| +| Function | bridgehubDeposit(uint256,address,uint256,bytes) | 0xca408c23 | +|----------+----------------------------------------------------------------+------------| +| Function | calculateAssetId(address) | 0xb68c104a | +|----------+----------------------------------------------------------------+------------| +| Function | registerCTMAssetOnL1(address) | 0x2f9db630 | ++----------+----------------------------------------------------------------+------------+ + +IMessageRoot ++----------+--------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+--------------------------------------------+------------| +| Function | addChainBatchRoot(uint256,uint256,bytes32) | 0xfb644fc5 | +|----------+--------------------------------------------+------------| +| Function | addNewChain(uint256) | 0xd4ce08c2 | ++----------+--------------------------------------------+------------+ + +IL2Messenger ++----------+-----------------+------------+ +| Type | Signature | Selector | ++=========================================+ +| Function | sendToL1(bytes) | 0x62f84b24 | ++----------+-----------------+------------+ + +IL1Messenger ++----------+-----------------+------------+ +| Type | Signature | Selector | ++=========================================+ +| Function | sendToL1(bytes) | 0x62f84b24 | ++----------+-----------------+------------+ + +IL2ContractDeployer ++----------+----------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================================+ +| Function | create2(bytes32,bytes32,bytes) | 0x3cda3351 | +|----------+----------------------------------------------------------------+------------| +| Function | forceDeployOnAddresses((bytes32,address,bool,uint256,bytes)[]) | 0xe9f18c17 | ++----------+----------------------------------------------------------------+------------+ + +DummyRestriction ++----------+-----------------------------------------------+------------+ +| Type | Signature | Selector | ++=======================================================================+ +| Function | getSupportsRestrictionMagic() | 0x83e866f5 | +|----------+-----------------------------------------------+------------| +| Function | validateCall((address,uint256,bytes),address) | 0x9a9debe9 | ++----------+-----------------------------------------------+------------+ + +EventOnFallback ++-------+-------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++============================================================================================================+ +| Event | Called(address,uint256,bytes) | 0x998729e624ef59107d5781f8c021b04a5d7b5153dd0ef79e7a08a9f8ab40a5a3 | ++-------+-------------------------------+--------------------------------------------------------------------+ + +FeeOnTransferToken ++----------+---------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================+ +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decreaseAllowance(address,uint256) | 0xa457c2d7 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | increaseAllowance(address,uint256) | 0x39509351 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | mint(address,uint256) | 0x40c10f19 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | ++----------+---------------------------------------+--------------------------------------------------------------------+ + +Forwarder ++----------+------------------------+------------+ +| Type | Signature | Selector | ++================================================+ +| Function | forward(address,bytes) | 0x6fadcf72 | ++----------+------------------------+------------+ + +Multicall ++----------+------------------------------+------------+ +| Type | Signature | Selector | ++======================================================+ +| Function | aggregate((address,bytes)[]) | 0x252dba42 | +|----------+------------------------------+------------| +| Function | getBlockHash(uint256) | 0xee82ac5e | +|----------+------------------------------+------------| +| Function | getCurrentBlockCoinbase() | 0xa8b0574e | +|----------+------------------------------+------------| +| Function | getCurrentBlockDifficulty() | 0x72425d9d | +|----------+------------------------------+------------| +| Function | getCurrentBlockGasLimit() | 0x86d516e8 | +|----------+------------------------------+------------| +| Function | getCurrentBlockTimestamp() | 0x0f28c97d | +|----------+------------------------------+------------| +| Function | getEthBalance(address) | 0x4d2301cc | +|----------+------------------------------+------------| +| Function | getLastBlockHash() | 0x27e86d6e | ++----------+------------------------------+------------+ + +Multicall3 ++----------+-------------------------------------------------+------------+ +| Type | Signature | Selector | ++=========================================================================+ +| Function | aggregate((address,bytes)[]) | 0x252dba42 | +|----------+-------------------------------------------------+------------| +| Function | aggregate3((address,bool,bytes)[]) | 0x82ad56cb | +|----------+-------------------------------------------------+------------| +| Function | aggregate3Value((address,bool,uint256,bytes)[]) | 0x174dea71 | +|----------+-------------------------------------------------+------------| +| Function | blockAndAggregate((address,bytes)[]) | 0xc3077fa9 | +|----------+-------------------------------------------------+------------| +| Function | getBasefee() | 0x3e64a696 | +|----------+-------------------------------------------------+------------| +| Function | getBlockHash(uint256) | 0xee82ac5e | +|----------+-------------------------------------------------+------------| +| Function | getBlockNumber() | 0x42cbb15c | +|----------+-------------------------------------------------+------------| +| Function | getChainId() | 0x3408e470 | +|----------+-------------------------------------------------+------------| +| Function | getCurrentBlockCoinbase() | 0xa8b0574e | +|----------+-------------------------------------------------+------------| +| Function | getCurrentBlockDifficulty() | 0x72425d9d | +|----------+-------------------------------------------------+------------| +| Function | getCurrentBlockGasLimit() | 0x86d516e8 | +|----------+-------------------------------------------------+------------| +| Function | getCurrentBlockTimestamp() | 0x0f28c97d | +|----------+-------------------------------------------------+------------| +| Function | getEthBalance(address) | 0x4d2301cc | +|----------+-------------------------------------------------+------------| +| Function | getLastBlockHash() | 0x27e86d6e | +|----------+-------------------------------------------------+------------| +| Function | tryAggregate(bool,(address,bytes)[]) | 0xbce38bd7 | +|----------+-------------------------------------------------+------------| +| Function | tryBlockAndAggregate(bool,(address,bytes)[]) | 0x399542e9 | ++----------+-------------------------------------------------+------------+ + +RevertReceiveAccount ++----------+------------------------+------------+ +| Type | Signature | Selector | ++================================================+ +| Function | revertReceive() | 0xaa4593dc | +|----------+------------------------+------------| +| Function | setRevertReceive(bool) | 0x607e2cb2 | ++----------+------------------------+------------+ + +RevertTransferERC20 ++----------+---------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================+ +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decreaseAllowance(address,uint256) | 0xa457c2d7 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | increaseAllowance(address,uint256) | 0x39509351 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | mint(address,uint256) | 0x40c10f19 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | revertTransfer() | 0x1f067457 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | setRevertTransfer(bool) | 0xf20265d2 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | ++----------+---------------------------------------+--------------------------------------------------------------------+ + +SingletonFactory ++----------+-----------------------+------------+ +| Type | Signature | Selector | ++===============================================+ +| Function | deploy(bytes,bytes32) | 0x4af63f02 | ++----------+-----------------------+------------+ + +TestnetERC20Token ++----------+---------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================+ +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decreaseAllowance(address,uint256) | 0xa457c2d7 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | increaseAllowance(address,uint256) | 0x39509351 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | mint(address,uint256) | 0x40c10f19 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | ++----------+---------------------------------------+--------------------------------------------------------------------+ + +WETH9 ++----------+---------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================+ +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | deposit() | 0xd0e30db0 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(uint256) | 0x2e1a7d4d | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Deposit(address,uint256) | 0xe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | +|----------+---------------------------------------+--------------------------------------------------------------------| +| Event | Withdrawal(address,uint256) | 0x7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65 | ++----------+---------------------------------------+--------------------------------------------------------------------+ + +ITestnetERC20Token ++----------+-----------------------+------------+ +| Type | Signature | Selector | ++===============================================+ +| Function | decimals() | 0x313ce567 | +|----------+-----------------------+------------| +| Function | mint(address,uint256) | 0x40c10f19 | ++----------+-----------------------+------------+ + +AddressAliasHelperTest ++----------+---------------------------+------------+ +| Type | Signature | Selector | ++===================================================+ +| Function | applyL1ToL2Alias(address) | 0x7528c2c6 | +|----------+---------------------------+------------| +| Function | undoL1ToL2Alias(address) | 0x689992b3 | ++----------+---------------------------+------------+ + +DummyChainTypeManagerForValidatorTimelock ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | chainAdmin() | 0x6478d8ed | +|----------+-----------------------------+------------| +| Function | getChainAdmin(uint256) | 0x301e7765 | +|----------+-----------------------------+------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+-----------------------------+------------| +| Function | setZKChain(uint256,address) | 0xce214549 | +|----------+-----------------------------+------------| +| Function | zkChainAddress() | 0xbfcdc5bd | ++----------+-----------------------------+------------+ + +DummyERC20BytesTransferReturnValue ++----------+---------------------------+------------+ +| Type | Signature | Selector | ++===================================================+ +| Function | transfer(address,uint256) | 0xa9059cbb | ++----------+---------------------------+------------+ + +DummyERC20NoTransferReturnValue ++----------+---------------------------+------------+ +| Type | Signature | Selector | ++===================================================+ +| Function | transfer(address,uint256) | 0xa9059cbb | ++----------+---------------------------+------------+ + +DummyEraBaseTokenBridge ++----------+------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================================+ +| Function | bridgehubDepositBaseToken(uint256,address,address,uint256) | 0x2c4f2a58 | ++----------+------------------------------------------------------------+------------+ + +TransactionFiltererFalse ++----------+---------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=============================================================================================+ +| Function | isTransactionAllowed(address,address,uint256,uint256,bytes,address) | 0xcbcf2e3c | ++----------+---------------------------------------------------------------------+------------+ + +TransactionFiltererTrue ++----------+---------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=============================================================================================+ +| Function | isTransactionAllowed(address,address,uint256,uint256,bytes,address) | 0xcbcf2e3c | ++----------+---------------------------------------------------------------------+------------+ + +ReenterGovernance ++----------+-----------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++===============================================================================================+ +| Function | initialize(address,((address,uint256,bytes)[],bytes32,bytes32),uint8) | 0xb2ded522 | ++----------+-----------------------------------------------------------------------+------------+ + +ReenterL1ERC20Bridge ++----------+--------------------------+------------+ +| Type | Signature | Selector | ++==================================================+ +| Function | setBridge(address) | 0x8dd14802 | +|----------+--------------------------+------------| +| Function | setFunctionToCall(uint8) | 0x77421056 | ++----------+--------------------------+------------+ + +TestCalldataDA ++----------+-------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=====================================================================================+ +| Function | processCalldataDA(uint256,bytes32,uint256,bytes) | 0xfd3c6b55 | +|----------+-------------------------------------------------------------+------------| +| Function | processL2RollupDAValidatorOutputHash(bytes32,uint256,bytes) | 0x53e61bdc | ++----------+-------------------------------------------------------------+------------+ + +UncheckedMathTest ++----------+-------------------------------+------------+ +| Type | Signature | Selector | ++=======================================================+ +| Function | uncheckedAdd(uint256,uint256) | 0xb277f199 | +|----------+-------------------------------+------------| +| Function | uncheckedInc(uint256) | 0x8cf2b2f0 | ++----------+-------------------------------+------------+ + +UnsafeBytesTest ++----------+----------------------------+------------+ +| Type | Signature | Selector | ++====================================================+ +| Function | readAddress(bytes,uint256) | 0xf0e9da23 | +|----------+----------------------------+------------| +| Function | readBytes32(bytes,uint256) | 0xaf500fb7 | +|----------+----------------------------+------------| +| Function | readUint256(bytes,uint256) | 0xe02da327 | +|----------+----------------------------+------------| +| Function | readUint32(bytes,uint256) | 0x69c76df2 | ++----------+----------------------------+------------+ + +VerifierRecursiveTest ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | verificationKeyHash() | 0x9e8945d2 | +|----------+-----------------------------+------------| +| Function | verify(uint256[],uint256[]) | 0xb864f5a9 | ++----------+-----------------------------+------------+ + +VerifierTest ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | verificationKeyHash() | 0x9e8945d2 | +|----------+-----------------------------+------------| +| Function | verify(uint256[],uint256[]) | 0xb864f5a9 | ++----------+-----------------------------+------------+ + +IAccessControlRestriction ++-------+----------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================+ +| Event | FallbackRoleSet(address,bytes32) | 0xacb22a6b6e4593545bea6f5cdd10238b8a592aba079d9cfc76adb71edf02d40b | +|-------+----------------------------------+--------------------------------------------------------------------| +| Event | RoleSet(address,bytes4,bytes32) | 0x25c1ec7629ef447de39798ef5e6e0da89139b2257681441b45f1779c3efda036 | ++-------+----------------------------------+--------------------------------------------------------------------+ + +IChainAdmin ++----------+--------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==================================================================================================================================+ +| Function | addRestriction(address) | 0x33163987 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | getRestrictions() | 0xc4195cb8 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | isRestrictionActive(address) | 0x02f0277d | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | multicall((address,uint256,bytes)[],bool) | 0x69340beb | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | removeRestriction(address) | 0x69a5b950 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | CallExecuted((address,uint256,bytes),bool,bytes) | 0x157c677a40c50f832f816d7b59c8c3e94774acae328c8ccb145b73aea7566d75 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | RestrictionAdded(address) | 0x83cfa0dec28fa91596ce8081b6279e7d1c402d3d4bc40934fc51f8830e7d82c6 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | RestrictionRemoved(address) | 0xdf4f1ec932dcab3c66fb7845ba6fc669816121e5d4a81d6955d3c6d3bff7b7e9 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | UpdateUpgradeTimestamp(uint256,uint256) | 0xd50ef21701c8ef211433b140724b8d6de471e7d822c8a616c3d424fe2d0e98a9 | ++----------+--------------------------------------------------+--------------------------------------------------------------------+ + +IGovernance ++----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++============================================================================================================================================================================+ +| Function | cancel(bytes32) | 0xc4d252f5 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | execute(((address,uint256,bytes)[],bytes32,bytes32)) | 0x74da756b | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeInstant(((address,uint256,bytes)[],bytes32,bytes32)) | 0x95218ecd | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getOperationState(bytes32) | 0x7958004c | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | hashOperation(((address,uint256,bytes)[],bytes32,bytes32)) | 0xc126e860 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperation(bytes32) | 0x31d50750 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationDone(bytes32) | 0x2ab0f529 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationPending(bytes32) | 0x584b153e | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationReady(bytes32) | 0x13bc9f20 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | scheduleShadow(bytes32,uint256) | 0x6d1d8363 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | scheduleTransparent(((address,uint256,bytes)[],bytes32,bytes32),uint256) | 0x2c431917 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | updateDelay(uint256) | 0x64d62353 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | updateSecurityCouncil(address) | 0xdbfe3e96 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChangeMinDelay(uint256,uint256) | 0x0c5ff76c31d24175d9e84ef46e328eafbcaeb2aa67a2333035eb082dd34324f1 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChangeSecurityCouncil(address,address) | 0xe55ac8ae7914efca1278b8ed4ae21728d06ad9f6e7637bb2c905aacf2a6f5951 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OperationCancelled(bytes32) | 0xcf0f63b97f3387253cbc0bde884f975df77e39184dc3280c2c81be495f58eef4 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OperationExecuted(bytes32) | 0x1277662f4b42b8a4069e99fb5e41ce8919d3c621156090ac08fb11adbcec66f9 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ShadowOperationScheduled(bytes32,uint256) | 0xbcb40fd953364ec8aed99fa0bd6dcc03103f979efde4744ad7452e556ff20ba6 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | TransparentOperationScheduled(bytes32,uint256,((address,uint256,bytes)[],bytes32,bytes32)) | 0x23bc9f5dc037eb49c162fd08c2a4d43dfe70063149e140d502273168da0a0625 | ++----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IPermanentRestriction ++-------+------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================+ +| Event | AdminImplementationAllowed(bytes32,bool) | 0xb9b1bc97b8d56d15ac2abdd71d788b0d6e14dc92fa9b8df811d0a2f41c14354a | +|-------+------------------------------------------+--------------------------------------------------------------------| +| Event | AllowL2Admin(address) | 0x43472806f9101fbc243f5a64948e56332b1d18bb082e7d4772a29368eb80991e | +|-------+------------------------------------------+--------------------------------------------------------------------| +| Event | AllowedDataChanged(bytes,bool) | 0xbb577d7ca5995b00ceaae0c75f77ab5df42a1e24673e2e36858ee718f3f1eb8c | +|-------+------------------------------------------+--------------------------------------------------------------------| +| Event | SelectorValidationChanged(bytes4,bool) | 0x85198d5146ae402b94f01f31a2049f75a6ecadc1d321090cd97467979b8d09d7 | ++-------+------------------------------------------+--------------------------------------------------------------------+ + +L2ProxyAdminDeployer ++----------+-----------------------+------------+ +| Type | Signature | Selector | ++===============================================+ +| Function | PROXY_ADMIN_ADDRESS() | 0x7e1dfea3 | ++----------+-----------------------+------------+ + +TransitionaryOwner ++----------+--------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================+ +| Function | GOVERNANCE_ADDRESS() | 0x0143dd86 | +|----------+--------------------------------------------+------------| +| Function | claimOwnershipAndGiveToGovernance(address) | 0xfbdb0a0b | ++----------+--------------------------------------------+------------+ + +IRestriction ++----------+-----------------------------------------------+------------+ +| Type | Signature | Selector | ++=======================================================================+ +| Function | getSupportsRestrictionMagic() | 0x83e866f5 | +|----------+-----------------------------------------------+------------| +| Function | validateCall((address,uint256,bytes),address) | 0x9a9debe9 | ++----------+-----------------------------------------------+------------+ + +Restriction ++----------+-----------------------------------------------+------------+ +| Type | Signature | Selector | ++=======================================================================+ +| Function | getSupportsRestrictionMagic() | 0x83e866f5 | +|----------+-----------------------------------------------+------------| +| Function | validateCall((address,uint256,bytes),address) | 0x9a9debe9 | ++----------+-----------------------------------------------+------------+ + +TestnetVerifier ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | verificationKeyHash() | 0x9e8945d2 | +|----------+-----------------------------+------------| +| Function | verify(uint256[],uint256[]) | 0xb864f5a9 | ++----------+-----------------------------+------------+ + +Verifier ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | verificationKeyHash() | 0x9e8945d2 | +|----------+-----------------------------+------------| +| Function | verify(uint256[],uint256[]) | 0xb864f5a9 | ++----------+-----------------------------+------------+ + +IExecutor ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===========================================================================================================================================+ +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +IL1DAValidator ++----------+------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================+ +| Function | checkDA(uint256,uint256,bytes32,bytes,uint256) | 0x381c3f13 | ++----------+------------------------------------------------+------------+ + +ILegacyGetters ++----------+------------------------------------------+------------+ +| Type | Signature | Selector | ++==================================================================+ +| Function | getL2SystemContractsUpgradeBlockNumber() | 0x9d1b5a81 | +|----------+------------------------------------------+------------| +| Function | getName() | 0x17d7de7c | +|----------+------------------------------------------+------------| +| Function | getTotalBlocksCommitted() | 0xfe26699e | +|----------+------------------------------------------+------------| +| Function | getTotalBlocksExecuted() | 0x39607382 | +|----------+------------------------------------------+------------| +| Function | getTotalBlocksVerified() | 0xaf6a2dcd | +|----------+------------------------------------------+------------| +| Function | storedBlockHash(uint256) | 0x74f4d30d | ++----------+------------------------------------------+------------+ + +IMailbox ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===================================================================================================================================================================================================================================================================+ +| Function | bridgehubRequestL2Transaction((address,address,uint256,uint256,bytes,uint256,uint256,bytes[],address)) | 0x12f43dab | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2TransactionOnGateway(bytes32,uint64) | 0xddcc9eec | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeEthWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x6c0960f9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256) | 0xb473318e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0x042901c7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LeafInclusion(uint256,uint256,bytes32,bytes32[]) | 0x7efda2ae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0x263b7f8e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,(uint16,address,bytes),bytes32[]) | 0xe4948f43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2Transaction(address,uint256,bytes,uint256,uint256,bytes[],address) | 0xeb672419 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionToGatewayMailbox(uint256,bytes32,uint64) | 0xd0772551 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityRequest(uint256,bytes32,uint64,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[]) | 0x4531cd5795773d7101c17bdeb9f5ab7f47d7056017506f937083be5d6e77a382 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewRelayedPriorityTransaction(uint256,bytes32,uint64) | 0x0137d2eaa6ec5b7e4f233f6d6f441410014535d0f3985367994c94bf15a2a564 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +ITransactionFilterer ++----------+---------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=============================================================================================+ +| Function | isTransactionAllowed(address,address,uint256,uint256,bytes,address) | 0xcbcf2e3c | ++----------+---------------------------------------------------------------------+------------+ + +IVerifier ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | verificationKeyHash() | 0x9e8945d2 | +|----------+-----------------------------+------------| +| Function | verify(uint256[],uint256[]) | 0xb864f5a9 | ++----------+-----------------------------+------------+ + +IZKChainBase ++----------+-----------+------------+ +| Type | Signature | Selector | ++===================================+ +| Function | getName() | 0x17d7de7c | ++----------+-----------+------------+ + +RelayedSLDAValidator ++----------+------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================+ +| Function | checkDA(uint256,uint256,bytes32,bytes,uint256) | 0x381c3f13 | ++----------+------------------------------------------------+------------+ + +ValidiumL1DAValidator ++----------+------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================+ +| Function | checkDA(uint256,uint256,bytes32,bytes,uint256) | 0x381c3f13 | ++----------+------------------------------------------------+------------+ + +IComplexUpgrader ++----------+------------------------+------------+ +| Type | Signature | Selector | ++================================================+ +| Function | upgrade(address,bytes) | 0xc987336c | ++----------+------------------------+------------+ + +IL2GatewayUpgrade ++----------+---------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=============================================================================================+ +| Function | upgrade((bytes32,address,bool,uint256,bytes)[],address,bytes,bytes) | 0xff87ffa5 | ++----------+---------------------------------------------------------------------+------------+ + +IL2GenesisUpgrade ++----------+---------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=============================================================================================================================+ +| Function | genesisUpgrade(uint256,address,bytes,bytes) | 0x012aa9a4 | +|----------+---------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256) | 0xd01e21be66147e834d803d6e8b8656aabf0c7c4cb36947b8c3cac47be96afd84 | ++----------+---------------------------------------------+--------------------------------------------------------------------+ + +ISystemContext ++----------+---------------------+------------+ +| Type | Signature | Selector | ++=============================================+ +| Function | setChainId(uint256) | 0xef0e2ff4 | ++----------+---------------------+------------+ + +IL1GenesisUpgrade ++----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++========================================================================================================================================================================================================================================================+ +| Function | genesisUpgrade(address,uint256,uint256,address,bytes,bytes[]) | 0xd83e4e03 | +|----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256,bytes[]) | 0xc5902263211386c797097c5eef7ce20567f0e13359623233314cfa01a55341da | ++----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +BridgedStandardERC20 ++----------+---------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================================+ +| Function | DOMAIN_SEPARATOR() | 0x3644e515 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId() | 0x44de240a | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(address,uint256) | 0x74f4f547 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeInitialize(bytes32,address,bytes) | 0x9a6ab870 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(address,uint256) | 0x8c2a993e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decodeString(bytes) | 0x95ce3e93 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decodeUint8(bytes) | 0x7ba8be34 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decreaseAllowance(address,uint256) | 0xa457c2d7 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | eip712Domain() | 0x84b0196e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | increaseAllowance(address,uint256) | 0x39509351 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1Address() | 0xc2eeeebd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nonces(address) | 0x7ecebe00 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | originToken() | 0x13096a41 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | permit(address,address,uint256,uint256,uint8,bytes32,bytes32) | 0xd505accf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | reinitializeToken((bool,bool,bool),string,string,uint8) | 0xb71bcf90 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AdminChanged(address,address) | 0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BeaconUpgraded(address) | 0x1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(address,uint256) | 0x9b5b9a05e4726d8bb959f1440e05c6b8109443f2083bc4e386237d7654526553 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | EIP712DomainChanged() | 0x0a6387c9ea3628b88a633bb4f3b151770f70085117a15f9bf3787cda53f13d31 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Upgraded(address) | 0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonSequentialVersion() | 0x0ac76f01 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+---------------------------------------------------------------+--------------------------------------------------------------------+ + +L1ERC20Bridge ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==============================================================================================================================================================+ +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NATIVE_TOKEN_VAULT() | 0x293e8520 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(address,address,bytes32,uint256,uint256,uint16,bytes32[]) | 0x19fa7f62 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256) | 0x933999fb | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256,address) | 0xe8b99b1b | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositAmount(address,address,bytes32) | 0x01eae183 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x11a2ccc1 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize() | 0x8129fc1c | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256) | 0x4bed8212 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenProxyBytecodeHash() | 0x823f1d96 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDeposit(address,address,uint256) | 0xbe066dc591f4a444f75176d387c3e6c775e5706d9ea9a91d11eb49030c66cf60 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositInitiated(bytes32,address,address,address,uint256) | 0xdd341179f4edc78148d894d0213a96d212af2cbaf223d19ef6d483bdd47ab81d | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalFinalized(address,address,uint256) | 0xac1b18083978656d557d6e91c88203585cfda1031bdb14538327121ef140d383 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ApprovalFailed() | 0x8164f842 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ETHDepositNotSupported() | 0x627e0872 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawalAlreadyFinalized() | 0xae899454 | ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L1Nullifier ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_admin() | 0xf7a5cec0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_chainBalance(uint256,address) | 0x6182877b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_l2BridgeAddress(uint256) | 0xfdbb0301 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_pendingAdmin() | 0x6cdecb2b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes,bytes32,uint256,uint256,uint16,bytes32[]) | 0x3601e63e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2TransactionForwarded(uint256,bytes32,bytes32) | 0x4bc2c8c0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,address) | 0x9cd45184 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(uint256,address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0xc0991525 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDepositLegacyErc20Bridge(address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0x8fbb3711 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositHappened(uint256,bytes32) | 0x9fa8826b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | encodeTxDataHash(bytes1,address,bytes32,bytes) | 0xf120e6c4 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit((uint256,uint256,uint256,address,uint16,bytes,bytes32[])) | 0x74beea82 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address,uint256,uint256,uint256,uint256) | 0xf92ad219 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256,uint256) | 0x8f31f052 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1AssetRouter() | 0x6d9860e1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1NativeTokenVault() | 0x6f513211 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | legacyBridge() | 0x6e9d7899 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nullifyChainBalanceByNTV(uint256,address) | 0x5de097b1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1AssetRouter(address) | 0x780ce114 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1Erc20Bridge(address) | 0x30bda03e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1NativeTokenVault(address) | 0xb7cc6f46 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferTokenToNTV(address) | 0x40a434d5 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositFinalized(uint256,bytes32,bytes32) | 0xe4def01b981193a97a9e81230d7b9f31812ceaf23f864a828a82c687911cb2df | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressAlreadySet(address) | 0x0dfb42bf | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DepositDoesNotExist() | 0xc7c9660f | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DepositExists() | 0xad2fa98e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProof() | 0x09bde339 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidSelector(bytes4) | 0x12ba286f | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2WithdrawalMessageWrongLength(uint256) | 0x97e1359e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SharedBridgeValueNotSet(uint8) | 0x7774d2f9 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawalAlreadyFinalized() | 0xae899454 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L2SharedBridgeLegacy ++----------+--------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++========================================================================================================================================+ +| Function | deployBeaconProxy(bytes32) | 0x07168226 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(address,address,address,uint256,bytes) | 0xcfe7af7c | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address,bytes32,address) | 0xd26b3e6e | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1Bridge() | 0x969b53da | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1SharedBridge() | 0xb852ad36 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1TokenAddress(address) | 0xf54266a2 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | sendMessageToL1(bytes) | 0xff21c125 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(address,address,uint256) | 0xd9caed12 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployFailed() | 0xb4f54111 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyBytes32() | 0x1c25715b | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidCaller(address) | 0xcbd9d2e0 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | U32CastOverflow() | 0xfe3c3c45 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+--------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+--------------------------------------------------------+--------------------------------------------------------------------+ + +L2WrappedBaseToken ++----------+---------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================================+ +| Function | DOMAIN_SEPARATOR() | 0x3644e515 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | allowance(address,address) | 0xdd62ed3e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | approve(address,uint256) | 0x095ea7b3 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId() | 0x44de240a | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | balanceOf(address) | 0x70a08231 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenAssetId() | 0x22ce9d15 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(address,uint256) | 0x74f4f547 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(address,uint256) | 0x8c2a993e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decimals() | 0x313ce567 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | decreaseAllowance(address,uint256) | 0xa457c2d7 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit() | 0xd0e30db0 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositTo(address) | 0xb760faf9 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | eip712Domain() | 0x84b0196e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | increaseAllowance(address,uint256) | 0x39509351 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initializeV2(string,string,address,address,bytes32) | 0x92f9f0a0 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1Address() | 0xc2eeeebd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | name() | 0x06fdde03 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nonces(address) | 0x7ecebe00 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | originToken() | 0x13096a41 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | permit(address,address,uint256,uint256,uint8,bytes32,bytes32) | 0xd505accf | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | symbol() | 0x95d89b41 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | totalSupply() | 0x18160ddd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transfer(address,uint256) | 0xa9059cbb | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferFrom(address,address,uint256) | 0x23b872dd | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(uint256) | 0x2e1a7d4d | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdrawTo(address,uint256) | 0x205c2878 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Approval(address,address,uint256) | 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(address,uint256) | 0x9b5b9a05e4726d8bb959f1440e05c6b8109443f2083bc4e386237d7654526553 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | EIP712DomainChanged() | 0x0a6387c9ea3628b88a633bb4f3b151770f70085117a15f9bf3787cda53f13d31 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialize(string,string,uint8) | 0xc21caeb4e8f73861400d4c0870ad3e468ddb4e45225da3832ce1da5561f1f61e | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Transfer(address,address,uint256) | 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BridgeMintNotImplemented() | 0xdb538614 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawFailed() | 0x750b219c | +|----------+---------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+---------------------------------------------------------------+--------------------------------------------------------------------+ + +AssetRouterBase ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetDeploymentTracker(bytes32) | 0x85e4e16a | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ + +L1AssetRouter ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_WETH_TOKEN() | 0x41c841c3 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetDeploymentTracker(bytes32) | 0x85e4e16a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes) | 0x1346ca3b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes,bytes32,uint256,uint256,uint16,bytes32[]) | 0x3601e63e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2Transaction(uint256,bytes32,bytes32) | 0x8eb7db57 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDeposit(uint256,address,uint256,bytes) | 0xca408c23 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDepositBaseToken(uint256,bytes32,address,uint256) | 0xc4879440 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(uint256,address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0xc0991525 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositLegacyErc20Bridge(address,address,address,uint256,uint256,uint256,address) | 0x9e6ea417 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint256,uint16,bytes,bytes32[]) | 0xc87325f1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getDepositCalldata(address,bytes32,bytes) | 0x2ff0b2ea | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256,uint256) | 0x8f31f052 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | legacyBridge() | 0x6e9d7899 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetDeploymentTracker(bytes32,address) | 0xc0a16dda | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1Erc20Bridge(address) | 0x30bda03e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNativeTokenVault(address) | 0x0f3fa211 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferFundsToNTV(bytes32,uint256,address) | 0x57d4ca5c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetDeploymentTrackerSet(bytes32,address,bytes32) | 0x14c1bae9bcc3777747463b66a36584aa75e4ded1aa38089f447beecb125a2175 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositFinalized(uint256,bytes32,bytes32) | 0xe4def01b981193a97a9e81230d7b9f31812ceaf23f864a828a82c687911cb2df | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubMintData(bytes) | 0x31a15cb4f69820f57afabeaff74feae31dc25875c07c952ba742a3acf8690f91 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDepositAssetRouter(uint256,bytes32,bytes) | 0x4250817d22c13fba8067153d85ccd9706326ac2bd14d5c3898c8b1bccc440658 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | LegacyDepositInitiated(uint256,bytes32,address,address,address,uint256) | 0xa1846a4248529db592da99da276f761d9f37a84d0f3d4e83819b869759000700 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressAlreadyUsed(address) | 0x1ff9d522 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetHandlerDoesNotExist(bytes32) | 0xfde974f4 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokenNotSupported(address) | 0x06439c6b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L2AssetRouter ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================+ +| Function | BASE_TOKEN_ASSET_ID() | 0xcb944dec | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L2_LEGACY_SHARED_BRIDGE() | 0xc438a9f2 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetDeploymentTracker(bytes32) | 0x85e4e16a | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(uint256,bytes32,bytes) | 0x9c884fd1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit(address,address,address,uint256,bytes) | 0xcfe7af7c | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDepositLegacyBridge(address,address,address,uint256,bytes) | 0x54b2e69c | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1AssetRouter() | 0x6d9860e1 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1Bridge() | 0x969b53da | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1TokenAddress(address) | 0xf54266a2 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddress(uint256,bytes32,address) | 0xda556bdc | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(bytes32,bytes) | 0x4a2e35ba | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdraw(address,address,uint256) | 0xd9caed12 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdrawLegacyBridge(address,address,uint256,address) | 0x7ac3a553 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | withdrawToken(address,bytes) | 0x958a9f51 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegistered(bytes32,address) | 0x2632cc0d58b0cb1017b99cc0b6cc66ad86440cc0dd923bfdaa294f95ba1b0201 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetHandlerRegisteredInitial(bytes32,address,bytes32,address) | 0xb1e82bee3e85b2755fbceb4b7e051f5c66a7f35f0476657504e77e18ebd3a17d | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositInitiated(uint256,bytes32,address,bytes32,bytes) | 0xe21913bc89c1320d9709a5d236ffe06b54cf88aecfc9509ebd68f1adba45781e | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubWithdrawalInitiated(uint256,address,bytes32,bytes32) | 0x9a3d4025b7294a1754ea5b56309c1e72328d97b73718183db595c850d14a3ae0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositFinalizedAssetRouter(uint256,bytes32,bytes) | 0x44eb9a840094a49b3cd0a5205042598a1c08c4e87bafb5760bc2d8efa170c541 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiatedAssetRouter(uint256,address,bytes32,bytes) | 0x55362fc62473cb1255e770af5d5e02ba6ee5bc7ed6969c30eb11ca31b92384dc | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyAddress() | 0x7138356f | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidCaller(address) | 0xcbd9d2e0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ + +L1NativeTokenVault ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | BASE_TOKEN_ASSET_ID() | 0xcb944dec | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeCheckCounterpartAddress(uint256,bytes32,address,address) | 0x9cc395d0 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xc2e90293 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgedTokenBeacon() | 0xf2d44246 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,bytes32) | 0x3345359b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address,address) | 0x485cc955 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerEthToken() | 0xcb6da609 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenDataOriginChainId(bytes) | 0x07a6d4bc | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferFundsFromSharedBridge(address) | 0x8310f2c6 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | updateChainBalancesFromSharedBridge(address,uint256) | 0x1c9f0149 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | TokenBeaconUpdated(address) | 0x5ed5e4f58bf9a324a38beaa1177fb96fcb7bf3a5f4c4585ebb78c4a8c0249d0f | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressMismatch(address,address) | 0x1f73225f | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdMismatch(bytes32,bytes32) | 0x1294e9e1 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployingBridgedTokenForNativeToken() | 0x138ee1a3 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InsufficientChainBalance() | 0x826fb11e | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFundsTransferred() | 0xcab098d8 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyMsgValue() | 0x536ec84b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OriginChainIdNotFound() | 0xb926450e | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokenNotSupported(address) | 0x06439c6b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawFailed() | 0x750b219c | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ + +L2NativeTokenVault ++----------+------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++======================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | BASE_TOKEN_ASSET_ID() | 0xcb944dec | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | L2_LEGACY_SHARED_BRIDGE() | 0xc438a9f2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgedTokenBeacon() | 0xf2d44246 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyTokenAssetId(address) | 0x4cd40a02 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenDataOriginChainId(bytes) | 0x07a6d4bc | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | L2TokenBeaconUpdated(address,bytes32) | 0x01fd5911e6d04aec6b21f19752502ad7f3e9876279643c8fa7a4d30c88a29fb2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiated(address,address,address,uint256) | 0x2fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b0 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressMismatch(address,address) | 0x1f73225f | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdMismatch(bytes32,bytes32) | 0x1294e9e1 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployFailed() | 0xb4f54111 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployingBridgedTokenForNativeToken() | 0x138ee1a3 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyAddress() | 0x7138356f | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyBytes32() | 0x1c25715b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyMsgValue() | 0x536ec84b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokenNotSupported(address) | 0x06439c6b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | U32CastOverflow() | 0xfe3c3c45 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+------------------------------------------------------+--------------------------------------------------------------------+ + +NativeTokenVault ++----------+-----------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | BASE_TOKEN_ASSET_ID() | 0xcb944dec | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgedTokenBeacon() | 0xf2d44246 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenDataOriginChainId(bytes) | 0x07a6d4bc | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressMismatch(address,address) | 0x1f73225f | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdMismatch(bytes32,bytes32) | 0x1294e9e1 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployingBridgedTokenForNativeToken() | 0x138ee1a3 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyMsgValue() | 0x536ec84b | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | TokenNotSupported(address) | 0x06439c6b | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+-----------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-----------------------------------------------------+--------------------------------------------------------------------+ + +Bridgehub ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================+ +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | MAX_NUMBER_OF_ZK_CHAINS() | 0x8f8d37a8 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_baseToken(uint256) | 0x5d83b6da | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_tokenIsRegistered(address) | 0xeced0bf0 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addChainTypeManager(address) | 0xff5a62a1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addTokenAssetId(bytes32) | 0x1c50cfea | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetIdIsRegistered(bytes32) | 0xe0ab6368 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetRouter() | 0xbc0aac10 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseToken(uint256) | 0x59ec65a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenAssetId(uint256) | 0xe52db4ca | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xc2e90293 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManager(uint256) | 0x9d5bd3da | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManagerIsRegistered(address) | 0xb93c9366 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,address,bytes32,uint256,address,bytes,bytes[]) | 0xf113c88b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromAddress(address) | 0x70fccb52 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromChainId(uint256) | 0x24358c61 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdToAddress(bytes32) | 0x07621f84 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardTransactionOnGateway(uint256,bytes32,uint64) | 0x524c0cfa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChainChainIDs() | 0x68b8d331 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChains() | 0x49707f31 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initializeV2() | 0x5cd8a76b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1CtmDeployer() | 0xcbe83612 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256,uint256) | 0x71623274 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | messageRoot() | 0xd4b9f4fa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | migrationPaused() | 0x2a641114 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pauseMigration() | 0xac700e63 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(uint256,bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xb292f5f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0xe6d9923b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,uint256,(uint16,address,bytes),bytes32[]) | 0x99c16d1a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerAlreadyDeployedZKChain(uint256,address) | 0xb5662c5d | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | removeChainTypeManager(address) | 0x332b96dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionDirect((uint256,uint256,address,uint256,bytes,uint256,uint256,bytes[],address)) | 0xd52471c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionTwoBridges((uint256,uint256,uint256,uint256,uint256,address,address,uint256,bytes)) | 0x24fd57fb | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAddresses(address,address,address) | 0x363bf964 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddress(bytes32,address) | 0x3f704d2a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyBaseTokenAssetId(uint256) | 0xca8f93f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyChainAddress(uint256) | 0xd92f86a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | settlementLayer(uint256) | 0x671a7131 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | sharedBridge() | 0x38720778 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpauseMigration() | 0xf7c7eb92 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | whitelistedSettlementLayers(uint256) | 0xe9420f8c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetRegistered(bytes32,address,bytes32,address) | 0x8f09d7694a9ae17acec5cf132d594d7eee23572f7fe132396ce72b1afbf7ef20 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BaseTokenAssetIdRegistered(bytes32) | 0x3df150949161462acf3be30521d7da9e533b247327a254e55dd01875897a6df3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerAdded(address) | 0x2eae91be1021e05cc8076387b0182458ae474ae44ee44cc59aefda6ca53c1f42 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerRemoved(address) | 0x4e04a497739580efe78a7ee09cdabe6f6fe90965c683292a519102ce5193b68a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationFinalized(uint256,bytes32,address) | 0xb0cc16029b506b2a262b52711e71db4fcd1cb078bd4bb86c7ba82cd3be2eadd3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationStarted(uint256,bytes32,uint256) | 0xc60eb6d595da5361c68f60aa7c8286b8f73c3a99e9db1818e146c522f512496f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChain(uint256,address,address) | 0x1e9125bc72db22c58abff6821d7333551967e26454b419ffa958e4cb8ef47600 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | SettlementLayerRegistered(uint256,bool) | 0x02629feb109d94b16a367231d248ba81c462f51ce5b984835f150f1c9f49ed25 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressTooLow(address) | 0x1eee5481 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetHandlerNotRegistered(bytes32) | 0x64107968 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdAlreadyRegistered() | 0xfe919e28 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BridgeHubAlreadyRegistered() | 0x6cf12312 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CTMAlreadyRegistered() | 0xec273439 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CTMNotRegistered() | 0xc630ef3c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainAlreadyLive() | 0x78d2ed02 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdAlreadyExists() | 0x24591d89 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdCantBeCurrentChain() | 0x717a1656 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdMismatch() | 0xa179f8c9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdNotRegistered(uint256) | 0x23f3c357 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdTooBig() | 0x8f620a06 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainNotLegacy() | 0x5de72107 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyAssetId() | 0x2d4d012f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | IncorrectBridgeHubAddress(address) | 0xdd381a4c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MigrationPaused() | 0x3312a450 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MsgValueMismatch(uint256,uint256) | 0x4a094431 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SharedBridgeNotSet() | 0x856d5b77 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WrongMagicValue(uint256,uint256) | 0x15e8e429 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZKChainLimitReached() | 0x601b6882 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroChainId() | 0xc84885d4 | ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +CTMDeploymentTracker ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeCheckCounterpartAddress(uint256,bytes32,address,address) | 0x9cc395d0 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2Transaction(uint256,bytes32,bytes32) | 0x8eb7db57 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDeposit(uint256,address,uint256,bytes) | 0xca408c23 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateAssetId(address) | 0xb68c104a | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerCTMAssetOnL1(address) | 0x2f9db630 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+----------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | ++----------+----------------------------------------------------------------+--------------------------------------------------------------------+ + +MessageRoot ++----------+-------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | addChainBatchRoot(uint256,uint256,bytes32) | 0xfb644fc5 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | addNewChain(uint256) | 0xd4ce08c2 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | chainCount() | 0xe02e1bfd | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | chainIndex(uint256) | 0x48ceb85e | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | chainIndexToId(uint256) | 0xed1d7d97 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | chainRegistered(uint256) | 0xb8776d4d | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | getAggregatedRoot() | 0x3977d71c | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainRoot(uint256) | 0x1e4fba05 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize() | 0x8129fc1c | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | sharedTree() | 0xb1fde1a8 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | updateFullTree() | 0xbcd1b23d | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | AddedChain(uint256,uint256) | 0x5d96eda109bfd71cf9f4f70c83de31c4150760e8828979a95d9e5f9f15455af7 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | AppendedChainBatchRoot(uint256,uint256,bytes32) | 0x4f7fd9ed016150a623d5a2cf43053fe313a56293a77e060a05db49ed22579520 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | Preimage(bytes32,bytes32) | 0x79a6ee6d75f19524cbfb09fe5df3f30024a7a557e62bea09bfdd3843b7fe5bda | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | ++----------+-------------------------------------------------+--------------------------------------------------------------------+ + +IContractDeployer ++----------+----------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++========================================================================================+ +| Function | create2(bytes32,bytes32,bytes) | 0x3cda3351 | +|----------+----------------------------------------------------------------+------------| +| Function | forceDeployOnAddresses((bytes32,address,bool,uint256,bytes)[]) | 0xe9f18c17 | ++----------+----------------------------------------------------------------+------------+ + +DummyL1ERC20Bridge ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==============================================================================================================================================================+ +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NATIVE_TOKEN_VAULT() | 0x293e8520 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(address,address,bytes32,uint256,uint256,uint16,bytes32[]) | 0x19fa7f62 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256) | 0x933999fb | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256,address) | 0xe8b99b1b | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositAmount(address,address,bytes32) | 0x01eae183 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x11a2ccc1 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize() | 0x8129fc1c | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256) | 0x4bed8212 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenProxyBytecodeHash() | 0x823f1d96 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValues(address,address,bytes32) | 0xf5407abe | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDeposit(address,address,uint256) | 0xbe066dc591f4a444f75176d387c3e6c775e5706d9ea9a91d11eb49030c66cf60 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositInitiated(bytes32,address,address,address,uint256) | 0xdd341179f4edc78148d894d0213a96d212af2cbaf223d19ef6d483bdd47ab81d | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalFinalized(address,address,uint256) | 0xac1b18083978656d557d6e91c88203585cfda1031bdb14538327121ef140d383 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ApprovalFailed() | 0x8164f842 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ETHDepositNotSupported() | 0x627e0872 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawalAlreadyFinalized() | 0xae899454 | ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L1NullifierDev ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_admin() | 0xf7a5cec0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_chainBalance(uint256,address) | 0x6182877b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_l2BridgeAddress(uint256) | 0xfdbb0301 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_pendingAdmin() | 0x6cdecb2b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,address,bytes32,bytes,bytes32,uint256,uint256,uint16,bytes32[]) | 0x3601e63e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2TransactionForwarded(uint256,bytes32,bytes32) | 0x4bc2c8c0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,address) | 0x9cd45184 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(uint256,address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0xc0991525 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDepositLegacyErc20Bridge(address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0x8fbb3711 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositHappened(uint256,bytes32) | 0x9fa8826b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | encodeTxDataHash(bytes1,address,bytes32,bytes) | 0xf120e6c4 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeDeposit((uint256,uint256,uint256,address,uint16,bytes,bytes32[])) | 0x74beea82 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address,uint256,uint256,uint256,uint256) | 0xf92ad219 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256,uint256) | 0x8f31f052 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1AssetRouter() | 0x6d9860e1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1NativeTokenVault() | 0x6f513211 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2BridgeAddress(uint256) | 0x07ee9355 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | legacyBridge() | 0x6e9d7899 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nullifyChainBalanceByNTV(uint256,address) | 0x5de097b1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1AssetRouter(address) | 0x780ce114 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1Erc20Bridge(address) | 0x30bda03e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL1NativeTokenVault(address) | 0xb7cc6f46 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setL2LegacySharedBridge(uint256,address) | 0x4771ebad | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferTokenToNTV(address) | 0x40a434d5 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositFinalized(uint256,bytes32,bytes32) | 0xe4def01b981193a97a9e81230d7b9f31812ceaf23f864a828a82c687911cb2df | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressAlreadySet(address) | 0x0dfb42bf | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DepositDoesNotExist() | 0xc7c9660f | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DepositExists() | 0xad2fa98e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProof() | 0x09bde339 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidSelector(bytes4) | 0x12ba286f | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2WithdrawalMessageWrongLength(uint256) | 0x97e1359e | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SharedBridgeValueNotSet(uint8) | 0x7774d2f9 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawalAlreadyFinalized() | 0xae899454 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +AdminFacetTest ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================================================+ +| Function | acceptAdmin() | 0x0e18b681 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams((uint8,uint32,uint32,uint32,uint32,uint64)) | 0x64bf8d66 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0xa9f6d941 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(address,address,bytes) | 0x64b554ad | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(bytes,bool) | 0x3f42d5dd | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeDiamond() | 0x27ae4c16 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | genesisUpgrade(address,address,bytes,bytes[]) | 0x2878fe74 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAdmin() | 0x6e9960c3 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPendingAdmin() | 0xd0468156 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPorterAvailability() | 0xf90eb963 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityTxMaxGasLimit() | 0x0ec6b0b7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isValidator(address) | 0xfacd743b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | prepareChainCommitment() | 0x41cf49bb | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setDAValidatorPair(address,address) | 0x6223258e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(bool) | 0x1cc5d103 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256) | 0xbe6f11cf | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPubdataPricingMode(uint8) | 0xe76db865 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint128,uint128) | 0x235d9eb5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTransactionFilterer(address) | 0x21f603d7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(address,bool) | 0x4623c91d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeDiamond() | 0x17338945 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xfc57565f | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ExecuteUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x1dabfc3f4f6a4e74e19be10cc9d1d8e23db03e415d5d3547a1a7d5eb766513ba | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Freeze() | 0x615acbaede366d76a8b8cb2a9ada6a71495f0786513d71aa97aaf0c3910b78de | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | IsPorterAvailableStatusUpdate(bool) | 0x036b81a8a07344698cb5aa4142c5669a9317c9ce905264a08f0b9f9331883936 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationComplete() | 0x96e718f44bd77cb63370212c5aa24a0396d8f43e88e7ce175d160e371c8e2a6a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewBaseTokenMultiplier(uint128,uint128,uint128,uint128) | 0xc9cbdb110bd58a133e82c62b1488e57677be1f326df10a4d8096b5f170c370c8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewFeeParams((uint8,uint32,uint32,uint32,uint32,uint64),(uint8,uint32,uint32,uint32,uint32,uint64)) | 0xc8b245ac8b138b17b6b1dbbbb8860adc66b373afa000d99f3cdc775d8ae0bbed | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL1DAValidator(address,address) | 0x08b0b676d456a0431162145d2821f30c665b69ca626521c937ba7a77a29ed67c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DAValidator(address,address) | 0x866a71b85fb8625f74adc67901361962f0aa3730a1615400911ae610d65dc130 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityTxMaxGasLimit(uint256,uint256) | 0x83dd728f7e76a849126c55ffabdc6e299eb8c85dccf12498701376d9f5c954d1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewTransactionFilterer(address,address) | 0xa9b43a66c5d1c607986f49e932a0c08058d843210db03dd6e8a621b96b4770f4 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unfreeze() | 0x2f05ba71d0df11bf5fa562a6569d70c4f80da84284badbe015ce1456063d0ded | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorStatusUpdate(address,bool) | 0x065b77b53864e46fda3d8986acb51696223d6dde7ced42441eb150bae6d48136 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidiumModeStatusUpdate(uint8) | 0xaa01146df0a628c6b214e79a281f7524b792de4a52ad6f07c78e6e035d58c896 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainAlreadyLive() | 0x78d2ed02 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DenominatorIsZero() | 0x0a8ed92c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DiamondAlreadyFrozen() | 0x0e7ee319 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DiamondNotFrozen() | 0xa7151b9a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidPubdataPricingMode() | 0x6f1cf752 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PriorityTxPubdataExceedsMaxPubDataPerBatch() | 0x1a4d284a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolIdMismatch(uint256,uint256) | 0xa461f651 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolIdNotGreater() | 0x64f94ec2 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +CustomUpgradeTest ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Test() | 0xa163a6249e860c278ef4049759a7f7c7e8c141d30fd634fda9b5a6a95d111a30 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NewProtocolMajorVersionNotZero() | 0x72ea85ad | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousProtocolMajorVersionNotZero() | 0x5c598b60 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotCleaned() | 0xa0f47245 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionMinorDeltaTooBig(uint256,uint256) | 0xd328c12a | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DiamondCutTestContract ++----------+-------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=============================================================================================================================================+ +| Function | baseTokenGasPriceMultiplierDenominator() | 0x1de72e34 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenGasPriceMultiplierNominator() | 0xea6c029c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | diamondCut(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x4cc5b15e | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetAddress(bytes4) | 0xcdffacc6 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetAddresses() | 0x52ef6b2c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetFunctionSelectors(address) | 0xadfca15e | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facets() | 0x7a0ed627 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAdmin() | 0x6e9960c3 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBaseToken() | 0x98acd7a6 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBaseTokenAssetId() | 0x960dcf24 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBridgehub() | 0x3591c1a0 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainId() | 0x3408e470 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainTypeManager() | 0x946ebad1 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getDAValidatorPair() | 0x5a590335 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2BootloaderBytecodeHash() | 0xd86970d8 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2DefaultAccountBytecodeHash() | 0xfd791f3c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2SystemContractsUpgradeBatchNumber() | 0xe5355c75 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2SystemContractsUpgradeBlockNumber() | 0x9d1b5a81 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2SystemContractsUpgradeTxHash() | 0x7b30c8da | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPendingAdmin() | 0xd0468156 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityQueueSize() | 0x631f4bac | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityTreeRoot() | 0x39d7d4aa | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityTxMaxGasLimit() | 0x0ec6b0b7 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion() | 0x33ce93fe | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPubdataPricingMode() | 0x06d49e5b | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSettlementLayer() | 0x6a27e8b5 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesCommitted() | 0xdb1f0bf9 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesExecuted() | 0xb8c2f66f | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesVerified() | 0xef3f0bae | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBlocksCommitted() | 0xfe26699e | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBlocksExecuted() | 0x39607382 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBlocksVerified() | 0xaf6a2dcd | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTransactionFilterer() | 0x22c5cf23 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getVerifier() | 0x46657fe9 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getVerifierParams() | 0x18e3a941 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isDiamondStorageFrozen() | 0x29b98c67 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isEthWithdrawalFinalized(uint256,uint256) | 0xbd7c5412 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isFacetFreezable(address) | 0xc3bbd2d7 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isFunctionFreezable(bytes4) | 0xe81e0ba1 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isValidator(address) | 0xfacd743b | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2LogsRootHash(uint256) | 0x9cd939e4 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchHash(uint256) | 0xb22dd78e | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBlockHash(uint256) | 0x74f4d30d | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidSelector(bytes4) | 0x12ba286f | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|----------+-------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | ++----------+-------------------------------------------------------------+--------------------------------------------------------------------+ + +DiamondProxyTest ++----------+-----------------------+------------+ +| Type | Signature | Selector | ++===============================================+ +| Function | setFreezability(bool) | 0xbf529569 | ++----------+-----------------------+------------+ + +DummyAdminFacet ++----------+----------------------------+------------+ +| Type | Signature | Selector | ++====================================================+ +| Function | dummySetValidator(address) | 0x7321c485 | +|----------+----------------------------+------------| +| Function | getName() | 0x17d7de7c | ++----------+----------------------------+------------+ + +DummyAdminFacetNoOverlap ++----------+--------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==========================================================================================================================================================+ +| Function | executeUpgradeNoOverlap(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x68c09202 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | receiveEther() | 0xa3912ec8 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|----------+--------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | ++----------+--------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DummyBridgehub ++----------+-----------------------------+------------+ +| Type | Signature | Selector | ++=====================================================+ +| Function | baseTokenAssetId(uint256) | 0xe52db4ca | +|----------+-----------------------------+------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+-----------------------------+------------| +| Function | messageRoot() | 0xd4b9f4fa | +|----------+-----------------------------+------------| +| Function | setMessageRoot(address) | 0x70f5c679 | +|----------+-----------------------------+------------| +| Function | setSharedBridge(address) | 0xd0bf6fd4 | +|----------+-----------------------------+------------| +| Function | setZKChain(uint256,address) | 0xce214549 | +|----------+-----------------------------+------------| +| Function | sharedBridge() | 0x38720778 | +|----------+-----------------------------+------------| +| Function | zkChain() | 0x2b3558a6 | ++----------+-----------------------------+------------+ + +DummyBridgehubSetter ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================+ +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | MAX_NUMBER_OF_ZK_CHAINS() | 0x8f8d37a8 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_baseToken(uint256) | 0x5d83b6da | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | __DEPRECATED_tokenIsRegistered(address) | 0xeced0bf0 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addChainTypeManager(address) | 0xff5a62a1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | addTokenAssetId(bytes32) | 0x1c50cfea | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetIdIsRegistered(bytes32) | 0xe0ab6368 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetRouter() | 0xbc0aac10 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseToken(uint256) | 0x59ec65a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenAssetId(uint256) | 0xe52db4ca | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xc2e90293 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManager(uint256) | 0x9d5bd3da | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManagerIsRegistered(address) | 0xb93c9366 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,address,bytes32,uint256,address,bytes,bytes[]) | 0xf113c88b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromAddress(address) | 0x70fccb52 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdFromChainId(uint256) | 0x24358c61 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | ctmAssetIdToAddress(bytes32) | 0x07621f84 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardTransactionOnGateway(uint256,bytes32,uint64) | 0x524c0cfa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChainChainIDs() | 0x68b8d331 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAllZKChains() | 0x49707f31 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initializeV2() | 0x5cd8a76b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1CtmDeployer() | 0xcbe83612 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256,uint256) | 0x71623274 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | messageRoot() | 0xd4b9f4fa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | migrationPaused() | 0x2a641114 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pauseMigration() | 0xac700e63 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(uint256,bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xb292f5f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0xe6d9923b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,uint256,(uint16,address,bytes),bytes32[]) | 0x99c16d1a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerAlreadyDeployedZKChain(uint256,address) | 0xb5662c5d | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | removeChainTypeManager(address) | 0x332b96dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionDirect((uint256,uint256,address,uint256,bytes,uint256,uint256,bytes[],address)) | 0xd52471c1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionTwoBridges((uint256,uint256,uint256,uint256,uint256,address,address,uint256,bytes)) | 0x24fd57fb | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAddresses(address,address,address) | 0x363bf964 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddress(bytes32,address) | 0x3f704d2a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setCTM(uint256,address) | 0xa52c6753 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyBaseTokenAssetId(uint256) | 0xca8f93f1 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyChainAddress(uint256) | 0xd92f86a2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setZKChain(uint256,address) | 0xce214549 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | settlementLayer(uint256) | 0x671a7131 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | sharedBridge() | 0x38720778 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpauseMigration() | 0xf7c7eb92 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | whitelistedSettlementLayers(uint256) | 0xe9420f8c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | AssetRegistered(bytes32,address,bytes32,address) | 0x8f09d7694a9ae17acec5cf132d594d7eee23572f7fe132396ce72b1afbf7ef20 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BaseTokenAssetIdRegistered(bytes32) | 0x3df150949161462acf3be30521d7da9e533b247327a254e55dd01875897a6df3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerAdded(address) | 0x2eae91be1021e05cc8076387b0182458ae474ae44ee44cc59aefda6ca53c1f42 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChainTypeManagerRemoved(address) | 0x4e04a497739580efe78a7ee09cdabe6f6fe90965c683292a519102ce5193b68a | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationFinalized(uint256,bytes32,address) | 0xb0cc16029b506b2a262b52711e71db4fcd1cb078bd4bb86c7ba82cd3be2eadd3 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationStarted(uint256,bytes32,uint256) | 0xc60eb6d595da5361c68f60aa7c8286b8f73c3a99e9db1818e146c522f512496f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChain(uint256,address,address) | 0x1e9125bc72db22c58abff6821d7333551967e26454b419ffa958e4cb8ef47600 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | SettlementLayerRegistered(uint256,bool) | 0x02629feb109d94b16a367231d248ba81c462f51ce5b984835f150f1c9f49ed25 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressTooLow(address) | 0x1eee5481 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetHandlerNotRegistered(bytes32) | 0x64107968 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdAlreadyRegistered() | 0xfe919e28 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BridgeHubAlreadyRegistered() | 0x6cf12312 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CTMAlreadyRegistered() | 0xec273439 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CTMNotRegistered() | 0xc630ef3c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainAlreadyLive() | 0x78d2ed02 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdAlreadyExists() | 0x24591d89 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdCantBeCurrentChain() | 0x717a1656 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdMismatch() | 0xa179f8c9 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdNotRegistered(uint256) | 0x23f3c357 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainIdTooBig() | 0x8f620a06 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainNotLegacy() | 0x5de72107 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyAssetId() | 0x2d4d012f | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | IncorrectBridgeHubAddress(address) | 0xdd381a4c | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MigrationPaused() | 0x3312a450 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MsgValueMismatch(uint256,uint256) | 0x4a094431 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SharedBridgeNotSet() | 0x856d5b77 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WrongMagicValue(uint256,uint256) | 0x15e8e429 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZKChainLimitReached() | 0x601b6882 | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | +|----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroChainId() | 0xc84885d4 | ++----------+---------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DummyChainTypeManager ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams(uint256,(uint8,uint32,uint32,uint32,uint32,uint64)) | 0x027f12e1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,bytes32,address,bytes,bytes[]) | 0x88c7c5d2 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xe34a329a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(uint256,bytes) | 0xf85894c5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(uint256,bytes) | 0xe8a71ca9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeChain(uint256) | 0xaccdd16c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainAdmin(uint256) | 0x301e7765 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion(uint256) | 0xba238947 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChainLegacy(uint256) | 0x4caa740f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialCutHash() | 0x57e6246b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialForceDeploymentHash() | 0x61f91b2e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize((address,address,(address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes),uint256)) | 0xce7df3d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1GenesisUpgrade() | 0x3437949a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersion() | 0x2ae9c600 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionDeadline(uint256) | 0xf4943a20 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionIsActive(uint256) | 0xdef9d6af | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatches(uint256,uint256) | 0x53ce2061 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setChainCreationParams((address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes)) | 0x9b016b8b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNewVersionUpgrade(((address,uint8,bool,bytes4[])[],address,bytes),uint256,uint256,uint256) | 0x2e522851 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(uint256,bool) | 0x18717dc1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256,uint256) | 0xec3d5f88 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setProtocolVersionDeadline(uint256,uint256) | 0xaad74262 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint256,uint128,uint128) | 0x7ebba672 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setUpgradeDiamondCut(((address,uint8,bool,bytes4[])[],address,bytes),uint256) | 0x98461504 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(uint256,address,bool) | 0xcf347e17 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidatorTimelock(address) | 0x7fb67816 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setZKChain(uint256,address) | 0xce214549 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchZero() | 0xd2ef1b0e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeChain(uint256) | 0x51d218f7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0x0dbad27e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeCutHash(uint256) | 0x52c9eacb | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | validatorTimelock() | 0xe66c8c44 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256) | 0x778b7f95aad9610955002f243aabbbf9546bb6e792f7b3b89dab86b4f210e30f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChainCreationParams(address,bytes32,uint64,bytes32,bytes32,bytes32) | 0x04b363b4a0200ada216b1cb4aaf2736ff6f332d5f1d90f98e60b1159f3dac3aa | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutData(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xf99295383247eabb6bee8798669fa768502f8843d3be0e82a0aa81d7b6c4f60c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutHash(uint256,bytes32) | 0x71b0aeaf8eaa06ed78ccb9a4981da026eea05ca1d818c22dd120446db4c936d4 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewValidatorTimelock(address,address) | 0x5a1b0d8808a8dca64c1f7c230dce7a09f7f9a1c26507e190e03dcd382e69018e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewZKChain(uint256,address) | 0xf83c256407747903308213919067f883f683c5cde6a64ebbf25096b8bb555ddc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchCommitmentZero() | 0x6d4a7df8 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchHashZero() | 0x7940c83f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisIndexStorageZero() | 0xb4fc6835 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisUpgradeZero() | 0x3a1a8589 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DummyChainTypeManagerWBH ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams(uint256,(uint8,uint32,uint32,uint32,uint32,uint64)) | 0x027f12e1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,bytes32,address,bytes,bytes[]) | 0x88c7c5d2 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xe34a329a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(uint256,bytes) | 0xf85894c5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(uint256,bytes) | 0xe8a71ca9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeChain(uint256) | 0xaccdd16c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainAdmin(uint256) | 0x301e7765 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion(uint256) | 0xba238947 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChainLegacy(uint256) | 0x4caa740f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialCutHash() | 0x57e6246b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialForceDeploymentHash() | 0x61f91b2e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize((address,address,(address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes),uint256)) | 0xce7df3d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1GenesisUpgrade() | 0x3437949a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersion() | 0x2ae9c600 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionDeadline(uint256) | 0xf4943a20 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionIsActive(uint256) | 0xdef9d6af | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatches(uint256,uint256) | 0x53ce2061 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setChainCreationParams((address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes)) | 0x9b016b8b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNewVersionUpgrade(((address,uint8,bool,bytes4[])[],address,bytes),uint256,uint256,uint256) | 0x2e522851 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(uint256,bool) | 0x18717dc1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256,uint256) | 0xec3d5f88 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setProtocolVersionDeadline(uint256,uint256) | 0xaad74262 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint256,uint128,uint128) | 0x7ebba672 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setUpgradeDiamondCut(((address,uint8,bool,bytes4[])[],address,bytes),uint256) | 0x98461504 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(uint256,address,bool) | 0xcf347e17 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidatorTimelock(address) | 0x7fb67816 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setZKChain(uint256,address) | 0xce214549 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchZero() | 0xd2ef1b0e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeChain(uint256) | 0x51d218f7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0x0dbad27e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeCutHash(uint256) | 0x52c9eacb | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | validatorTimelock() | 0xe66c8c44 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256) | 0x778b7f95aad9610955002f243aabbbf9546bb6e792f7b3b89dab86b4f210e30f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChainCreationParams(address,bytes32,uint64,bytes32,bytes32,bytes32) | 0x04b363b4a0200ada216b1cb4aaf2736ff6f332d5f1d90f98e60b1159f3dac3aa | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutData(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xf99295383247eabb6bee8798669fa768502f8843d3be0e82a0aa81d7b6c4f60c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutHash(uint256,bytes32) | 0x71b0aeaf8eaa06ed78ccb9a4981da026eea05ca1d818c22dd120446db4c936d4 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewValidatorTimelock(address,address) | 0x5a1b0d8808a8dca64c1f7c230dce7a09f7f9a1c26507e190e03dcd382e69018e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewZKChain(uint256,address) | 0xf83c256407747903308213919067f883f683c5cde6a64ebbf25096b8bb555ddc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchCommitmentZero() | 0x6d4a7df8 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchHashZero() | 0x7940c83f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisIndexStorageZero() | 0xb4fc6835 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisUpgradeZero() | 0x3a1a8589 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DummySharedBridge ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=======================================================================================================================================================================================+ +| Function | assetHandlerAddress(bytes32) | 0x53b9e632 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubConfirmL2Transaction(uint256,bytes32,bytes32) | 0x8eb7db57 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDeposit(uint256,address,uint256,bytes) | 0xca408c23 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubDepositBaseToken(uint256,bytes32,address,uint256) | 0xc4879440 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainBalance(uint256,address) | 0x9cd45184 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(uint256,address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0xc0991525 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDepositLegacyErc20Bridge(address,address,uint256,bytes32,uint256,uint256,uint16,bytes32[]) | 0x8fbb3711 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositLegacyErc20Bridge(address,address,address,uint256,uint256,uint256,address) | 0x9e6ea417 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint256,uint16,bytes,bytes32[]) | 0xc87325f1 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawalLegacyErc20Bridge(uint256,uint256,uint16,bytes,bytes32[]) | 0x7ab08472 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | nativeTokenVault() | 0x64e130cf | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | receiveEth(uint256) | 0xc2aaf9c4 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setAssetHandlerAddressThisChain(bytes32,address) | 0x548a5a33 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setDataToBeReturnedInFinalizeWithdrawal(address,address,uint256) | 0xa6f2c076 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNativeTokenVault(address) | 0x0f3fa211 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgehubDepositBaseTokenInitiated(uint256,address,bytes32,uint256) | 0x0f87e1ea5eb1f034a6071ef630c174063e3d48756f853efaaf4292b929298240 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Debugger(uint256) | 0x8d9c8ca1e649d98242c05e8424ce820b45ac79086a871220eec3a570ac0a9828 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | ++----------+-------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DummyZKChain ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===================================================================================================================================================================================================================================================================+ +| Function | bridgehubRequestL2Transaction((address,address,uint256,uint256,bytes,uint256,uint256,bytes[],address)) | 0x12f43dab | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2TransactionOnGateway(bytes32,uint64) | 0xddcc9eec | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeEthWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x6c0960f9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | genesisUpgrade(address,bytes,bytes[]) | 0xa3bd0112 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBridgeHubAddress() | 0x8466d8d1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getEraChainId() | 0xe23d2563 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256) | 0xb473318e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0x042901c7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatusViaGateway(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xe717bab7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LeafInclusion(uint256,uint256,bytes32,bytes32[]) | 0x7efda2ae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0x263b7f8e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,(uint16,address,bytes),bytes32[]) | 0xe4948f43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2Transaction(address,uint256,bytes,uint256,uint256,bytes[],address) | 0xeb672419 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionToGatewayMailbox(uint256,bytes32,uint64) | 0xd0772551 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setBaseTokenGasMultiplierPrice(uint128,uint128) | 0x328ef4fe | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setBridgeHubAddress(address) | 0x8ffe1b81 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setFeeParams() | 0x47fcedb8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityRequest(uint256,bytes32,uint64,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[]) | 0x4531cd5795773d7101c17bdeb9f5ab7f47d7056017506f937083be5d6e77a382 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewRelayedPriorityTransaction(uint256,bytes32,uint64) | 0x0137d2eaa6ec5b7e4f233f6d6f441410014535d0f3985367994c94bf15a2a564 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BaseTokenGasPriceDenominatorNotSet() | 0x6ef9a972 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNotExecuted(uint256) | 0x2078a6a0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GasPerPubdataMismatch() | 0xc91cf3b1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashedLogIsDefault() | 0xd356e6ba | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerkleIndexOutOfBounds() | 0x9bb54c35 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MsgValueTooLow(uint256,uint256) | 0xb385a3da | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OnlyEraSupported() | 0xf3ed9dfa | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TransactionNotAllowed() | 0x00c5a6a9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +ExecutorProvingTest ++----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================================================================================================+ +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createBatchCommitment((uint64,uint64,uint64,bytes32,uint256,bytes32,bytes32,bytes32,bytes,bytes),bytes32,bytes32[],bytes32[]) | 0xc1899c1d | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBatchProofPublicInput(bytes32,bytes32) | 0x868085b1 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | processL2Logs((uint64,uint64,uint64,bytes32,uint256,bytes32,bytes32,bytes32,bytes,bytes),bytes32,uint8) | 0xc75ac8fa | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setHashes(bytes32,bytes32) | 0xced531eb | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchHashMismatch(bytes32,bytes32) | 0x55ad3fd3 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNumberMismatch(uint256,uint256) | 0xbd4455ff | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CanOnlyProcessOneBatch() | 0xe85392f9 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantExecuteUnprovenBatches() | 0x00c6ead2 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantRevertExecutedBatch() | 0xe18cb383 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyData() | 0x99d8fec9 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | IncorrectBatchBounds(uint256,uint256,uint256,uint256) | 0xd7d93e1f | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidLogSender(address,uint256) | 0xc1780bd6 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidNumberOfBlobs(uint256,uint256,uint256) | 0xd8e9405c | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProof() | 0x09bde339 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProtocolVersion() | 0x5428eae7 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2TimestampTooBig() | 0xfb5c22e6 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LogAlreadyProcessed(uint8) | 0x1b6825bb | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MissingSystemLogs(uint256,uint256) | 0xfa44b527 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonIncreasingTimestamp() | 0xd018e08e | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonSequentialBatch() | 0x0105f9c0 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PriorityOperationsRollingHashMismatch() | 0xd5a99014 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | QueueIsEmpty() | 0x63c36549 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RevertedBatchNotAfterNewLastBatch() | 0x9a67c1cb | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SystemLogsSizeTooBig() | 0xae43b424 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimestampError() | 0x2d50c33b | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxHashMismatch() | 0x4c991078 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedSystemLog(uint256) | 0x6aa39880 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedCommitBatchEncoding(uint8) | 0xf3dd1b9c | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedExecuteBatchEncoding(uint8) | 0x14d2ed8a | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedProofBatchEncoding(uint8) | 0xf338f830 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UpgradeBatchNumberIsNotZero() | 0xf093c2e5 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | VerifiedBatchesExceedsCommittedBatches() | 0xe1022469 | ++----------+-------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +FullMerkleTest ++----------+-------------------------------------------+------------+ +| Type | Signature | Selector | ++===================================================================+ +| Function | height() | 0x0ef26743 | +|----------+-------------------------------------------+------------| +| Function | index() | 0x2986c0e5 | +|----------+-------------------------------------------+------------| +| Function | node(uint256,uint256) | 0xae65def1 | +|----------+-------------------------------------------+------------| +| Function | nodeCount(uint256) | 0xcdc4878b | +|----------+-------------------------------------------+------------| +| Function | pushNewLeaf(bytes32) | 0xb6ea1757 | +|----------+-------------------------------------------+------------| +| Function | root() | 0xebf0c717 | +|----------+-------------------------------------------+------------| +| Function | updateAllLeaves(bytes32[]) | 0x505e6d47 | +|----------+-------------------------------------------+------------| +| Function | updateAllNodesAtHeight(uint256,bytes32[]) | 0x580d6bff | +|----------+-------------------------------------------+------------| +| Function | updateLeaf(uint256,bytes32) | 0xfcc73360 | +|----------+-------------------------------------------+------------| +| Function | zeros(uint256) | 0xe8295588 | ++----------+-------------------------------------------+------------+ + +IncrementalMerkleTest ++----------+----------------+------------+ +| Type | Signature | Selector | ++========================================+ +| Function | height() | 0x0ef26743 | +|----------+----------------+------------| +| Function | index() | 0x2986c0e5 | +|----------+----------------+------------| +| Function | push(bytes32) | 0xb298e36b | +|----------+----------------+------------| +| Function | root() | 0xebf0c717 | +|----------+----------------+------------| +| Function | side(uint256) | 0x7890e5da | +|----------+----------------+------------| +| Function | zeros(uint256) | 0xe8295588 | ++----------+----------------+------------+ + +L1ERC20BridgeTest ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==============================================================================================================================================================+ +| Function | ERA_CHAIN_ID() | 0xef011dff | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NATIVE_TOKEN_VAULT() | 0x293e8520 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_NULLIFIER() | 0xe60ccaba | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | claimFailedDeposit(address,address,bytes32,uint256,uint256,uint16,bytes32[]) | 0x19fa7f62 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256) | 0x933999fb | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | deposit(address,address,uint256,uint256,uint256,address) | 0xe8b99b1b | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | depositAmount(address,address,bytes32) | 0x01eae183 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x11a2ccc1 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize() | 0x8129fc1c | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isWithdrawalFinalized(uint256,uint256) | 0x4bed8212 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2Bridge() | 0xae1f6aaf | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenBeacon() | 0x6dde7209 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenProxyBytecodeHash() | 0x823f1d96 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ClaimedFailedDeposit(address,address,uint256) | 0xbe066dc591f4a444f75176d387c3e6c775e5706d9ea9a91d11eb49030c66cf60 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DepositInitiated(bytes32,address,address,address,uint256) | 0xdd341179f4edc78148d894d0213a96d212af2cbaf223d19ef6d483bdd47ab81d | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalFinalized(address,address,uint256) | 0xac1b18083978656d557d6e91c88203585cfda1031bdb14538327121ef140d383 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ApprovalFailed() | 0x8164f842 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ETHDepositNotSupported() | 0x627e0872 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | WithdrawalAlreadyFinalized() | 0xae899454 | ++----------+------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L2NativeTokenVaultDev ++----------+------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++======================================================================================================================================+ +| Function | ASSET_ROUTER() | 0xc6a70bbb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | BASE_TOKEN_ASSET_ID() | 0xcb944dec | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_CHAIN_ID() | 0x2f90b184 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | L2_LEGACY_SHARED_BRIDGE() | 0xc438a9f2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | WETH_TOKEN() | 0x37d277d4 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | assetId(address) | 0xfd3f60df | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeBurn(uint256,uint256,bytes32,address,bytes) | 0x699b0fb9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgeMint(uint256,bytes32,bytes) | 0x36ba0355 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgedTokenBeacon() | 0xf2d44246 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | calculateCreate2TokenAddress(uint256,address) | 0xc487412c | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | deployBridgedStandardERC20(address) | 0xbfff27c2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | ensureTokenIsRegistered(address) | 0x19a2a285 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | getERC20Getters(address,uint256) | 0xa7236d16 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TokenAddress(address) | 0xf5f15168 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | originChainId(bytes32) | 0x5f3455b5 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | pause() | 0x8456cb59 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | paused() | 0x5c975abb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerToken(address) | 0x09824a80 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | setLegacyTokenAssetId(address) | 0x4cd40a02 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | test() | 0xf8a8fd6d | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenAddress(bytes32) | 0x97bb3ce9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | tokenDataOriginChainId(bytes) | 0x07a6d4bc | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Function | unpause() | 0x3f4ba83a | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeBurn(uint256,bytes32,address,address,uint256) | 0x1cd02155ad1064c60598a8bd0e4e795d7e7d0a0f3c38aad04d261f1297fb2545 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(uint256,bytes32,address,uint256) | 0xbc0f4055a7869d8ecad34b33382a0bc181c5811565fec42f335505be5fd661d2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgedTokenBeaconUpdated(address,bytes32) | 0xc3f14dba68f86c42f518e5c0e8a5cbc9514da6f388e2f52c5b1a6263d8588bfb | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | FinalizeDeposit(address,address,address,uint256) | 0xb84fba9af218da60d299dc177abd5805e7ac541d2673cbee7808c10017874f63 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | L2TokenBeaconUpdated(address,bytes32) | 0x01fd5911e6d04aec6b21f19752502ad7f3e9876279643c8fa7a4d30c88a29fb2 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Paused(address) | 0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unpaused(address) | 0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Event | WithdrawalInitiated(address,address,address,uint256) | 0x2fc3848834aac8e883a2d2a17a7514dc4f2d3dd268089df9b9f5d918259ef3b0 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressMismatch(address,address) | 0x1f73225f | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AmountMustBeGreaterThanZero() | 0x5e85ae73 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdMismatch(bytes32,bytes32) | 0x1294e9e1 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | AssetIdNotSupported(bytes32) | 0x04a0b7e9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | DeployingBridgedTokenForNativeToken() | 0x138ee1a3 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyAddress() | 0x7138356f | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyBytes32() | 0x1c25715b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyDeposit() | 0x95b66fe9 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyMsgValue() | 0x536ec84b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokenNotSupported(address) | 0x06439c6b | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | TokensWithFeesNotSupported() | 0x23830e28 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedEncodingVersion() | 0x084a1449 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+------------------------------------------------------+--------------------------------------------------------------------+ + +MailboxFacetTest ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===================================================================================================================================================================================================================================================================+ +| Function | bridgehubRequestL2Transaction((address,address,uint256,uint256,bytes,uint256,uint256,bytes[],address)) | 0x12f43dab | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2TransactionOnGateway(bytes32,uint64) | 0xddcc9eec | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeEthWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x6c0960f9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2GasPrice(uint256) | 0xab07b2e9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256) | 0xb473318e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0x042901c7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatusViaGateway(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xe717bab7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LeafInclusion(uint256,uint256,bytes32,bytes32[]) | 0x7efda2ae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0x263b7f8e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,(uint16,address,bytes),bytes32[]) | 0xe4948f43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2Transaction(address,uint256,bytes,uint256,uint256,bytes[],address) | 0xeb672419 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionToGatewayMailbox(uint256,bytes32,uint64) | 0xd0772551 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setFeeParams((uint8,uint32,uint32,uint32,uint32,uint64)) | 0xb4866c43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityRequest(uint256,bytes32,uint64,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[]) | 0x4531cd5795773d7101c17bdeb9f5ab7f47d7056017506f937083be5d6e77a382 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewRelayedPriorityTransaction(uint256,bytes32,uint64) | 0x0137d2eaa6ec5b7e4f233f6d6f441410014535d0f3985367994c94bf15a2a564 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BaseTokenGasPriceDenominatorNotSet() | 0x6ef9a972 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNotExecuted(uint256) | 0x2078a6a0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GasPerPubdataMismatch() | 0xc91cf3b1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashedLogIsDefault() | 0xd356e6ba | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerkleIndexOutOfBounds() | 0x9bb54c35 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MsgValueTooLow(uint256,uint256) | 0xb385a3da | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OnlyEraSupported() | 0xf3ed9dfa | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TransactionNotAllowed() | 0x00c5a6a9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +MerkleTest ++----------+------------------------------------------------------+------------+ +| Type | Signature | Selector | ++==============================================================================+ +| Function | calculateRoot(bytes32[],uint256,bytes32) | 0x7a592065 | +|----------+------------------------------------------------------+------------| +| Function | calculateRoot(bytes32[],bytes32[],uint256,bytes32[]) | 0xee7fb38b | +|----------+------------------------------------------------------+------------| +| Error | MerkleIndexOutOfBounds() | 0x9bb54c35 | +|----------+------------------------------------------------------+------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+------------------------------------------------------+------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | ++----------+------------------------------------------------------+------------+ + +MockExecutorFacet ++----------+-------------------------------------+------------+ +| Type | Signature | Selector | ++=============================================================+ +| Function | saveL2LogsRootHash(uint256,bytes32) | 0x8a75bb09 | +|----------+-------------------------------------+------------| +| Function | setExecutedBatches(uint256) | 0x59890bcb | ++----------+-------------------------------------+------------+ + +PriorityQueueTest ++----------+------------------------------------+------------+ +| Type | Signature | Selector | ++============================================================+ +| Function | front() | 0xba75bbd8 | +|----------+------------------------------------+------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+------------------------------------+------------| +| Function | getSize() | 0xde8fa431 | +|----------+------------------------------------+------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+------------------------------------+------------| +| Function | isEmpty() | 0x681fe70c | +|----------+------------------------------------+------------| +| Function | popFront() | 0x84d9fedd | +|----------+------------------------------------+------------| +| Function | pushBack((bytes32,uint64,uint192)) | 0x75fe6a99 | +|----------+------------------------------------+------------| +| Error | QueueIsEmpty() | 0x63c36549 | ++----------+------------------------------------+------------+ + +PriorityTreeTest ++----------+---------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=================================================================================+ +| Function | getCommitment() | 0x2a79c611 | +|----------+---------------------------------------------------------+------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+---------------------------------------------------------+------------| +| Function | getRoot() | 0x5ca1e165 | +|----------+---------------------------------------------------------+------------| +| Function | getSize() | 0xde8fa431 | +|----------+---------------------------------------------------------+------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+---------------------------------------------------------+------------| +| Function | getZero() | 0x9f3f89dc | +|----------+---------------------------------------------------------+------------| +| Function | initFromCommitment((uint256,uint256,uint256,bytes32[])) | 0x4636d6f9 | +|----------+---------------------------------------------------------+------------| +| Function | processBatch((bytes32[],bytes32[],bytes32[])) | 0xc9daf4b1 | +|----------+---------------------------------------------------------+------------| +| Function | push(bytes32) | 0xb298e36b | +|----------+---------------------------------------------------------+------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+---------------------------------------------------------+------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | ++----------+---------------------------------------------------------+------------+ + +TestExecutor ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===========================================================================================================================================+ +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTreeStartIndex(uint256) | 0xa9b0d128 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchHashMismatch(bytes32,bytes32) | 0x55ad3fd3 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNumberMismatch(uint256,uint256) | 0xbd4455ff | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CanOnlyProcessOneBatch() | 0xe85392f9 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantExecuteUnprovenBatches() | 0x00c6ead2 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantRevertExecutedBatch() | 0xe18cb383 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyData() | 0x99d8fec9 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | IncorrectBatchBounds(uint256,uint256,uint256,uint256) | 0xd7d93e1f | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidLogSender(address,uint256) | 0xc1780bd6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidNumberOfBlobs(uint256,uint256,uint256) | 0xd8e9405c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProof() | 0x09bde339 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProtocolVersion() | 0x5428eae7 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2TimestampTooBig() | 0xfb5c22e6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | LogAlreadyProcessed(uint8) | 0x1b6825bb | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MissingSystemLogs(uint256,uint256) | 0xfa44b527 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonIncreasingTimestamp() | 0xd018e08e | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonSequentialBatch() | 0x0105f9c0 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | PriorityOperationsRollingHashMismatch() | 0xd5a99014 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | QueueIsEmpty() | 0x63c36549 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | RevertedBatchNotAfterNewLastBatch() | 0x9a67c1cb | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | SystemLogsSizeTooBig() | 0xae43b424 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimestampError() | 0x2d50c33b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxHashMismatch() | 0x4c991078 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedSystemLog(uint256) | 0x6aa39880 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedCommitBatchEncoding(uint8) | 0xf3dd1b9c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedExecuteBatchEncoding(uint8) | 0x14d2ed8a | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedProofBatchEncoding(uint8) | 0xf338f830 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UpgradeBatchNumberIsNotZero() | 0xf093c2e5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | VerifiedBatchesExceedsCommittedBatches() | 0xe1022469 | ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +AccessControlRestriction ++----------+-------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=================================================================================================================================+ +| Function | DEFAULT_ADMIN_ROLE() | 0xa217fddf | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptDefaultAdminTransfer() | 0xcefc1429 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | beginDefaultAdminTransfer(address) | 0x634e93da | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | cancelDefaultAdminTransfer() | 0xd602b9fd | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | changeDefaultAdminDelay(uint48) | 0x649a5ec7 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | defaultAdmin() | 0x84ef8ffc | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | defaultAdminDelay() | 0xcc8463c8 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | defaultAdminDelayIncreaseWait() | 0x022d63fb | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | getRoleAdmin(bytes32) | 0x248a9ca3 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | getSupportsRestrictionMagic() | 0x83e866f5 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | grantRole(bytes32,address) | 0x2f2ff15d | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | hasRole(bytes32,address) | 0x91d14854 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingDefaultAdmin() | 0xcf6eefb7 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingDefaultAdminDelay() | 0xa1eda53c | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceRole(bytes32,address) | 0x36568abe | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | requiredRoles(address,bytes4) | 0x3f620077 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | requiredRolesForFallback(address) | 0x92c25350 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | revokeRole(bytes32,address) | 0xd547741f | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | rollbackDefaultAdminDelay() | 0x0aa6220b | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | setRequiredRoleForCall(address,bytes4,bytes32) | 0xb915e405 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | setRequiredRoleForFallback(address,bytes32) | 0x2de34186 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | supportsInterface(bytes4) | 0x01ffc9a7 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Function | validateCall((address,uint256,bytes),address) | 0x9a9debe9 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | DefaultAdminDelayChangeCanceled() | 0x2b1fa2edafe6f7b9e97c1a9e0c3660e645beb2dcaa2d45bdbf9beaf5472e1ec5 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | DefaultAdminDelayChangeScheduled(uint48,uint48) | 0xf1038c18cf84a56e432fdbfaf746924b7ea511dfe03a6506a0ceba4888788d9b | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | DefaultAdminTransferCanceled() | 0x8886ebfc4259abdbc16601dd8fb5678e54878f47b3c34836cfc51154a9605109 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | DefaultAdminTransferScheduled(address,uint48) | 0x3377dc44241e779dd06afab5b788a35ca5f3b778836e2990bdb26a2a4b2e5ed6 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | FallbackRoleSet(address,bytes32) | 0xacb22a6b6e4593545bea6f5cdd10238b8a592aba079d9cfc76adb71edf02d40b | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | RoleAdminChanged(bytes32,bytes32,bytes32) | 0xbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | RoleGranted(bytes32,address,address) | 0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | RoleRevoked(bytes32,address,address) | 0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Event | RoleSet(address,bytes4,bytes32) | 0x25c1ec7629ef447de39798ef5e6e0da89139b2257681441b45f1779c3efda036 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Error | AccessToFallbackDenied(address,address) | 0x5ecf2d7a | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Error | AccessToFunctionDenied(address,bytes4,address) | 0x3995f750 | +|----------+-------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-------------------------------------------------+--------------------------------------------------------------------+ + +ChainAdmin ++----------+--------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++==================================================================================================================================+ +| Function | addRestriction(address) | 0x33163987 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | getRestrictions() | 0xc4195cb8 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | isRestrictionActive(address) | 0x02f0277d | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | multicall((address,uint256,bytes)[],bool) | 0x69340beb | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionToUpgradeTimestamp(uint256) | 0xede25608 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | removeRestriction(address) | 0x69a5b950 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Function | setUpgradeTimestamp(uint256,uint256) | 0xe2a9d554 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | CallExecuted((address,uint256,bytes),bool,bytes) | 0x157c677a40c50f832f816d7b59c8c3e94774acae328c8ccb145b73aea7566d75 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | RestrictionAdded(address) | 0x83cfa0dec28fa91596ce8081b6279e7d1c402d3d4bc40934fc51f8830e7d82c6 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | RestrictionRemoved(address) | 0xdf4f1ec932dcab3c66fb7845ba6fc669816121e5d4a81d6955d3c6d3bff7b7e9 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Event | UpdateUpgradeTimestamp(uint256,uint256) | 0xd50ef21701c8ef211433b140724b8d6de471e7d822c8a616c3d424fe2d0e98a9 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | NoCallsProvided() | 0x79cc2d22 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | NotARestriction(address) | 0x64846fe4 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | OnlySelfAllowed() | 0x6c167909 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | RestrictionWasAlreadyPresent(address) | 0xf126e113 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | RestrictionWasNotPresent(address) | 0x52e22c98 | +|----------+--------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | ++----------+--------------------------------------------------+--------------------------------------------------------------------+ + +Governance ++----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++============================================================================================================================================================================+ +| Function | acceptOwnership() | 0x79ba5097 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | cancel(bytes32) | 0xc4d252f5 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | execute(((address,uint256,bytes)[],bytes32,bytes32)) | 0x74da756b | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeInstant(((address,uint256,bytes)[],bytes32,bytes32)) | 0x95218ecd | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getOperationState(bytes32) | 0x7958004c | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | hashOperation(((address,uint256,bytes)[],bytes32,bytes32)) | 0xc126e860 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperation(bytes32) | 0x31d50750 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationDone(bytes32) | 0x2ab0f529 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationPending(bytes32) | 0x584b153e | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isOperationReady(bytes32) | 0x13bc9f20 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | minDelay() | 0xc63c4e9b | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | scheduleShadow(bytes32,uint256) | 0x6d1d8363 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | scheduleTransparent(((address,uint256,bytes)[],bytes32,bytes32),uint256) | 0x2c431917 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | securityCouncil() | 0x27eb6c0f | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | timestamps(bytes32) | 0xb5872958 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | updateDelay(uint256) | 0x64d62353 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | updateSecurityCouncil(address) | 0xdbfe3e96 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChangeMinDelay(uint256,uint256) | 0x0c5ff76c31d24175d9e84ef46e328eafbcaeb2aa67a2333035eb082dd34324f1 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ChangeSecurityCouncil(address,address) | 0xe55ac8ae7914efca1278b8ed4ae21728d06ad9f6e7637bb2c905aacf2a6f5951 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OperationCancelled(bytes32) | 0xcf0f63b97f3387253cbc0bde884f975df77e39184dc3280c2c81be495f58eef4 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OperationExecuted(bytes32) | 0x1277662f4b42b8a4069e99fb5e41ce8919d3c621156090ac08fb11adbcec66f9 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ShadowOperationScheduled(bytes32,uint256) | 0xbcb40fd953364ec8aed99fa0bd6dcc03103f979efde4744ad7452e556ff20ba6 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | TransparentOperationScheduled(bytes32,uint256,((address,uint256,bytes)[],bytes32,bytes32)) | 0x23bc9f5dc037eb49c162fd08c2a4d43dfe70063149e140d502273168da0a0625 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidDelay() | 0x4fbe5dba | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OperationExists() | 0x1a21feed | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OperationMustBePending() | 0xeda2fbb1 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OperationMustBeReady() | 0xe1c1ff37 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousOperationNotExecuted() | 0x9b48e060 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+--------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +L2AdminFactory ++----------+--------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================+ +| Function | deployAdmin(address[],bytes32) | 0x8f466729 | +|----------+--------------------------------+--------------------------------------------------------------------| +| Function | requiredRestrictions(uint256) | 0x63cf72b8 | +|----------+--------------------------------+--------------------------------------------------------------------| +| Event | AdminDeployed(address) | 0xc2be628060b55b6da5404f7ce7a00e0996aa76a0a6447b084fdc5af1b056cb40 | +|----------+--------------------------------+--------------------------------------------------------------------| +| Error | NotARestriction(address) | 0x64846fe4 | ++----------+--------------------------------+--------------------------------------------------------------------+ + +PermanentRestriction ++----------+-----------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===============================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | L2_ADMIN_FACTORY() | 0x8761cf4b | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | allowAdminImplementation(bytes32,bool) | 0xce21e9cd | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | allowL2Admin(bytes32,bytes32,bytes32) | 0xa1603458 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | allowedAdminImplementations(bytes32) | 0x1b808213 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | allowedCalls(bytes) | 0x5c2bdd21 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | allowedL2Admins(address) | 0xac1cb217 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | getSupportsRestrictionMagic() | 0x83e866f5 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | setAllowedData(bytes,bool) | 0xdbaabcfd | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | setSelectorIsValidated(bytes4,bool) | 0x636ccb60 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | validateCall((address,uint256,bytes),address) | 0x9a9debe9 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Function | validatedSelectors(bytes4) | 0x430d2d36 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | AdminImplementationAllowed(bytes32,bool) | 0xb9b1bc97b8d56d15ac2abdd71d788b0d6e14dc92fa9b8df811d0a2f41c14354a | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | AllowL2Admin(address) | 0x43472806f9101fbc243f5a64948e56332b1d18bb082e7d4772a29368eb80991e | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | AllowedDataChanged(bytes,bool) | 0xbb577d7ca5995b00ceaae0c75f77ab5df42a1e24673e2e36858ee718f3f1eb8c | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Event | SelectorValidationChanged(bytes4,bool) | 0x85198d5146ae402b94f01f31a2049f75a6ecadc1d321090cd97467979b8d09d7 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | AlreadyWhitelisted(address) | 0x0bfcef28 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | CallNotAllowed(bytes) | 0x3331e9c0 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | NotAllowed(address) | 0xfa5cd00f | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | RemovingPermanentRestriction() | 0xf6fd7071 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | UnallowedImplementation(bytes32) | 0xfcb9b2e1 | +|----------+-----------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-----------------------------------------------+--------------------------------------------------------------------+ + +ChainTypeManager ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | admin() | 0xf851a440 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams(uint256,(uint8,uint32,uint32,uint32,uint32,uint64)) | 0x027f12e1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,bytes32,address,bytes,bytes[]) | 0x88c7c5d2 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xe34a329a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(uint256,bytes) | 0xf85894c5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(uint256,bytes) | 0xe8a71ca9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeChain(uint256) | 0xaccdd16c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainAdmin(uint256) | 0x301e7765 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getHyperchain(uint256) | 0xdead6f7f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion(uint256) | 0xba238947 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChainLegacy(uint256) | 0x4caa740f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialCutHash() | 0x57e6246b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialForceDeploymentHash() | 0x61f91b2e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize((address,address,(address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes),uint256)) | 0xce7df3d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1GenesisUpgrade() | 0x3437949a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersion() | 0x2ae9c600 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionDeadline(uint256) | 0xf4943a20 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionIsActive(uint256) | 0xdef9d6af | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatches(uint256,uint256) | 0x53ce2061 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setChainCreationParams((address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes)) | 0x9b016b8b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNewVersionUpgrade(((address,uint8,bool,bytes4[])[],address,bytes),uint256,uint256,uint256) | 0x2e522851 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(uint256,bool) | 0x18717dc1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256,uint256) | 0xec3d5f88 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setProtocolVersionDeadline(uint256,uint256) | 0xaad74262 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint256,uint128,uint128) | 0x7ebba672 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setUpgradeDiamondCut(((address,uint8,bool,bytes4[])[],address,bytes),uint256) | 0x98461504 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(uint256,address,bool) | 0xcf347e17 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidatorTimelock(address) | 0x7fb67816 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchZero() | 0xd2ef1b0e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeChain(uint256) | 0x51d218f7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0x0dbad27e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeCutHash(uint256) | 0x52c9eacb | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | validatorTimelock() | 0xe66c8c44 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256) | 0x778b7f95aad9610955002f243aabbbf9546bb6e792f7b3b89dab86b4f210e30f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChainCreationParams(address,bytes32,uint64,bytes32,bytes32,bytes32) | 0x04b363b4a0200ada216b1cb4aaf2736ff6f332d5f1d90f98e60b1159f3dac3aa | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutData(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xf99295383247eabb6bee8798669fa768502f8843d3be0e82a0aa81d7b6c4f60c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutHash(uint256,bytes32) | 0x71b0aeaf8eaa06ed78ccb9a4981da026eea05ca1d818c22dd120446db4c936d4 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewValidatorTimelock(address,address) | 0x5a1b0d8808a8dca64c1f7c230dce7a09f7f9a1c26507e190e03dcd382e69018e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewZKChain(uint256,address) | 0xf83c256407747903308213919067f883f683c5cde6a64ebbf25096b8bb555ddc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchCommitmentZero() | 0x6d4a7df8 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisBatchHashZero() | 0x7940c83f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisIndexStorageZero() | 0xb4fc6835 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GenesisUpgradeZero() | 0x3a1a8589 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IChainTypeManager ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++================================================================================================================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptAdmin() | 0x0e18b681 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams(uint256,(uint8,uint32,uint32,uint32,uint32,uint64)) | 0x027f12e1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | createNewChain(uint256,bytes32,address,bytes,bytes[]) | 0x88c7c5d2 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xe34a329a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(uint256,bytes) | 0xf85894c5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(uint256,bytes) | 0xe8a71ca9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeChain(uint256) | 0xaccdd16c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainAdmin(uint256) | 0x301e7765 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion(uint256) | 0xba238947 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChain(uint256) | 0xe680c4c1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getZKChainLegacy(uint256) | 0x4caa740f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialCutHash() | 0x57e6246b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize((address,address,(address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes),uint256)) | 0xce7df3d6 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l1GenesisUpgrade() | 0x3437949a | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersion() | 0x2ae9c600 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionDeadline(uint256) | 0xf4943a20 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | protocolVersionIsActive(uint256) | 0xdef9d6af | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | registerSettlementLayer(uint256,bool) | 0xdc8e4b26 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setChainCreationParams((address,bytes32,uint64,bytes32,((address,uint8,bool,bytes4[])[],address,bytes),bytes)) | 0x9b016b8b | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setNewVersionUpgrade(((address,uint8,bool,bytes4[])[],address,bytes),uint256,uint256,uint256) | 0x2e522851 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(uint256,bool) | 0x18717dc1 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256,uint256) | 0xec3d5f88 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint256,uint128,uint128) | 0x7ebba672 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setUpgradeDiamondCut(((address,uint8,bool,bytes4[])[],address,bytes),uint256) | 0x98461504 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(uint256,address,bool) | 0xcf347e17 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidatorTimelock(address) | 0x7fb67816 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchZero() | 0xd2ef1b0e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeChain(uint256) | 0x51d218f7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0x0dbad27e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeCutHash(uint256) | 0x52c9eacb | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256) | 0x778b7f95aad9610955002f243aabbbf9546bb6e792f7b3b89dab86b4f210e30f | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewChainCreationParams(address,bytes32,uint64,bytes32,bytes32,bytes32) | 0x04b363b4a0200ada216b1cb4aaf2736ff6f332d5f1d90f98e60b1159f3dac3aa | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutData(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xf99295383247eabb6bee8798669fa768502f8843d3be0e82a0aa81d7b6c4f60c | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewUpgradeCutHash(uint256,bytes32) | 0x71b0aeaf8eaa06ed78ccb9a4981da026eea05ca1d818c22dd120446db4c936d4 | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewValidatorTimelock(address,address) | 0x5a1b0d8808a8dca64c1f7c230dce7a09f7f9a1c26507e190e03dcd382e69018e | +|----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewZKChain(uint256,address) | 0xf83c256407747903308213919067f883f683c5cde6a64ebbf25096b8bb555ddc | ++----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +ValidatorTimelock ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===========================================================================================================================================+ +| Function | acceptOwnership() | 0x79ba5097 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | addValidator(uint256,address) | 0x4b561753 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | chainTypeManager() | 0xc0e42a5c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | executionDelay() | 0x8b257989 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | getCommittedBatchTimestamp(uint256,uint256) | 0xb993549e | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | removeValidator(uint256,address) | 0x6a0cd1f5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | setChainTypeManager(address) | 0xbd5bcf93 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | setExecutionDelay(uint32) | 0xf34d1868 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | validators(uint256,address) | 0x91b19874 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewExecutionDelay(uint256) | 0xd32d6d626bb9c7077c559fc3b4e5ce71ef14609d7d216d030ee63dcf2422c2c4 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorAdded(uint256,address) | 0x7429a06e9412e469f0d64f9d222640b0af359f556b709e2913588c227851b88d | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorRemoved(uint256,address) | 0x7126bef88d1149ccdff9681ed5aecd3ba5ae70c96517551de250af09cebd1a0b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressAlreadyValidator(uint256) | 0x004aef8a | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidatorDoesNotExist(uint256) | 0x5fd1e44b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +DiamondInit ++----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================================================================================================================================================================+ +| Function | initialize((uint256,address,address,uint256,address,address,bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes32,bytes32,uint256,(uint8,uint32,uint32,uint32,uint32,uint64),address)) | 0xadad4b1b | +|----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ + +DiamondProxy ++-------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++========================================================================================================================================+ +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|-------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | ++-------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +AdminFacet ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================================================+ +| Function | acceptAdmin() | 0x0e18b681 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams((uint8,uint32,uint32,uint32,uint32,uint64)) | 0x64bf8d66 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0xa9f6d941 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(address,address,bytes) | 0x64b554ad | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(bytes,bool) | 0x3f42d5dd | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeDiamond() | 0x27ae4c16 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | genesisUpgrade(address,address,bytes,bytes[]) | 0x2878fe74 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | prepareChainCommitment() | 0x41cf49bb | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setDAValidatorPair(address,address) | 0x6223258e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(bool) | 0x1cc5d103 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256) | 0xbe6f11cf | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPubdataPricingMode(uint8) | 0xe76db865 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint128,uint128) | 0x235d9eb5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTransactionFilterer(address) | 0x21f603d7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(address,bool) | 0x4623c91d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeDiamond() | 0x17338945 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xfc57565f | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ExecuteUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x1dabfc3f4f6a4e74e19be10cc9d1d8e23db03e415d5d3547a1a7d5eb766513ba | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Freeze() | 0x615acbaede366d76a8b8cb2a9ada6a71495f0786513d71aa97aaf0c3910b78de | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | IsPorterAvailableStatusUpdate(bool) | 0x036b81a8a07344698cb5aa4142c5669a9317c9ce905264a08f0b9f9331883936 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationComplete() | 0x96e718f44bd77cb63370212c5aa24a0396d8f43e88e7ce175d160e371c8e2a6a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewBaseTokenMultiplier(uint128,uint128,uint128,uint128) | 0xc9cbdb110bd58a133e82c62b1488e57677be1f326df10a4d8096b5f170c370c8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewFeeParams((uint8,uint32,uint32,uint32,uint32,uint64),(uint8,uint32,uint32,uint32,uint32,uint64)) | 0xc8b245ac8b138b17b6b1dbbbb8860adc66b373afa000d99f3cdc775d8ae0bbed | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL1DAValidator(address,address) | 0x08b0b676d456a0431162145d2821f30c665b69ca626521c937ba7a77a29ed67c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DAValidator(address,address) | 0x866a71b85fb8625f74adc67901361962f0aa3730a1615400911ae610d65dc130 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityTxMaxGasLimit(uint256,uint256) | 0x83dd728f7e76a849126c55ffabdc6e299eb8c85dccf12498701376d9f5c954d1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewTransactionFilterer(address,address) | 0xa9b43a66c5d1c607986f49e932a0c08058d843210db03dd6e8a621b96b4770f4 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unfreeze() | 0x2f05ba71d0df11bf5fa562a6569d70c4f80da84284badbe015ce1456063d0ded | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorStatusUpdate(address,bool) | 0x065b77b53864e46fda3d8986acb51696223d6dde7ced42441eb150bae6d48136 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidiumModeStatusUpdate(uint8) | 0xaa01146df0a628c6b214e79a281f7524b792de4a52ad6f07c78e6e035d58c896 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ChainAlreadyLive() | 0x78d2ed02 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DenominatorIsZero() | 0x0a8ed92c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DiamondAlreadyFrozen() | 0x0e7ee319 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DiamondNotFrozen() | 0xa7151b9a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidPubdataPricingMode() | 0x6f1cf752 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PriorityTxPubdataExceedsMaxPubDataPerBatch() | 0x1a4d284a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolIdMismatch(uint256,uint256) | 0xa461f651 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolIdNotGreater() | 0x64f94ec2 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +ExecutorFacet ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===========================================================================================================================================+ +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchHashMismatch(bytes32,bytes32) | 0x55ad3fd3 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNumberMismatch(uint256,uint256) | 0xbd4455ff | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CanOnlyProcessOneBatch() | 0xe85392f9 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantExecuteUnprovenBatches() | 0x00c6ead2 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | CantRevertExecutedBatch() | 0xe18cb383 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | EmptyData() | 0x99d8fec9 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashMismatch(bytes32,bytes32) | 0x0b08d5be | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | IncorrectBatchBounds(uint256,uint256,uint256,uint256) | 0xd7d93e1f | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidLogSender(address,uint256) | 0xc1780bd6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidNumberOfBlobs(uint256,uint256,uint256) | 0xd8e9405c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProof() | 0x09bde339 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidProtocolVersion() | 0x5428eae7 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2TimestampTooBig() | 0xfb5c22e6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | LogAlreadyProcessed(uint8) | 0x1b6825bb | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | MissingSystemLogs(uint256,uint256) | 0xfa44b527 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonIncreasingTimestamp() | 0xd018e08e | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonSequentialBatch() | 0x0105f9c0 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | PriorityOperationsRollingHashMismatch() | 0xd5a99014 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | QueueIsEmpty() | 0x63c36549 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | RevertedBatchNotAfterNewLastBatch() | 0x9a67c1cb | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | SystemLogsSizeTooBig() | 0xae43b424 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimestampError() | 0x2d50c33b | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxHashMismatch() | 0x4c991078 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedSystemLog(uint256) | 0x6aa39880 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedCommitBatchEncoding(uint8) | 0xf3dd1b9c | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedExecuteBatchEncoding(uint8) | 0x14d2ed8a | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnsupportedProofBatchEncoding(uint8) | 0xf338f830 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | UpgradeBatchNumberIsNotZero() | 0xf093c2e5 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValueMismatch(uint256,uint256) | 0x626ade30 | +|----------+-----------------------------------------------------------+--------------------------------------------------------------------| +| Error | VerifiedBatchesExceedsCommittedBatches() | 0xe1022469 | ++----------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +GettersFacet ++----------+-------------------------------------------+------------+ +| Type | Signature | Selector | ++===================================================================+ +| Function | baseTokenGasPriceMultiplierDenominator() | 0x1de72e34 | +|----------+-------------------------------------------+------------| +| Function | baseTokenGasPriceMultiplierNominator() | 0xea6c029c | +|----------+-------------------------------------------+------------| +| Function | facetAddress(bytes4) | 0xcdffacc6 | +|----------+-------------------------------------------+------------| +| Function | facetAddresses() | 0x52ef6b2c | +|----------+-------------------------------------------+------------| +| Function | facetFunctionSelectors(address) | 0xadfca15e | +|----------+-------------------------------------------+------------| +| Function | facets() | 0x7a0ed627 | +|----------+-------------------------------------------+------------| +| Function | getAdmin() | 0x6e9960c3 | +|----------+-------------------------------------------+------------| +| Function | getBaseToken() | 0x98acd7a6 | +|----------+-------------------------------------------+------------| +| Function | getBaseTokenAssetId() | 0x960dcf24 | +|----------+-------------------------------------------+------------| +| Function | getBridgehub() | 0x3591c1a0 | +|----------+-------------------------------------------+------------| +| Function | getChainId() | 0x3408e470 | +|----------+-------------------------------------------+------------| +| Function | getChainTypeManager() | 0x946ebad1 | +|----------+-------------------------------------------+------------| +| Function | getDAValidatorPair() | 0x5a590335 | +|----------+-------------------------------------------+------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+-------------------------------------------+------------| +| Function | getL2BootloaderBytecodeHash() | 0xd86970d8 | +|----------+-------------------------------------------+------------| +| Function | getL2DefaultAccountBytecodeHash() | 0xfd791f3c | +|----------+-------------------------------------------+------------| +| Function | getL2SystemContractsUpgradeBatchNumber() | 0xe5355c75 | +|----------+-------------------------------------------+------------| +| Function | getL2SystemContractsUpgradeBlockNumber() | 0x9d1b5a81 | +|----------+-------------------------------------------+------------| +| Function | getL2SystemContractsUpgradeTxHash() | 0x7b30c8da | +|----------+-------------------------------------------+------------| +| Function | getName() | 0x17d7de7c | +|----------+-------------------------------------------+------------| +| Function | getPendingAdmin() | 0xd0468156 | +|----------+-------------------------------------------+------------| +| Function | getPriorityQueueSize() | 0x631f4bac | +|----------+-------------------------------------------+------------| +| Function | getPriorityTreeRoot() | 0x39d7d4aa | +|----------+-------------------------------------------+------------| +| Function | getPriorityTxMaxGasLimit() | 0x0ec6b0b7 | +|----------+-------------------------------------------+------------| +| Function | getProtocolVersion() | 0x33ce93fe | +|----------+-------------------------------------------+------------| +| Function | getPubdataPricingMode() | 0x06d49e5b | +|----------+-------------------------------------------+------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+-------------------------------------------+------------| +| Function | getSettlementLayer() | 0x6a27e8b5 | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesCommitted() | 0xdb1f0bf9 | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesExecuted() | 0xb8c2f66f | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesVerified() | 0xef3f0bae | +|----------+-------------------------------------------+------------| +| Function | getTotalBlocksCommitted() | 0xfe26699e | +|----------+-------------------------------------------+------------| +| Function | getTotalBlocksExecuted() | 0x39607382 | +|----------+-------------------------------------------+------------| +| Function | getTotalBlocksVerified() | 0xaf6a2dcd | +|----------+-------------------------------------------+------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+-------------------------------------------+------------| +| Function | getTransactionFilterer() | 0x22c5cf23 | +|----------+-------------------------------------------+------------| +| Function | getVerifier() | 0x46657fe9 | +|----------+-------------------------------------------+------------| +| Function | getVerifierParams() | 0x18e3a941 | +|----------+-------------------------------------------+------------| +| Function | isDiamondStorageFrozen() | 0x29b98c67 | +|----------+-------------------------------------------+------------| +| Function | isEthWithdrawalFinalized(uint256,uint256) | 0xbd7c5412 | +|----------+-------------------------------------------+------------| +| Function | isFacetFreezable(address) | 0xc3bbd2d7 | +|----------+-------------------------------------------+------------| +| Function | isFunctionFreezable(bytes4) | 0xe81e0ba1 | +|----------+-------------------------------------------+------------| +| Function | isValidator(address) | 0xfacd743b | +|----------+-------------------------------------------+------------| +| Function | l2LogsRootHash(uint256) | 0x9cd939e4 | +|----------+-------------------------------------------+------------| +| Function | storedBatchHash(uint256) | 0xb22dd78e | +|----------+-------------------------------------------+------------| +| Function | storedBlockHash(uint256) | 0x74f4d30d | +|----------+-------------------------------------------+------------| +| Error | InvalidSelector(bytes4) | 0x12ba286f | ++----------+-------------------------------------------+------------+ + +MailboxFacet ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===================================================================================================================================================================================================================================================================+ +| Function | bridgehubRequestL2Transaction((address,address,uint256,uint256,bytes,uint256,uint256,bytes[],address)) | 0x12f43dab | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2TransactionOnGateway(bytes32,uint64) | 0xddcc9eec | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeEthWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x6c0960f9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256) | 0xb473318e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0x042901c7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatusViaGateway(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0xe717bab7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LeafInclusion(uint256,uint256,bytes32,bytes32[]) | 0x7efda2ae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0x263b7f8e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,(uint16,address,bytes),bytes32[]) | 0xe4948f43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2Transaction(address,uint256,bytes,uint256,uint256,bytes[],address) | 0xeb672419 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionToGatewayMailbox(uint256,bytes32,uint64) | 0xd0772551 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityRequest(uint256,bytes32,uint64,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[]) | 0x4531cd5795773d7101c17bdeb9f5ab7f47d7056017506f937083be5d6e77a382 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewRelayedPriorityTransaction(uint256,bytes32,uint64) | 0x0137d2eaa6ec5b7e4f233f6d6f441410014535d0f3985367994c94bf15a2a564 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BaseTokenGasPriceDenominatorNotSet() | 0x6ef9a972 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | BatchNotExecuted(uint256) | 0x2078a6a0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | GasPerPubdataMismatch() | 0xc91cf3b1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | HashedLogIsDefault() | 0xd356e6ba | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerkleIndexOutOfBounds() | 0x9bb54c35 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathEmpty() | 0x8e23ac1a | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MerklePathOutOfBounds() | 0x1c500385 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MsgValueTooLow(uint256,uint256) | 0xb385a3da | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotInitializedReentrancyGuard() | 0xdd7e3621 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | OnlyEraSupported() | 0xf3ed9dfa | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Reentrancy() | 0xab143c06 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TransactionNotAllowed() | 0x00c5a6a9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | Unauthorized(address) | 0x8e4a23d6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IAdmin ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================================================+ +| Function | acceptAdmin() | 0x0e18b681 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams((uint8,uint32,uint32,uint32,uint32,uint64)) | 0x64bf8d66 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0xa9f6d941 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(address,address,bytes) | 0x64b554ad | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(bytes,bool) | 0x3f42d5dd | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeDiamond() | 0x27ae4c16 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | genesisUpgrade(address,address,bytes,bytes[]) | 0x2878fe74 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | prepareChainCommitment() | 0x41cf49bb | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setDAValidatorPair(address,address) | 0x6223258e | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(bool) | 0x1cc5d103 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256) | 0xbe6f11cf | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPubdataPricingMode(uint8) | 0xe76db865 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint128,uint128) | 0x235d9eb5 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTransactionFilterer(address) | 0x21f603d7 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(address,bool) | 0x4623c91d | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeDiamond() | 0x17338945 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xfc57565f | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ExecuteUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x1dabfc3f4f6a4e74e19be10cc9d1d8e23db03e415d5d3547a1a7d5eb766513ba | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Freeze() | 0x615acbaede366d76a8b8cb2a9ada6a71495f0786513d71aa97aaf0c3910b78de | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | IsPorterAvailableStatusUpdate(bool) | 0x036b81a8a07344698cb5aa4142c5669a9317c9ce905264a08f0b9f9331883936 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationComplete() | 0x96e718f44bd77cb63370212c5aa24a0396d8f43e88e7ce175d160e371c8e2a6a | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewBaseTokenMultiplier(uint128,uint128,uint128,uint128) | 0xc9cbdb110bd58a133e82c62b1488e57677be1f326df10a4d8096b5f170c370c8 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewFeeParams((uint8,uint32,uint32,uint32,uint32,uint64),(uint8,uint32,uint32,uint32,uint32,uint64)) | 0xc8b245ac8b138b17b6b1dbbbb8860adc66b373afa000d99f3cdc775d8ae0bbed | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL1DAValidator(address,address) | 0x08b0b676d456a0431162145d2821f30c665b69ca626521c937ba7a77a29ed67c | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DAValidator(address,address) | 0x866a71b85fb8625f74adc67901361962f0aa3730a1615400911ae610d65dc130 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityTxMaxGasLimit(uint256,uint256) | 0x83dd728f7e76a849126c55ffabdc6e299eb8c85dccf12498701376d9f5c954d1 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewTransactionFilterer(address,address) | 0xa9b43a66c5d1c607986f49e932a0c08058d843210db03dd6e8a621b96b4770f4 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unfreeze() | 0x2f05ba71d0df11bf5fa562a6569d70c4f80da84284badbe015ce1456063d0ded | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorStatusUpdate(address,bool) | 0x065b77b53864e46fda3d8986acb51696223d6dde7ced42441eb150bae6d48136 | +|----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidiumModeStatusUpdate(uint8) | 0xaa01146df0a628c6b214e79a281f7524b792de4a52ad6f07c78e6e035d58c896 | ++----------+-----------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IDiamondInit ++----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++====================================================================================================================================================================================================================+ +| Function | initialize((uint256,address,address,uint256,address,address,bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes32,bytes32,uint256,(uint8,uint32,uint32,uint32,uint32,uint64),address)) | 0xadad4b1b | ++----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ + +IGetters ++----------+-------------------------------------------+------------+ +| Type | Signature | Selector | ++===================================================================+ +| Function | baseTokenGasPriceMultiplierDenominator() | 0x1de72e34 | +|----------+-------------------------------------------+------------| +| Function | baseTokenGasPriceMultiplierNominator() | 0xea6c029c | +|----------+-------------------------------------------+------------| +| Function | facetAddress(bytes4) | 0xcdffacc6 | +|----------+-------------------------------------------+------------| +| Function | facetAddresses() | 0x52ef6b2c | +|----------+-------------------------------------------+------------| +| Function | facetFunctionSelectors(address) | 0xadfca15e | +|----------+-------------------------------------------+------------| +| Function | facets() | 0x7a0ed627 | +|----------+-------------------------------------------+------------| +| Function | getAdmin() | 0x6e9960c3 | +|----------+-------------------------------------------+------------| +| Function | getBaseToken() | 0x98acd7a6 | +|----------+-------------------------------------------+------------| +| Function | getBaseTokenAssetId() | 0x960dcf24 | +|----------+-------------------------------------------+------------| +| Function | getBridgehub() | 0x3591c1a0 | +|----------+-------------------------------------------+------------| +| Function | getChainId() | 0x3408e470 | +|----------+-------------------------------------------+------------| +| Function | getChainTypeManager() | 0x946ebad1 | +|----------+-------------------------------------------+------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+-------------------------------------------+------------| +| Function | getL2BootloaderBytecodeHash() | 0xd86970d8 | +|----------+-------------------------------------------+------------| +| Function | getL2DefaultAccountBytecodeHash() | 0xfd791f3c | +|----------+-------------------------------------------+------------| +| Function | getL2SystemContractsUpgradeBatchNumber() | 0xe5355c75 | +|----------+-------------------------------------------+------------| +| Function | getL2SystemContractsUpgradeTxHash() | 0x7b30c8da | +|----------+-------------------------------------------+------------| +| Function | getName() | 0x17d7de7c | +|----------+-------------------------------------------+------------| +| Function | getPendingAdmin() | 0xd0468156 | +|----------+-------------------------------------------+------------| +| Function | getPriorityQueueSize() | 0x631f4bac | +|----------+-------------------------------------------+------------| +| Function | getPriorityTreeRoot() | 0x39d7d4aa | +|----------+-------------------------------------------+------------| +| Function | getPriorityTxMaxGasLimit() | 0x0ec6b0b7 | +|----------+-------------------------------------------+------------| +| Function | getProtocolVersion() | 0x33ce93fe | +|----------+-------------------------------------------+------------| +| Function | getPubdataPricingMode() | 0x06d49e5b | +|----------+-------------------------------------------+------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+-------------------------------------------+------------| +| Function | getSettlementLayer() | 0x6a27e8b5 | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesCommitted() | 0xdb1f0bf9 | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesExecuted() | 0xb8c2f66f | +|----------+-------------------------------------------+------------| +| Function | getTotalBatchesVerified() | 0xef3f0bae | +|----------+-------------------------------------------+------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+-------------------------------------------+------------| +| Function | getTransactionFilterer() | 0x22c5cf23 | +|----------+-------------------------------------------+------------| +| Function | getVerifier() | 0x46657fe9 | +|----------+-------------------------------------------+------------| +| Function | getVerifierParams() | 0x18e3a941 | +|----------+-------------------------------------------+------------| +| Function | isDiamondStorageFrozen() | 0x29b98c67 | +|----------+-------------------------------------------+------------| +| Function | isEthWithdrawalFinalized(uint256,uint256) | 0xbd7c5412 | +|----------+-------------------------------------------+------------| +| Function | isFacetFreezable(address) | 0xc3bbd2d7 | +|----------+-------------------------------------------+------------| +| Function | isFunctionFreezable(bytes4) | 0xe81e0ba1 | +|----------+-------------------------------------------+------------| +| Function | isValidator(address) | 0xfacd743b | +|----------+-------------------------------------------+------------| +| Function | l2LogsRootHash(uint256) | 0x9cd939e4 | +|----------+-------------------------------------------+------------| +| Function | storedBatchHash(uint256) | 0xb22dd78e | ++----------+-------------------------------------------+------------+ + +IZKChain ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++===================================================================================================================================================================================================================================================================+ +| Function | acceptAdmin() | 0x0e18b681 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenGasPriceMultiplierDenominator() | 0x1de72e34 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | baseTokenGasPriceMultiplierNominator() | 0xea6c029c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2Transaction((address,address,uint256,uint256,bytes,uint256,uint256,bytes[],address)) | 0x12f43dab | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | bridgehubRequestL2TransactionOnGateway(bytes32,uint64) | 0xddcc9eec | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | changeFeeParams((uint8,uint32,uint32,uint32,uint32,uint64)) | 0x64bf8d66 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | commitBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0x98f81962 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xcf02827d | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | executeUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0xa9f6d941 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetAddress(bytes4) | 0xcdffacc6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetAddresses() | 0x52ef6b2c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facetFunctionSelectors(address) | 0xadfca15e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | facets() | 0x7a0ed627 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | finalizeEthWithdrawal(uint256,uint256,uint16,bytes,bytes32[]) | 0x6c0960f9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeBurn(address,address,bytes) | 0x64b554ad | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeMint(bytes,bool) | 0x3f42d5dd | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | forwardedBridgeRecoverFailedTransfer(uint256,bytes32,address,bytes) | 0xb7846107 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | freezeDiamond() | 0x27ae4c16 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | genesisUpgrade(address,address,bytes,bytes[]) | 0x2878fe74 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getAdmin() | 0x6e9960c3 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBaseToken() | 0x98acd7a6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBaseTokenAssetId() | 0x960dcf24 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getBridgehub() | 0x3591c1a0 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainId() | 0x3408e470 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getChainTypeManager() | 0x946ebad1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getFirstUnprocessedPriorityTx() | 0x79823c9a | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2BootloaderBytecodeHash() | 0xd86970d8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2DefaultAccountBytecodeHash() | 0xfd791f3c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2SystemContractsUpgradeBatchNumber() | 0xe5355c75 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getL2SystemContractsUpgradeTxHash() | 0x7b30c8da | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getName() | 0x17d7de7c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPendingAdmin() | 0xd0468156 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityQueueSize() | 0x631f4bac | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityTreeRoot() | 0x39d7d4aa | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPriorityTxMaxGasLimit() | 0x0ec6b0b7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getProtocolVersion() | 0x33ce93fe | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getPubdataPricingMode() | 0x06d49e5b | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSemverProtocolVersion() | 0xf5c1182c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getSettlementLayer() | 0x6a27e8b5 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesCommitted() | 0xdb1f0bf9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesExecuted() | 0xb8c2f66f | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalBatchesVerified() | 0xef3f0bae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTotalPriorityTxs() | 0xa1954fc5 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getTransactionFilterer() | 0x22c5cf23 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getVerifier() | 0x46657fe9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | getVerifierParams() | 0x18e3a941 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isDiamondStorageFrozen() | 0x29b98c67 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isEthWithdrawalFinalized(uint256,uint256) | 0xbd7c5412 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isFacetFreezable(address) | 0xc3bbd2d7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isFunctionFreezable(bytes4) | 0xe81e0ba1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isValidator(address) | 0xfacd743b | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2LogsRootHash(uint256) | 0x9cd939e4 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | l2TransactionBaseCost(uint256,uint256,uint256) | 0xb473318e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | prepareChainCommitment() | 0x41cf49bb | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveBatchesSharedBridge(uint256,uint256,uint256,bytes) | 0xe12a6137 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL1ToL2TransactionStatus(bytes32,uint256,uint256,uint16,bytes32[],uint8) | 0x042901c7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LeafInclusion(uint256,uint256,bytes32,bytes32[]) | 0x7efda2ae | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2LogInclusion(uint256,uint256,(uint8,bool,uint16,address,bytes32,bytes32),bytes32[]) | 0x263b7f8e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | proveL2MessageInclusion(uint256,uint256,(uint16,address,bytes),bytes32[]) | 0xe4948f43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2Transaction(address,uint256,bytes,uint256,uint256,bytes[],address) | 0xeb672419 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | requestL2TransactionToGatewayMailbox(uint256,bytes32,uint64) | 0xd0772551 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revertBatchesSharedBridge(uint256,uint256) | 0x0f23da43 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setDAValidatorPair(address,address) | 0x6223258e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPendingAdmin(address) | 0x4dd18bf5 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPorterAvailability(bool) | 0x1cc5d103 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPriorityTxMaxGasLimit(uint256) | 0xbe6f11cf | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setPubdataPricingMode(uint8) | 0xe76db865 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTokenMultiplier(uint128,uint128) | 0x235d9eb5 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setTransactionFilterer(address) | 0x21f603d7 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | setValidator(address,bool) | 0x4623c91d | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | storedBatchHash(uint256) | 0xb22dd78e | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | unfreezeDiamond() | 0x17338945 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeChainFromVersion(uint256,((address,uint8,bool,bytes4[])[],address,bytes)) | 0xfc57565f | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockCommit(uint256,bytes32,bytes32) | 0x8f2916b2f2d78cc5890ead36c06c0f6d5d112c7e103589947e8e2f0d6eddb763 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlockExecution(uint256,bytes32,bytes32) | 0x2402307311a4d6604e4e7b4c8a15a7e1213edb39c16a31efa70afb06030d3165 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksRevert(uint256,uint256,uint256) | 0x8bd4b15ea7d1bc41ea9abc3fc487ccb89cd678a00786584714faa9d751c84ee5 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BlocksVerification(uint256,uint256) | 0x22c9005dd88c18b552a1cd7e8b3b937fcde9ca69213c1f658f54d572e4877a81 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeInitialize(address,string,string,uint8) | 0x81e8e92e5873539605a102eddae7ed06d19bea042099a437cbc3644415eb7404 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | BridgeMint(address,uint256) | 0x397b33b307fc137878ebfc75b295289ec0ee25a31bb5bf034f33256fe8ea2aa6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ExecuteUpgrade(((address,uint8,bool,bytes4[])[],address,bytes)) | 0x1dabfc3f4f6a4e74e19be10cc9d1d8e23db03e415d5d3547a1a7d5eb766513ba | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Freeze() | 0x615acbaede366d76a8b8cb2a9ada6a71495f0786513d71aa97aaf0c3910b78de | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | IsPorterAvailableStatusUpdate(bool) | 0x036b81a8a07344698cb5aa4142c5669a9317c9ce905264a08f0b9f9331883936 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | MigrationComplete() | 0x96e718f44bd77cb63370212c5aa24a0396d8f43e88e7ce175d160e371c8e2a6a | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewAdmin(address,address) | 0xf9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewBaseTokenMultiplier(uint128,uint128,uint128,uint128) | 0xc9cbdb110bd58a133e82c62b1488e57677be1f326df10a4d8096b5f170c370c8 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewFeeParams((uint8,uint32,uint32,uint32,uint32,uint64),(uint8,uint32,uint32,uint32,uint32,uint64)) | 0xc8b245ac8b138b17b6b1dbbbb8860adc66b373afa000d99f3cdc775d8ae0bbed | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL1DAValidator(address,address) | 0x08b0b676d456a0431162145d2821f30c665b69ca626521c937ba7a77a29ed67c | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DAValidator(address,address) | 0x866a71b85fb8625f74adc67901361962f0aa3730a1615400911ae610d65dc130 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPendingAdmin(address,address) | 0xca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityRequest(uint256,bytes32,uint64,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[]) | 0x4531cd5795773d7101c17bdeb9f5ab7f47d7056017506f937083be5d6e77a382 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewPriorityTxMaxGasLimit(uint256,uint256) | 0x83dd728f7e76a849126c55ffabdc6e299eb8c85dccf12498701376d9f5c954d1 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewRelayedPriorityTransaction(uint256,bytes32,uint64) | 0x0137d2eaa6ec5b7e4f233f6d6f441410014535d0f3985367994c94bf15a2a564 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewTransactionFilterer(address,address) | 0xa9b43a66c5d1c607986f49e932a0c08058d843210db03dd6e8a621b96b4770f4 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ProposeTransparentUpgrade(((address,uint8,bool,bytes4[])[],address,bytes),uint256,bytes32) | 0x69115b49afe7a6101a2e7af17d421eda1dc153bd26d699f013c4fff0404646a6 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Unfreeze() | 0x2f05ba71d0df11bf5fa562a6569d70c4f80da84284badbe015ce1456063d0ded | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidatorStatusUpdate(address,bool) | 0x065b77b53864e46fda3d8986acb51696223d6dde7ced42441eb150bae6d48136 | +|----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | ValidiumModeStatusUpdate(uint8) | 0xaa01146df0a628c6b214e79a281f7524b792de4a52ad6f07c78e6e035d58c896 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +Diamond ++-------+-----------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++========================================================================================================================================+ +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | ++-------+-----------------------------------------------------------+--------------------------------------------------------------------+ + +GatewayTransactionFilterer ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=====================================================================================================================================================+ +| Function | BRIDGE_HUB() | 0x5d4edca7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | L1_ASSET_ROUTER() | 0xcdf25430 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | acceptOwnership() | 0x79ba5097 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | grantWhitelist(address) | 0x5b063622 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | initialize(address) | 0xc4d66de8 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | isTransactionAllowed(address,address,uint256,uint256,bytes,address) | 0xcbcf2e3c | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | owner() | 0x8da5cb5b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | pendingOwner() | 0xe30c3978 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | renounceOwnership() | 0x715018a6 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | revokeWhitelist(address) | 0x9c7f3315 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | transferOwnership(address) | 0xf2fde38b | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | whitelistedSenders(address) | 0x272efc69 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | Initialized(uint8) | 0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferStarted(address,address) | 0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | OwnershipTransferred(address,address) | 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WhitelistGranted(address) | 0xd5a6b3454d1aa211b5b7e99c94012bed9883c7695b5c58fd97e20f425ec0b5bf | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | WhitelistRevoked(address) | 0x79bc96e8fb893a32b4429ae9fd9084cdb98be910b9c7cdbb4307cc96732c7ec7 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AlreadyWhitelisted(address) | 0x0bfcef28 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidSelector(bytes4) | 0x12ba286f | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NotWhitelisted(address) | 0xdf17e316 | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SlotOccupied() | 0xdf3a8fdd | +|----------+---------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ZeroAddress() | 0xd92e233d | ++----------+---------------------------------------------------------------------+--------------------------------------------------------------------+ + +BaseZkSyncUpgrade ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NewProtocolMajorVersionNotZero() | 0x72ea85ad | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousProtocolMajorVersionNotZero() | 0x5c598b60 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotCleaned() | 0xa0f47245 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionMinorDeltaTooBig(uint256,uint256) | 0xd328c12a | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +BaseZkSyncUpgradeGenesis ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeBatchNotCleared() | 0xd7f8c13e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolMajorVersionNotZero() | 0x3c43ccce | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionDeltaTooLarge(uint256,uint256) | 0xe1a9736b | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +DefaultUpgrade ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NewProtocolMajorVersionNotZero() | 0x72ea85ad | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousProtocolMajorVersionNotZero() | 0x5c598b60 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotCleaned() | 0xa0f47245 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionMinorDeltaTooBig(uint256,uint256) | 0xd328c12a | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +GatewayUpgrade ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | THIS_ADDRESS() | 0x315fff4e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgradeExternal(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0xde7c5443 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NewProtocolMajorVersionNotZero() | 0x72ea85ad | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousProtocolMajorVersionNotZero() | 0x5c598b60 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotCleaned() | 0xa0f47245 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionMinorDeltaTooBig(uint256,uint256) | 0xd328c12a | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ + +IDefaultUpgrade ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================+ +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ + +IGatewayUpgrade ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ +| Type | Signature | Selector | ++=================================================================================================================================================================================================================================================================+ +| Function | upgradeExternal(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0xde7c5443 | ++----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------+ + +L1GenesisUpgrade ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ +| Type | Signature | Selector | ++=========================================================================================================================================================================================================================================================================================================================================+ +| Function | genesisUpgrade(address,uint256,uint256,address,bytes,bytes[]) | 0xd83e4e03 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Function | upgrade(((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x08284e57 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | DiamondCut((address,uint8,bool,bytes4[])[],address,bytes) | 0x87b829356b3403d36217eff1f66ee48eacd0a69015153aba4f0de29fe5340c30 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | GenesisUpgrade(address,(uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),uint256,bytes[]) | 0xc5902263211386c797097c5eef7ce20567f0e13359623233314cfa01a55341da | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2BootloaderBytecodeHash(bytes32,bytes32) | 0x271b33af94e3f065ecd8659833e6b1daf851f063700c36ddefefab35d4ce4746 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewL2DefaultAccountBytecodeHash(bytes32,bytes32) | 0x36df93a47cc02081d9d8208022ab736fdf98fac566e5fc6f5762bf7666e521f3 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewProtocolVersion(uint256,uint256) | 0x4235104f56661fe2e9d2f2a460b42766581bc45ce366c6a30a9f86c8a2b371a7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifier(address,address) | 0x2ff4895c300d6993c27f2bb507b4b59d29464dc640af727383451365631ba8b2 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | NewVerifierParams((bytes32,bytes32,bytes32),(bytes32,bytes32,bytes32)) | 0x4c055dbc5f14dcb6e081c9421d9657d950dcd6372f6db0a714b9135171cbc15d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Event | UpgradeComplete(uint256,bytes32,((uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256[4],bytes,bytes,uint256[],bytes,bytes),bytes[],bytes32,bytes32,address,(bytes32,bytes32,bytes32),bytes,bytes,uint256,uint256)) | 0x56405fee20a4cf3c21d1b23cbbedc0f54921b0347dc19a7641c80645f6916798 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | AddressHasNoCode(address) | 0x86bb51b8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | DelegateCallFailed(bytes) | 0xf7a01e4d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | FacetExists(bytes4,address) | 0xac4a3f98 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidTxType(uint256) | 0x5cb29523 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | InvalidUpgradeTxn(uint8) | 0x5f1aa154 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2BytecodeHashMismatch(bytes32,bytes32) | 0xcb5e4247 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | L2UpgradeNonceNotEqualToNewProtocolVersion(uint256,uint256) | 0xd2c011d6 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | LengthIsNotDivisibleBy32(uint256) | 0xe37d2c02 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | MalformedBytecode(uint8) | 0x43e266b0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NoFunctionsForDiamondCut() | 0xa6fef710 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | NonEmptyCalldata() | 0xc21b1ab7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchCantSetUpgradeTxn() | 0xd7f50a9d | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetBootloader() | 0x962fd7d0 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PatchUpgradeCantSetDefaultAccount() | 0x559cc34e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeBatchNotCleared() | 0xd7f8c13e | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PreviousUpgradeNotFinalized(bytes32) | 0x101ba748 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolMajorVersionNotZero() | 0x3c43ccce | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionDeltaTooLarge(uint256,uint256) | 0xe1a9736b | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ProtocolVersionTooSmall() | 0x88d7b498 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | PubdataGreaterThanLimit(uint256,uint256) | 0x959f26fb | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressNotZero(address) | 0x667d17de | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | RemoveFunctionFacetAddressZero() | 0xa2d4b16c | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ReplaceFunctionFacetAddressZero() | 0x3580370c | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | SelectorsMustAllHaveSameFreezability() | 0xd3b6535b | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TimeNotReached(uint256,uint256) | 0x08753982 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooManyFactoryDeps() | 0x76da24b9 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TooMuchGas() | 0xf0b4e88f | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | TxnBodyGasLimitNotEnoughGas() | 0x2e311df8 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UndefinedDiamondCutAction() | 0xe52478c7 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | UnexpectedNumberOfFactoryDeps() | 0x07218375 | +|----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------| +| Error | ValidateTxnNotEnoughGas() | 0x47b3b145 | ++----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------+ diff --git a/l1-contracts/src.ts/deploy.ts b/l1-contracts/src.ts/deploy.ts index 0c8ccc2cc..4747418c7 100644 --- a/l1-contracts/src.ts/deploy.ts +++ b/l1-contracts/src.ts/deploy.ts @@ -211,8 +211,6 @@ export class Deployer { messageRootBytecodeHash: ethers.utils.hexlify(hashL2Bytecode(messageRootZKBytecode)), l2SharedBridgeLegacyImpl: ethers.constants.AddressZero, l2BridgedStandardERC20Impl: ethers.constants.AddressZero, - l2BridgeProxyOwnerAddress: ethers.constants.AddressZero, - l2BridgedStandardERC20ProxyOwnerAddress: ethers.constants.AddressZero, }; return ethers.utils.defaultAbiCoder.encode([FIXED_FORCE_DEPLOYMENTS_DATA_ABI_STRING], [fixedForceDeploymentsData]); @@ -383,7 +381,7 @@ export class Deployer { // @ts-ignore // TODO try to make it work with zksync ethers const zkWal = this.deployWallet as ZkWallet; - // FIXME: this is a hack + // TODO: this is a hack const tmpContractFactory = await hardhat.ethers.getContractFactory( "@openzeppelin/contracts-v4/proxy/transparent/ProxyAdmin.sol:ProxyAdmin", { @@ -568,7 +566,7 @@ export class Deployer { public async deployAdminFacet(create2Salt: string, ethTxOptions: ethers.providers.TransactionRequest) { const contractAddress = await this.deployViaCreate2( "AdminFacet", - [await this.getL1ChainId()], + [await this.getL1ChainId(), ethers.constants.AddressZero], create2Salt, ethTxOptions ); @@ -598,7 +596,12 @@ export class Deployer { } public async deployExecutorFacet(create2Salt: string, ethTxOptions: ethers.providers.TransactionRequest) { - const contractAddress = await this.deployViaCreate2("ExecutorFacet", [], create2Salt, ethTxOptions); + const contractAddress = await this.deployViaCreate2( + "ExecutorFacet", + [await this.getL1ChainId()], + create2Salt, + ethTxOptions + ); if (this.verbose) { console.log(`CONTRACTS_EXECUTOR_FACET_ADDR=${contractAddress}`); @@ -936,12 +939,11 @@ export class Deployer { create2Salt: string, ethTxOptions: ethers.providers.TransactionRequest ) { - const eraChainId = getNumberFromEnv("CONTRACTS_ERA_CHAIN_ID"); const tokens = getTokens(); const l1WethToken = tokens.find((token: { symbol: string }) => token.symbol == "WETH")!.address; const contractAddress = await this.deployViaCreate2( "L1NativeTokenVault", - [l1WethToken, this.addresses.Bridges.SharedBridgeProxy, eraChainId, this.addresses.Bridges.L1NullifierProxy], + [l1WethToken, this.addresses.Bridges.SharedBridgeProxy, this.addresses.Bridges.L1NullifierProxy], create2Salt, ethTxOptions ); @@ -1710,10 +1712,9 @@ export class Deployer { public async deployValidatorTimelock(create2Salt: string, ethTxOptions: ethers.providers.TransactionRequest) { const executionDelay = getNumberFromEnv("CONTRACTS_VALIDATOR_TIMELOCK_EXECUTION_DELAY"); - const eraChainId = getNumberFromEnv("CONTRACTS_ERA_CHAIN_ID"); const contractAddress = await this.deployViaCreate2( "ValidatorTimelock", - [this.ownerAddress, executionDelay, eraChainId], + [this.ownerAddress, executionDelay], create2Salt, ethTxOptions ); diff --git a/l1-contracts/src.ts/utils.ts b/l1-contracts/src.ts/utils.ts index 190a5743c..32eaf5f6e 100644 --- a/l1-contracts/src.ts/utils.ts +++ b/l1-contracts/src.ts/utils.ts @@ -47,7 +47,7 @@ export const FORCE_DEPLOYMENT_ABI_STRING = "tuple(bytes32 bytecodeHash, address newAddress, bool callConstructor, uint256 value, bytes input)[]"; export const BRIDGEHUB_CTM_ASSET_DATA_ABI_STRING = "tuple(uint256 chainId, bytes ctmData, bytes chainData)"; export const FIXED_FORCE_DEPLOYMENTS_DATA_ABI_STRING = - "tuple(uint256 l1ChainId, uint256 eraChainId, address l1AssetRouter, bytes32 l2TokenProxyBytecodeHash, address aliasedL1Governance, uint256 maxNumberOfZKChains, bytes32 bridgehubBytecodeHash, bytes32 l2AssetRouterBytecodeHash, bytes32 l2NtvBytecodeHash, bytes32 messageRootBytecodeHash, address l2SharedBridgeLegacyImpl, address l2BridgedStandardERC20Impl, address l2BridgeProxyOwnerAddress, address l2BridgedStandardERC20ProxyOwnerAddress)"; + "tuple(uint256 l1ChainId, uint256 eraChainId, address l1AssetRouter, bytes32 l2TokenProxyBytecodeHash, address aliasedL1Governance, uint256 maxNumberOfZKChains, bytes32 bridgehubBytecodeHash, bytes32 l2AssetRouterBytecodeHash, bytes32 l2NtvBytecodeHash, bytes32 messageRootBytecodeHash, address l2SharedBridgeLegacyImpl, address l2BridgedStandardERC20Impl)"; export const ADDITIONAL_FORCE_DEPLOYMENTS_DATA_ABI_STRING = "tuple(bytes32 baseTokenAssetId, address l2Weth)"; export function applyL1ToL2Alias(address: string): string { @@ -167,7 +167,6 @@ export interface FeeParams { export interface ProposedUpgrade { // The tx for the upgrade call to the l2 system upgrade contract l2ProtocolUpgradeTx: L2CanonicalTransaction; - factoryDeps: BytesLike[]; bootloaderHash: BytesLike; defaultAccountHash: BytesLike; verifier: string; diff --git a/l1-contracts/test/foundry/L1TestsErrors.sol b/l1-contracts/test/foundry/L1TestsErrors.sol new file mode 100644 index 000000000..0eabefc4c --- /dev/null +++ b/l1-contracts/test/foundry/L1TestsErrors.sol @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.21; + +error AddressesAlreadyGenerated(); + +error DepositNotSet(); + +error FeeParamsWereNotChangedCorrectly(); + +error EventOnFallbackTargetExpected(); + +error OverheadForTransactionMustBeEqualToTxSlotOverhead(uint256 overheadForTransaction); + +error InvalidBlobCommitmentsLength(); + +error InvalidBlobHashesLength(); diff --git a/l1-contracts/test/foundry/l1/integration/AssetRouterTest.t.sol b/l1-contracts/test/foundry/l1/integration/AssetRouterTest.t.sol index 7d122638d..881c38e88 100644 --- a/l1-contracts/test/foundry/l1/integration/AssetRouterTest.t.sol +++ b/l1-contracts/test/foundry/l1/integration/AssetRouterTest.t.sol @@ -89,8 +89,8 @@ contract AssetRouterTest is L1ContractDeployer, ZKChainDeployer, TokenDeployer, l2TokenAssetId = DataEncoding.encodeNTVAssetId(chainId, _tokenAddress); bytes memory transferData = DataEncoding.encodeBridgeMintData({ _originalCaller: ETH_TOKEN_ADDRESS, - _l2Receiver: address(this), - _l1Token: ETH_TOKEN_ADDRESS, + _remoteReceiver: address(this), + _originToken: ETH_TOKEN_ADDRESS, _amount: 100, _erc20Metadata: BridgeHelper.getERC20Getters(_tokenAddress, chainId) }); diff --git a/l1-contracts/test/foundry/l1/integration/BridgeHubInvariantTests.t.sol b/l1-contracts/test/foundry/l1/integration/BridgeHubInvariantTests.t.sol index b4fec78de..77c1aa2a3 100644 --- a/l1-contracts/test/foundry/l1/integration/BridgeHubInvariantTests.t.sol +++ b/l1-contracts/test/foundry/l1/integration/BridgeHubInvariantTests.t.sol @@ -22,6 +22,7 @@ import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IL1ERC20Bridge} from "contracts/bridge/interfaces/IL1ERC20Bridge.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; +import {AddressesAlreadyGenerated} from "test/foundry/L1TestsErrors.sol"; contract BridgeHubInvariantTests is L1ContractDeployer, ZKChainDeployer, TokenDeployer, L2TxMocker { uint256 constant TEST_USERS_COUNT = 10; @@ -122,7 +123,9 @@ contract BridgeHubInvariantTests is L1ContractDeployer, ZKChainDeployer, TokenDe // generate MAX_USERS addresses and append it to users array function _generateUserAddresses() internal { - require(users.length == 0, "Addresses already generated"); + if (users.length != 0) { + revert AddressesAlreadyGenerated(); + } for (uint256 i = 0; i < TEST_USERS_COUNT; i++) { address newAddress = makeAddr(string(abi.encode("account", i))); diff --git a/l1-contracts/test/foundry/l1/integration/BridgehubTests.t.sol b/l1-contracts/test/foundry/l1/integration/BridgehubTests.t.sol index a99790839..1467d8535 100644 --- a/l1-contracts/test/foundry/l1/integration/BridgehubTests.t.sol +++ b/l1-contracts/test/foundry/l1/integration/BridgehubTests.t.sol @@ -22,6 +22,7 @@ import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IL1ERC20Bridge} from "contracts/bridge/interfaces/IL1ERC20Bridge.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; +import {AddressesAlreadyGenerated} from "test/foundry/L1TestsErrors.sol"; contract BridgeHubInvariantTests is L1ContractDeployer, ZKChainDeployer, TokenDeployer, L2TxMocker { uint256 constant TEST_USERS_COUNT = 10; @@ -122,7 +123,9 @@ contract BridgeHubInvariantTests is L1ContractDeployer, ZKChainDeployer, TokenDe // generate MAX_USERS addresses and append it to users array function _generateUserAddresses() internal { - require(users.length == 0, "Addresses already generated"); + if (users.length != 0) { + revert AddressesAlreadyGenerated(); + } for (uint256 i = 0; i < TEST_USERS_COUNT; i++) { address newAddress = makeAddr(string(abi.encode("account", i))); diff --git a/l1-contracts/test/foundry/l1/integration/DeploymentTest.t.sol b/l1-contracts/test/foundry/l1/integration/DeploymentTest.t.sol index b4cca3bb1..1c8bba297 100644 --- a/l1-contracts/test/foundry/l1/integration/DeploymentTest.t.sol +++ b/l1-contracts/test/foundry/l1/integration/DeploymentTest.t.sol @@ -24,6 +24,7 @@ import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2ContractAdd import {IL1ERC20Bridge} from "contracts/bridge/interfaces/IL1ERC20Bridge.sol"; import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; import {IChainTypeManager} from "contracts/state-transition/IChainTypeManager.sol"; +import {AddressesAlreadyGenerated} from "test/foundry/L1TestsErrors.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; import {IncorrectBridgeHubAddress} from "contracts/common/L1ContractErrors.sol"; @@ -34,7 +35,9 @@ contract DeploymentTests is L1ContractDeployer, ZKChainDeployer, TokenDeployer, // generate MAX_USERS addresses and append it to users array function _generateUserAddresses() internal { - require(users.length == 0, "Addresses already generated"); + if (users.length != 0) { + revert AddressesAlreadyGenerated(); + } for (uint256 i = 0; i < TEST_USERS_COUNT; i++) { address newAddress = makeAddr(string(abi.encode("account", i))); diff --git a/l1-contracts/test/foundry/l1/integration/L1GatewayTests.t.sol b/l1-contracts/test/foundry/l1/integration/L1GatewayTests.t.sol index 9f67d7973..8a8ea62b2 100644 --- a/l1-contracts/test/foundry/l1/integration/L1GatewayTests.t.sol +++ b/l1-contracts/test/foundry/l1/integration/L1GatewayTests.t.sol @@ -34,6 +34,7 @@ import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol import {IChainTypeManager} from "contracts/state-transition/IChainTypeManager.sol"; import {AdminFacet} from "contracts/state-transition/chain-deps/facets/Admin.sol"; import {AddressAliasHelper} from "contracts/vendor/AddressAliasHelper.sol"; +import {AddressesAlreadyGenerated} from "test/foundry/L1TestsErrors.sol"; import {TxStatus} from "contracts/common/Messaging.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; import {IncorrectBridgeHubAddress} from "contracts/common/L1ContractErrors.sol"; @@ -55,7 +56,9 @@ contract L1GatewayTests is L1ContractDeployer, ZKChainDeployer, TokenDeployer, L // generate MAX_USERS addresses and append it to users array function _generateUserAddresses() internal { - require(users.length == 0, "Addresses already generated"); + if (users.length != 0) { + revert AddressesAlreadyGenerated(); + } for (uint256 i = 0; i < TEST_USERS_COUNT; i++) { address newAddress = makeAddr(string(abi.encode("account", i))); diff --git a/l1-contracts/test/foundry/l1/integration/UpgradeTest.t.sol b/l1-contracts/test/foundry/l1/integration/UpgradeTest.t.sol index 3cbcf454b..6434ce976 100644 --- a/l1-contracts/test/foundry/l1/integration/UpgradeTest.t.sol +++ b/l1-contracts/test/foundry/l1/integration/UpgradeTest.t.sol @@ -32,21 +32,13 @@ contract UpgradeTest is Test { // For chain, we have deployed the DA validator contracts // and also updated the chain admin. - // IMPORTANT: for erc20-based chains with token multiplier setter - // this should be coordinated with the server. console.log("Preparing chain for the upgrade"); chainUpgrade.prepareChain(ECOSYSTEM_INPUT, ECOSYSTEM_OUTPUT, CHAIN_INPUT, CHAIN_OUTPUT); console.log("Starting stage1 of the upgrade!"); // Now, some time has passed and we are ready to start the upgrade of the // ecosystem. - // Stage 1 of the upgrade: - // - accept all the ownerships of the contracts - // - set the new upgrade data for chains + update validator timelock. - Call[] memory stage1Calls = mergeCalls( - generateUpgradeData.provideAcceptOwnershipCalls(), - generateUpgradeData.provideSetNewVersionUpgradeCall() - ); + Call[] memory stage1Calls = generateUpgradeData.getStage1UpgradeCalls(); governanceMulticall(generateUpgradeData.getOwnerAddress(), stage1Calls); @@ -65,8 +57,7 @@ contract UpgradeTest is Test { // TODO: here we should include tests that depoists work for upgraded chains // including era specific deposit/withdraw functions // We also may need to test that normal flow of block commit / verify / execute works (but it is hard) - - vm.warp(generateUpgradeData.getOldProtocolDeadline()); + // so it was tested in e2e local environment. console.log("Starting stage2 of the upgrade!"); governanceMulticall(generateUpgradeData.getOwnerAddress(), generateUpgradeData.getStage2UpgradeCalls()); @@ -92,14 +83,4 @@ contract UpgradeTest is Test { vm.stopBroadcast(); } - - function mergeCalls(Call[] memory a, Call[] memory b) internal pure returns (Call[] memory result) { - result = new Call[](a.length + b.length); - for (uint256 i = 0; i < a.length; i++) { - result[i] = a[i]; - } - for (uint256 i = 0; i < b.length; i++) { - result[a.length + i] = b[i]; - } - } } diff --git a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2Erc20TestAbstract.t.sol b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2Erc20TestAbstract.t.sol index fcabf0d01..b73b829b3 100644 --- a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2Erc20TestAbstract.t.sol +++ b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2Erc20TestAbstract.t.sol @@ -1,7 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; - // solhint-disable gas-custom-errors import {Test} from "forge-std/Test.sol"; @@ -48,7 +47,9 @@ abstract contract L2Erc20TestAbstract is Test, SharedL2ContractDeployer { performDeposit(makeAddr("someDepositor"), makeAddr("someReeiver"), 1); l2TokenAddress = IL2NativeTokenVault(L2_NATIVE_TOKEN_VAULT_ADDR).l2TokenAddress(L1_TOKEN_ADDRESS); - require(l2TokenAddress != address(0), "Token not initialized"); + if (l2TokenAddress == address(0)) { + revert("Token not initialized"); + } } function test_shouldFinalizeERC20Deposit() public { @@ -83,7 +84,7 @@ abstract contract L2Erc20TestAbstract is Test, SharedL2ContractDeployer { assertEq(BridgedStandardERC20(l2TokenAddress).decimals(), 18); } - function test_governanceShouldNotBeAbleToSkipInitializerVersions() public { + function test_governanceShouldlNotBeAbleToSkipInitializerVersions() public { address l2TokenAddress = initializeTokenByDeposit(); BridgedStandardERC20.ERC20Getters memory getters = BridgedStandardERC20.ERC20Getters({ diff --git a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2WethTestAbstract.t.sol b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2WethTestAbstract.t.sol index d2a43be2e..3bc89b3ef 100644 --- a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2WethTestAbstract.t.sol +++ b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/L2WethTestAbstract.t.sol @@ -11,9 +11,7 @@ import {BridgedStandardERC20} from "contracts/bridge/BridgedStandardERC20.sol"; import {L2AssetRouter} from "contracts/bridge/asset-router/L2AssetRouter.sol"; import {IL2NativeTokenVault} from "contracts/bridge/ntv/IL2NativeTokenVault.sol"; -import {UpgradeableBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/UpgradeableBeacon.sol"; -import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; - +import {Unauthorized, BridgeMintNotImplemented} from "contracts/common/L1ContractErrors.sol"; import {L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR, L2_BRIDGEHUB_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {ETH_TOKEN_ADDRESS, SETTLEMENT_LAYER_RELAY_SENDER} from "contracts/common/Config.sol"; @@ -31,7 +29,6 @@ import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol import {SystemContractsArgs} from "./_SharedL2ContractL1DeployerUtils.sol"; import {DeployUtils} from "deploy-scripts/DeployUtils.s.sol"; -import {Unauthorized, UnimplementedMessage, BridgeMintNotImplemented} from "contracts/common/L1ContractErrors.sol"; abstract contract L2WethTestAbstract is Test, SharedL2ContractDeployer { function test_shouldDepositWethByCallingDeposit() public { diff --git a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractDeployer.sol b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractDeployer.sol index 83d8def98..b0c0ac6f7 100644 --- a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractDeployer.sol +++ b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractDeployer.sol @@ -117,7 +117,7 @@ abstract contract SharedL2ContractDeployer is Test, DeployUtils { vm.prank(ownerWallet); l2Bridgehub.addChainTypeManager(address(addresses.stateTransition.chainTypeManagerProxy)); vm.prank(AddressAliasHelper.applyL1ToL2Alias(l1CTMDeployer)); - l2Bridgehub.setAssetHandlerAddress( + l2Bridgehub.setCTMAssetAddress( bytes32(uint256(uint160(l1CTM))), address(addresses.stateTransition.chainTypeManagerProxy) ); @@ -136,6 +136,12 @@ abstract contract SharedL2ContractDeployer is Test, DeployUtils { abi.encodeWithSelector(IL1Nullifier.l2BridgeAddress.selector), abi.encode(address(0)) ); + vm.mockCall( + L2_BRIDGEHUB_ADDR, + abi.encodeWithSelector(IBridgehub.baseToken.selector, ERA_CHAIN_ID + 1), + abi.encode(address(uint160(1))) + ); + vm.prank(L2_BRIDGEHUB_ADDR); address chainAddress = chainTypeManager.createNewChain( ERA_CHAIN_ID + 1, @@ -193,7 +199,7 @@ abstract contract SharedL2ContractDeployer is Test, DeployUtils { L2WrappedBaseToken wethImpl = new L2WrappedBaseToken(); TransparentUpgradeableProxy wethProxy = new TransparentUpgradeableProxy(address(wethImpl), ownerWallet, ""); weth = L2WrappedBaseToken(payable(wethProxy)); - weth.initializeV2("Wrapped Ether", "WETH", L2_ASSET_ROUTER_ADDR, l1WethAddress, baseTokenAssetId); + weth.initializeV3("Wrapped Ether", "WETH", L2_ASSET_ROUTER_ADDR, l1WethAddress, baseTokenAssetId); return weth; } diff --git a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractL1DeployerUtils.sol b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractL1DeployerUtils.sol index 9dd125055..c5076c3c1 100644 --- a/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractL1DeployerUtils.sol +++ b/l1-contracts/test/foundry/l1/integration/l2-tests-in-l1-context/_SharedL2ContractL1DeployerUtils.sol @@ -89,7 +89,6 @@ contract SharedL2ContractL1DeployerUtils is DeployUtils { ); vm.etch(L2_ASSET_ROUTER_ADDR, assetRouter.code); - stdstore.target(address(L2_ASSET_ROUTER_ADDR)).sig("l1AssetRouter()").checked_write(_args.l1AssetRouter); stdstore .target(L2_ASSET_ROUTER_ADDR) @@ -121,7 +120,7 @@ contract SharedL2ContractL1DeployerUtils is DeployUtils { deployGenesisUpgrade(); deployVerifier(); deployValidatorTimelock(); - deployChainTypeManagerContract(); + deployChainTypeManagerContract(address(0)); } // add this to be excluded from coverage report diff --git a/l1-contracts/test/foundry/l1/integration/upgrade-envs/script-config/mainnet.toml b/l1-contracts/test/foundry/l1/integration/upgrade-envs/script-config/mainnet.toml index abf681e37..f3d5669bf 100644 --- a/l1-contracts/test/foundry/l1/integration/upgrade-envs/script-config/mainnet.toml +++ b/l1-contracts/test/foundry/l1/integration/upgrade-envs/script-config/mainnet.toml @@ -9,7 +9,6 @@ validator_timelock_execution_delay = 0 genesis_root = "0xf9030b78c5bf5ac997a76962aa32c90a6d8e8ebce9838c8eeb388d73e1f7659a" genesis_rollup_leaf_index = 64 genesis_batch_commitment = "0x34c1b220363e0cde7eaf10fe95754d61de097e0f9d9a1dc56c8026562e395259" -latest_protocol_version = "0x1900000000" recursion_node_level_vk_hash = "0x0000000000000000000000000000000000000000000000000000000000000000" recursion_leaf_level_vk_hash = "0x0000000000000000000000000000000000000000000000000000000000000000" recursion_circuits_set_vks_hash = "0x0000000000000000000000000000000000000000000000000000000000000000" @@ -20,8 +19,8 @@ diamond_init_max_pubdata_per_batch = 120000 diamond_init_max_l2_gas_per_batch = 80000000 diamond_init_priority_tx_max_pubdata = 99000 diamond_init_minimal_l2_gas_price = 250000000 -bootloader_hash = "0x010008c753336bc8d1ddca235602b9f31d346412b2d463cd342899f7bfb73baf" -default_aa_hash = "0x0100055d760f11a3d737e7fd1816e600a4cd874a9f17f7a225d1f1c537c51a1e" +bootloader_hash = "0x010008c79fe70427642db69b14314af076e5d54f1dada975b905bcbb5feb9f9e" +default_aa_hash = "0x0100055d4fddeeba9063fbdecd1dde707c04f84fdbd1b576f5230977e78ca775" bridgehub_proxy_address = "0x303a465B659cBB0ab36eE643eA362c509EEb5213" old_shared_bridge_proxy_address = "0xD7f9f54194C633F36CCD5F3da84ad4a1c38cB2cB" state_transition_manager_address = "0xc2eE6b6af7d616f6e27ce7F4A451Aedc2b0F5f5C" diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/MessageRoot.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/MessageRoot.t.sol index 34ca5f9d2..a3c917d56 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/MessageRoot.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/MessageRoot.t.sol @@ -5,6 +5,7 @@ pragma solidity 0.8.24; import {Test} from "forge-std/Test.sol"; import {MessageRoot} from "contracts/bridgehub/MessageRoot.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; +import {OnlyBridgehub, MessageRootNotRegistered} from "contracts/bridgehub/L1BridgehubErrors.sol"; import {Merkle} from "contracts/common/libraries/Merkle.sol"; import {MessageHashing} from "contracts/common/libraries/MessageHashing.sol"; @@ -37,7 +38,7 @@ contract MessageRootTest is Test { assertFalse(messageRoot.chainRegistered(alphaChainId), "alpha chain 1"); - vm.expectRevert("MR: only bridgehub"); + vm.expectRevert(abi.encodeWithSelector(OnlyBridgehub.selector, address(this), bridgeHub)); messageRoot.addNewChain(alphaChainId); assertFalse(messageRoot.chainRegistered(alphaChainId), "alpha chain 2"); @@ -71,7 +72,7 @@ contract MessageRootTest is Test { ); vm.prank(alphaChainSender); - vm.expectRevert("MR: not registered"); + vm.expectRevert(MessageRootNotRegistered.selector); messageRoot.addChainBatchRoot(alphaChainId, 1, bytes32(alphaChainId)); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/experimental_bridge.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/experimental_bridge.t.sol index 6ffbbc0e9..83ac20721 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/experimental_bridge.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridgehub/experimental_bridge.t.sol @@ -28,10 +28,11 @@ import {ICTMDeploymentTracker} from "contracts/bridgehub/ICTMDeploymentTracker.s import {IMessageRoot} from "contracts/bridgehub/IMessageRoot.sol"; import {MessageRoot} from "contracts/bridgehub/MessageRoot.sol"; import {L2TransactionRequestTwoBridgesInner} from "contracts/bridgehub/IBridgehub.sol"; -import {ETH_TOKEN_ADDRESS, REQUIRED_L2_GAS_PRICE_PER_PUBDATA, MAX_NEW_FACTORY_DEPS, TWO_BRIDGES_MAGIC_VALUE} from "contracts/common/Config.sol"; +import {ETH_TOKEN_ADDRESS, REQUIRED_L2_GAS_PRICE_PER_PUBDATA, MAX_NEW_FACTORY_DEPS, TWO_BRIDGES_MAGIC_VALUE, BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS} from "contracts/common/Config.sol"; import {L1ERC20Bridge} from "contracts/bridge/L1ERC20Bridge.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; -import {AssetIdNotSupported, ZeroChainId, ChainAlreadyLive, AssetIdAlreadyRegistered, AddressTooLow, ChainIdTooBig, WrongMagicValue, SharedBridgeNotSet, TokenNotRegistered, BridgeHubAlreadyRegistered, MsgValueMismatch, SlotOccupied, CTMAlreadyRegistered, TokenAlreadyRegistered, Unauthorized, NonEmptyMsgValue, CTMNotRegistered, InvalidChainId} from "contracts/common/L1ContractErrors.sol"; +import {AssetIdNotSupported, ZeroChainId, AssetIdAlreadyRegistered, ChainIdTooBig, WrongMagicValue, SharedBridgeNotSet, BridgeHubAlreadyRegistered, MsgValueMismatch, SlotOccupied, CTMAlreadyRegistered, Unauthorized, NonEmptyMsgValue, CTMNotRegistered} from "contracts/common/L1ContractErrors.sol"; +import {SecondBridgeAddressTooLow} from "contracts/bridgehub/L1BridgehubErrors.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; contract ExperimentalBridgeTest is Test { @@ -189,7 +190,7 @@ contract ExperimentalBridgeTest is Test { } function _deployNTV(address _sharedBridgeAddr) internal returns (L1NativeTokenVault addr) { - L1NativeTokenVault ntvImpl = new L1NativeTokenVault(weth, _sharedBridgeAddr, eraChainId, l1Nullifier); + L1NativeTokenVault ntvImpl = new L1NativeTokenVault(weth, _sharedBridgeAddr, l1Nullifier); TransparentUpgradeableProxy ntvProxy = new TransparentUpgradeableProxy( address(ntvImpl), address(bridgeOwner), @@ -1319,7 +1320,13 @@ contract ExperimentalBridgeTest is Test { ); l2TxnReq2BridgeOut.secondBridgeAddress = address(secondBridgeAddressValue); - vm.expectRevert(abi.encodeWithSelector(AddressTooLow.selector, secondBridgeAddress)); + vm.expectRevert( + abi.encodeWithSelector( + SecondBridgeAddressTooLow.selector, + secondBridgeAddress, + BRIDGEHUB_MIN_SECOND_BRIDGE_ADDRESS + ) + ); vm.prank(randomCaller); bridgeHub.requestL2TransactionTwoBridges{value: randomCaller.balance}(l2TxnReq2BridgeOut); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1Erc20Bridge/_L1Erc20Bridge_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1Erc20Bridge/_L1Erc20Bridge_Shared.t.sol index fb0c30c58..acbc8ccec 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1Erc20Bridge/_L1Erc20Bridge_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1Erc20Bridge/_L1Erc20Bridge_Shared.t.sol @@ -47,12 +47,7 @@ contract L1Erc20BridgeTest is Test { ); address weth = makeAddr("weth"); - L1NativeTokenVault ntv = new L1NativeTokenVault( - weth, - sharedBridgeAddress, - eraChainId, - IL1Nullifier(l1NullifierAddress) - ); + L1NativeTokenVault ntv = new L1NativeTokenVault(weth, sharedBridgeAddress, IL1Nullifier(l1NullifierAddress)); vm.store(address(bridge), bytes32(uint256(212)), bytes32(0)); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeBase.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeBase.t.sol index dd3b8c145..836304f62 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeBase.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeBase.t.sol @@ -17,6 +17,7 @@ import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR} from "contract import {IGetters} from "contracts/state-transition/chain-interfaces/IGetters.sol"; import {L1NativeTokenVault} from "contracts/bridge/ntv/L1NativeTokenVault.sol"; import {StdStorage, stdStorage} from "forge-std/Test.sol"; +import {DepositNotSet} from "test/foundry/L1TestsErrors.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; contract L1AssetRouterTestBase is L1AssetRouterTest { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeFails.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeFails.t.sol index 0603a34dc..2990e6695 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeFails.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeFails.t.sol @@ -21,8 +21,10 @@ import {INativeTokenVault} from "contracts/bridge/ntv/INativeTokenVault.sol"; import {L1NativeTokenVault} from "contracts/bridge/ntv/L1NativeTokenVault.sol"; import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IGetters} from "contracts/state-transition/chain-interfaces/IGetters.sol"; -import {AddressAlreadyUsed, WithdrawFailed, Unauthorized, AssetIdNotSupported, SharedBridgeKey, SharedBridgeValueNotSet, L2WithdrawalMessageWrongLength, InsufficientChainBalance, ZeroAddress, ValueMismatch, NonEmptyMsgValue, DepositExists, ValueMismatch, NonEmptyMsgValue, TokenNotSupported, EmptyDeposit, L2BridgeNotDeployed, InvalidProof, NoFundsTransferred, InsufficientFunds, DepositDoesNotExist, WithdrawalAlreadyFinalized, InsufficientFunds, MalformedMessage, InvalidSelector, TokensWithFeesNotSupported} from "contracts/common/L1ContractErrors.sol"; +import {AddressAlreadyUsed, WithdrawFailed, Unauthorized, AssetIdNotSupported, SharedBridgeKey, SharedBridgeValueNotSet, L2WithdrawalMessageWrongLength, InsufficientChainBalance, ZeroAddress, ValueMismatch, NonEmptyMsgValue, DepositExists, ValueMismatch, NonEmptyMsgValue, TokenNotSupported, EmptyDeposit, InvalidProof, NoFundsTransferred, DepositDoesNotExist, WithdrawalAlreadyFinalized, InvalidSelector, TokensWithFeesNotSupported} from "contracts/common/L1ContractErrors.sol"; import {StdStorage, stdStorage} from "forge-std/Test.sol"; +import {DepositNotSet} from "test/foundry/L1TestsErrors.sol"; +import {WrongCounterpart, EthTransferFailed, EmptyToken, NativeTokenVaultAlreadySet, ZeroAmountToTransfer, WrongAmountTransferred, ClaimFailedDepositFailed} from "contracts/bridge/L1BridgeContractErrors.sol"; /// We are testing all the specified revert and require cases. contract L1AssetRouterFailTest is L1AssetRouterTest { @@ -61,12 +63,12 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { } function test_nullifyChainBalanceByNTV_wrongCaller() public { - vm.expectRevert("L1N: not NTV"); + vm.expectRevert(); l1Nullifier.nullifyChainBalanceByNTV(chainId, address(token)); } function test_registerToken_noCode() public { - vm.expectRevert("NTV: empty token"); + vm.expectRevert(abi.encodeWithSelector(EmptyToken.selector)); nativeTokenVault.registerToken(address(0)); } @@ -86,14 +88,14 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { function test_setNativeTokenVault_alreadySet() public { vm.prank(owner); - vm.expectRevert("AR: native token v already set"); + vm.expectRevert(NativeTokenVaultAlreadySet.selector); sharedBridge.setNativeTokenVault(INativeTokenVault(address(0))); } function test_setNativeTokenVault_emptyAddressProvided() public { stdstore.target(address(sharedBridge)).sig(sharedBridge.nativeTokenVault.selector).checked_write(address(0)); vm.prank(owner); - vm.expectRevert("AR: native token vault 0"); + vm.expectRevert(ZeroAddress.selector); sharedBridge.setNativeTokenVault(INativeTokenVault(address(0))); } @@ -104,14 +106,14 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { ); vm.prank(bridgehubAddress); - vm.expectRevert("NTV: wrong counterpart"); + vm.expectRevert(abi.encodeWithSelector(WrongCounterpart.selector)); sharedBridge.bridgehubDeposit(eraChainId, owner, 0, data); } function test_transferFundsToSharedBridge_Eth_CallFailed() public { vm.mockCallRevert(address(nativeTokenVault), "", "eth transfer failed"); vm.prank(address(nativeTokenVault)); - vm.expectRevert("L1N: eth transfer failed"); + vm.expectRevert(abi.encodeWithSelector(EthTransferFailed.selector)); l1Nullifier.transferTokenToNTV(ETH_TOKEN_ADDRESS); } @@ -126,14 +128,14 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { vm.prank(address(l1Nullifier)); token.transfer(address(1), amount); vm.prank(address(nativeTokenVault)); - vm.expectRevert("NTV: 0 amount to transfer"); + vm.expectRevert(ZeroAmountToTransfer.selector); nativeTokenVault.transferFundsFromSharedBridge(address(token)); } function test_transferFundsToSharedBridge_Erc_WrongAmountTransferred() public { vm.mockCall(address(token), abi.encodeWithSelector(IERC20.balanceOf.selector), abi.encode(10)); vm.prank(address(nativeTokenVault)); - vm.expectRevert("NTV: wrong amount transferred"); + vm.expectRevert(abi.encodeWithSelector(WrongAmountTransferred.selector, 0, 10)); nativeTokenVault.transferFundsFromSharedBridge(address(token)); } @@ -297,7 +299,7 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { abi.encode(true) ); - vm.expectRevert("NTV: claimFailedDeposit failed, no funds or cannot transfer to receiver"); + vm.expectRevert(ClaimFailedDepositFailed.selector); l1Nullifier.bridgeRecoverFailedTransfer({ _chainId: chainId, _depositSender: alice, @@ -377,7 +379,7 @@ contract L1AssetRouterFailTest is L1AssetRouterTest { abi.encode(true) ); - vm.expectRevert(); + vm.expectRevert(InsufficientChainBalance.selector); vm.mockCall( address(bridgehubAddress), abi.encodeWithSelector(IBridgehub.proveL1ToL2TransactionStatus.selector), diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeHyperEnabled.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeHyperEnabled.t.sol index 6dc2da4e4..12b58108e 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeHyperEnabled.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/L1SharedBridgeHyperEnabled.t.sol @@ -10,6 +10,7 @@ import {IMailbox} from "contracts/state-transition/chain-interfaces/IMailbox.sol import {IL1AssetRouter} from "contracts/bridge/asset-router/IL1AssetRouter.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {L2_BASE_TOKEN_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR} from "contracts/common/L2ContractAddresses.sol"; +import {DepositNotSet} from "test/foundry/L1TestsErrors.sol"; // note, this should be the same as where hyper is disabled contract L1AssetRouterHyperEnabledTest is L1AssetRouterTest { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/_L1SharedBridge_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/_L1SharedBridge_Shared.t.sol index de655e7ee..f7ab8c6f5 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/_L1SharedBridge_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L1SharedBridge/_L1SharedBridge_Shared.t.sol @@ -153,7 +153,6 @@ contract L1AssetRouterTest is Test { nativeTokenVaultImpl = new L1NativeTokenVault({ _l1WethAddress: l1WethAddress, _l1AssetRouter: address(sharedBridge), - _eraChainId: eraChainId, _l1Nullifier: l1Nullifier }); address tokenBeacon = makeAddr("tokenBeacon"); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L2WrappedBaseTokenStore.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L2WrappedBaseTokenStore.t.sol new file mode 100644 index 000000000..7188f89a5 --- /dev/null +++ b/l1-contracts/test/foundry/l1/unit/concrete/Bridges/L2WrappedBaseTokenStore.t.sol @@ -0,0 +1,288 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.19; + +import {Test} from "forge-std/Test.sol"; +import {L2WrappedBaseTokenStore} from "contracts/bridge/L2WrappedBaseTokenStore.sol"; +import {ZeroAddress, Unauthorized} from "contracts/common/L1ContractErrors.sol"; + +contract L2WrappedBaseTokenStoreTest is Test { + L2WrappedBaseTokenStore store; + + address owner = address(0x1); + address admin = address(0x2); + address other = address(0x3); + address newAdmin = address(0x4); + address newPendingAdmin = address(0x5); + uint256 chainId = 100; + address l2WBaseToken = address(0xABC); + address newL2WBaseToken = address(0xDEF); + + // Events + event NewAdmin(address indexed oldAdmin, address indexed newAdmin); + event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin); + event NewWBaseTokenAddress(uint256 indexed chainId, address indexed l2WBaseTokenAddress); + + function setUp() public { + // Deploy the contract with owner and admin + vm.startPrank(owner); + store = new L2WrappedBaseTokenStore(owner, admin); + vm.stopPrank(); + } + + // Deployment Tests + function testInitialOwner() public { + assertEq(store.owner(), owner, "Owner should be set correctly"); + } + + function testInitialAdmin() public { + assertEq(store.admin(), admin, "Admin should be set correctly"); + } + + function testConstructorRevertsZeroOwner() public { + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + new L2WrappedBaseTokenStore(address(0), admin); + } + + function testConstructorRevertsZeroAdmin() public { + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + new L2WrappedBaseTokenStore(owner, address(0)); + } + + // Access Control Tests + function testOnlyOwnerOrAdminCanInitializeChain() public { + // Attempt from owner + vm.startPrank(owner); + store.initializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + + // Attempt from admin + vm.startPrank(admin); + store.initializeChain(chainId + 1, l2WBaseToken); + vm.stopPrank(); + + // Attempt from other + vm.startPrank(other); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, other)); + store.initializeChain(chainId + 2, l2WBaseToken); + vm.stopPrank(); + } + + function testOnlyOwnerCanReinitializeChain() public { + // Initialize first + vm.startPrank(admin); + store.initializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + + // Reinitialize from owner + vm.startPrank(owner); + store.reinitializeChain(chainId, newL2WBaseToken); + vm.stopPrank(); + + // Reinitialize from admin should fail + vm.startPrank(admin); + vm.expectRevert("Ownable: caller is not the owner"); + store.reinitializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + + // Reinitialize from other should fail + vm.startPrank(other); + vm.expectRevert("Ownable: caller is not the owner"); + store.reinitializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + } + + // initializeChain Tests + function testInitializeChain() public { + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit NewWBaseTokenAddress(chainId, l2WBaseToken); + store.initializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + + address storedAddress = store.l2WBaseTokenAddress(chainId); + assertEq(storedAddress, l2WBaseToken, "L2 WBaseToken address should be set correctly"); + } + + function testInitializeChainRevertsZeroAddress() public { + vm.startPrank(owner); + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + store.initializeChain(chainId, address(0)); + vm.stopPrank(); + } + + // reinitializeChain Tests + function testReinitializeChain() public { + // Initialize first + vm.startPrank(admin); + store.initializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + + // Reinitialize + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit NewWBaseTokenAddress(chainId, newL2WBaseToken); + store.reinitializeChain(chainId, newL2WBaseToken); + vm.stopPrank(); + + address storedAddress = store.l2WBaseTokenAddress(chainId); + assertEq(storedAddress, newL2WBaseToken, "L2 WBaseToken address should be updated correctly"); + } + + function testReinitializeChainRevertsZeroAddress() public { + vm.startPrank(owner); + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + store.reinitializeChain(chainId, address(0)); + vm.stopPrank(); + } + + // setPendingAdmin Tests + function testSetPendingAdmin() public { + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit NewPendingAdmin(address(0), newPendingAdmin); + store.setPendingAdmin(newPendingAdmin); + vm.stopPrank(); + + assertEq(store.pendingAdmin(), newPendingAdmin, "Pending admin should be set correctly"); + } + + function testSetPendingAdminByAdmin() public { + vm.startPrank(admin); + vm.expectEmit(true, true, false, true); + emit NewPendingAdmin(address(0), newPendingAdmin); + store.setPendingAdmin(newPendingAdmin); + vm.stopPrank(); + + assertEq(store.pendingAdmin(), newPendingAdmin, "Pending admin should be set correctly by admin"); + } + + function testSetPendingAdminRevertsZeroAddress() public { + vm.startPrank(owner); + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + store.setPendingAdmin(address(0)); + vm.stopPrank(); + } + + function testSetPendingAdminUnauthorized() public { + vm.startPrank(other); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, other)); + store.setPendingAdmin(newPendingAdmin); + vm.stopPrank(); + } + + // acceptAdmin Tests + function testAcceptAdmin() public { + // Set pending admin + vm.startPrank(owner); + store.setPendingAdmin(newAdmin); + vm.stopPrank(); + + // Accept admin by newAdmin + vm.startPrank(newAdmin); + vm.expectEmit(true, true, false, true); + emit NewPendingAdmin(newAdmin, address(0)); + vm.expectEmit(true, true, false, true); + emit NewAdmin(admin, newAdmin); + store.acceptAdmin(); + vm.stopPrank(); + + assertEq(store.admin(), newAdmin, "Admin should be updated correctly"); + assertEq(store.pendingAdmin(), address(0), "Pending admin should be cleared"); + } + + function testAcceptAdminRevertsIfNotPendingAdmin() public { + // Set pending admin + vm.startPrank(owner); + store.setPendingAdmin(newAdmin); + vm.stopPrank(); + + // Attempt to accept by someone else + vm.startPrank(other); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, other)); + store.acceptAdmin(); + vm.stopPrank(); + } + + function testSetAndAcceptAdminFlow() public { + // Set pending admin by admin + vm.startPrank(admin); + store.setPendingAdmin(newPendingAdmin); + vm.stopPrank(); + + // Accept admin by newPendingAdmin + vm.startPrank(newPendingAdmin); + store.acceptAdmin(); + vm.stopPrank(); + + assertEq(store.admin(), newPendingAdmin, "Admin should be updated to newPendingAdmin"); + assertEq(store.pendingAdmin(), address(0), "Pending admin should be cleared after acceptance"); + } + + // Event Emission Tests + function testInitializeChainEmitsEvent() public { + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit NewWBaseTokenAddress(chainId, l2WBaseToken); + store.initializeChain(chainId, l2WBaseToken); + vm.stopPrank(); + } + + function testReinitializeChainEmitsEvent() public { + vm.startPrank(owner); + store.initializeChain(chainId, l2WBaseToken); + vm.expectEmit(true, true, false, true); + emit NewWBaseTokenAddress(chainId, newL2WBaseToken); + store.reinitializeChain(chainId, newL2WBaseToken); + vm.stopPrank(); + } + + function testSetPendingAdminEmitsEvent() public { + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit NewPendingAdmin(address(0), newPendingAdmin); + store.setPendingAdmin(newPendingAdmin); + vm.stopPrank(); + } + + function testAcceptAdminEmitsEvents() public { + // Set pending admin + vm.startPrank(owner); + store.setPendingAdmin(newAdmin); + vm.stopPrank(); + + // Expect both events when accepting admin + vm.startPrank(newAdmin); + vm.expectEmit(true, true, false, true); + emit NewPendingAdmin(newAdmin, address(0)); + vm.expectEmit(true, true, false, true); + emit NewAdmin(admin, newAdmin); + store.acceptAdmin(); + vm.stopPrank(); + } + + // Edge Case Tests + function testReinitializeChainMultipleTimes() public { + vm.startPrank(owner); + store.initializeChain(chainId, l2WBaseToken); + store.reinitializeChain(chainId, newL2WBaseToken); + store.reinitializeChain(chainId, l2WBaseToken); + address stored = store.l2WBaseTokenAddress(chainId); + assertEq(stored, l2WBaseToken, "Mapping should reflect the last set address"); + vm.stopPrank(); + } + + function testSetPendingAdminTwice() public { + vm.startPrank(owner); + store.setPendingAdmin(newPendingAdmin); + store.setPendingAdmin(admin); + assertEq(store.pendingAdmin(), admin, "Pending admin should be updated to the latest set value"); + vm.stopPrank(); + } + + function testAcceptAdminWhenPendingAdminIsZero() public { + vm.startPrank(other); + vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, other)); + store.acceptAdmin(); + vm.stopPrank(); + } +} diff --git a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/FacetCut.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/FacetCut.t.sol index 2dd88c178..43cec79fd 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/FacetCut.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/FacetCut.t.sol @@ -9,7 +9,7 @@ import {ExecutorFacet} from "contracts/state-transition/chain-deps/facets/Execut import {GettersFacet} from "contracts/state-transition/chain-deps/facets/Getters.sol"; import {MailboxFacet} from "contracts/state-transition/chain-deps/facets/Mailbox.sol"; import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; -import {ReplaceFunctionFacetAddressZero, RemoveFunctionFacetAddressNotZero, FacetExists, SelectorsMustAllHaveSameFreezability, AddressHasNoCode, NonZeroAddress, ZeroAddress} from "contracts/common/L1ContractErrors.sol"; +import {ReplaceFunctionFacetAddressZero, RemoveFunctionFacetAddressNotZero, FacetExists, SelectorsMustAllHaveSameFreezability, AddressHasNoCode, ZeroAddress} from "contracts/common/L1ContractErrors.sol"; contract FacetCutTest is DiamondCutTest { MailboxFacet private mailboxFacet; @@ -32,8 +32,8 @@ contract FacetCutTest is DiamondCutTest { diamondCutTestContract = new DiamondCutTestContract(); mailboxFacet = new MailboxFacet(eraChainId, block.chainid); gettersFacet = new GettersFacet(); - executorFacet1 = new ExecutorFacet(); - executorFacet2 = new ExecutorFacet(); + executorFacet1 = new ExecutorFacet(block.chainid); + executorFacet2 = new ExecutorFacet(block.chainid); } function test_AddingFacetsToFreeSelectors() public { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/Initialization.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/Initialization.t.sol index 94996c5e1..238674049 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/Initialization.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/Initialization.t.sol @@ -6,7 +6,7 @@ import {RevertFallback} from "contracts/dev-contracts/RevertFallback.sol"; import {ReturnSomething} from "contracts/dev-contracts/ReturnSomething.sol"; import {DiamondCutTestContract} from "contracts/dev-contracts/test/DiamondCutTestContract.sol"; import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; -import {DelegateCallFailed, BadReturnData, MalformedCalldata, NonEmptyCalldata} from "contracts/common/L1ContractErrors.sol"; +import {DelegateCallFailed, NonEmptyCalldata} from "contracts/common/L1ContractErrors.sol"; contract InitializationTest is DiamondCutTest { address private revertFallbackAddress; diff --git a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/UpgradeLogic.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/UpgradeLogic.t.sol index 8823f20b9..ed92e27e3 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/UpgradeLogic.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/DiamondCut/UpgradeLogic.t.sol @@ -16,7 +16,8 @@ import {InitializeData} from "contracts/state-transition/chain-deps/DiamondInit. import {DummyChainTypeManager} from "contracts/dev-contracts/test/DummyChainTypeManager.sol"; import {DummyBridgehub} from "contracts/dev-contracts/test/DummyBridgehub.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; -import {DiamondAlreadyFrozen, Unauthorized, DiamondFreezeIncorrectState, DiamondNotFrozen} from "contracts/common/L1ContractErrors.sol"; +import {DiamondAlreadyFrozen, Unauthorized, DiamondNotFrozen} from "contracts/common/L1ContractErrors.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; contract UpgradeLogicTest is DiamondCutTest { DiamondProxy private diamondProxy; @@ -52,7 +53,7 @@ contract UpgradeLogicTest is DiamondCutTest { diamondCutTestContract = new DiamondCutTestContract(); diamondInit = new DiamondInit(); - adminFacet = new AdminFacet(block.chainid); + adminFacet = new AdminFacet(block.chainid, RollupDAManager(address(0))); gettersFacet = new GettersFacet(); Diamond.FacetCut[] memory facetCuts = new Diamond.FacetCut[](2); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Executor/Committing.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Executor/Committing.t.sol index 5c2d5b65a..a97f695b2 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Executor/Committing.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Executor/Committing.t.sol @@ -11,7 +11,9 @@ import {SystemLogKey} from "contracts/state-transition/chain-interfaces/IExecuto import {POINT_EVALUATION_PRECOMPILE_ADDR} from "contracts/common/Config.sol"; import {L2_PUBDATA_CHUNK_PUBLISHER_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {BLS_MODULUS} from "da-contracts/DAUtils.sol"; -import {TimeNotReached, BatchNumberMismatch, PubdataCommitmentsTooBig, InvalidPubdataCommitmentsSize, PubdataCommitmentsEmpty, L2TimestampTooBig, EmptyBlobVersionHash, CanOnlyProcessOneBatch, TimestampError, LogAlreadyProcessed, InvalidLogSender, UnexpectedSystemLog, HashMismatch, BatchHashMismatch, ValueMismatch, MissingSystemLogs, InvalidPubdataLength, NonEmptyBlobVersionHash, BlobHashCommitmentError} from "contracts/common/L1ContractErrors.sol"; +import {BLOB_DATA_OFFSET} from "da-contracts/CalldataDA.sol"; +import {PubdataCommitmentsEmpty, BlobHashCommitmentError, OperatorDAInputLengthTooSmall, EmptyBlobVersionHash, InvalidPubdataCommitmentsSize, NonEmptyBlobVersionHash} from "da-contracts/DAContractsErrors.sol"; +import {TimeNotReached, BatchNumberMismatch, L2TimestampTooBig, CanOnlyProcessOneBatch, TimestampError, LogAlreadyProcessed, InvalidLogSender, UnexpectedSystemLog, HashMismatch, BatchHashMismatch, ValueMismatch, MissingSystemLogs} from "contracts/common/L1ContractErrors.sol"; contract CommittingTest is ExecutorTest { bytes32[] defaultBlobVersionedHashes; @@ -658,7 +660,9 @@ contract CommittingTest is ExecutorTest { vm.prank(validator); - vm.expectRevert("too small"); + vm.expectRevert( + abi.encodeWithSelector(OperatorDAInputLengthTooSmall.selector, operatorDAInput.length, BLOB_DATA_OFFSET) + ); (uint256 commitBatchFrom, uint256 commitBatchTo, bytes memory commitData) = Utils.encodeCommitBatchesData( genesisStoredBatchInfo, correctCommitBatchInfoArray diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Executor/ExecutorProof.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Executor/ExecutorProof.t.sol index 9f4530cc4..b8aeaa2de 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Executor/ExecutorProof.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Executor/ExecutorProof.t.sol @@ -12,6 +12,8 @@ import {IExecutor, LogProcessingOutput} from "contracts/state-transition/chain-i import {TestnetVerifier} from "contracts/state-transition/TestnetVerifier.sol"; contract TestExecutorFacet is ExecutorFacet { + constructor() ExecutorFacet(block.chainid) {} + function createBatchCommitment( CommitBatchInfo calldata _newBatchData, bytes32 _stateDiffHash, @@ -113,13 +115,13 @@ contract ExecutorProofTest is Test { ); assertEq( nextCommitment, - 0x81e46ea22cdb4a0a6cb30b6c02170394703e9bdd101275d542a7c6c23c789898, + 0xc83d94049ae723b98705c52a4fdcd767b7818ccd229aa1738ac71dce0d4ff317, "nextCommitment computation failed" ); bytes32 prevCommitment = 0x6ebf945305689a8c3ac993df7f002d41d311a762cd6bf39bb054ead8d1f54404; uint256 result = executor.getBatchProofPublicInput(prevCommitment, nextCommitment); - assertEq(result, 0x7C854720CBA105B9E34DA6A28770B93AD384C1BF98C497CCBFA4DADB, "getBatchProofPublicInput"); + assertEq(result, 0xbe1803fdbeb40f12f953296979313339ac1d8289731a1e0dd3bcd39b, "getBatchProofPublicInput"); } // add this to be excluded from coverage report diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Executor/_Executor_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Executor/_Executor_Shared.t.sol index f44a93e72..a75c095a6 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Executor/_Executor_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Executor/_Executor_Shared.t.sol @@ -30,6 +30,7 @@ import {RollupL1DAValidator} from "da-contracts/RollupL1DAValidator.sol"; import {IL1AssetRouter} from "contracts/bridge/asset-router/IL1AssetRouter.sol"; import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {DataEncoding} from "contracts/common/libraries/DataEncoding.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; bytes32 constant EMPTY_PREPUBLISHED_COMMITMENT = 0x0000000000000000000000000000000000000000000000000000000000000000; bytes constant POINT_EVALUATION_PRECOMPILE_RESULT = hex"000000000000000000000000000000000000000000000000000000000000100073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"; @@ -162,7 +163,7 @@ contract ExecutorTest is Test { rollupL1DAValidator = new RollupL1DAValidator(); - admin = new AdminFacet(block.chainid); + admin = new AdminFacet(block.chainid, RollupDAManager(address(0))); getters = new GettersFacet(); executor = new TestExecutor(); mailbox = new MailboxFacet(eraChainId, block.chainid); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Governance/AccessControlRestriction.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Governance/AccessControlRestriction.t.sol index 1cd471413..51699797e 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Governance/AccessControlRestriction.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Governance/AccessControlRestriction.t.sol @@ -10,7 +10,7 @@ import {ChainAdmin} from "contracts/governance/ChainAdmin.sol"; import {AccessControlRestriction} from "contracts/governance/AccessControlRestriction.sol"; import {IAccessControlRestriction} from "contracts/governance/IAccessControlRestriction.sol"; import {Utils} from "test/foundry/l1/unit/concrete/Utils/Utils.sol"; -import {NoCallsProvided, AccessToFallbackDenied, AccessToFunctionDenied} from "contracts/common/L1ContractErrors.sol"; +import {ZeroAddress, NoCallsProvided, AccessToFallbackDenied, AccessToFunctionDenied} from "contracts/common/L1ContractErrors.sol"; import {Call} from "contracts/governance/Common.sol"; contract AccessRestrictionTest is Test { @@ -46,6 +46,15 @@ contract AccessRestrictionTest is Test { new AccessControlRestriction(0, address(0)); } + function test_setRequiredRoleForCallZeroTarget(bytes32 role) public { + vm.assume(role != DEFAULT_ADMIN_ROLE); + + vm.startPrank(owner); + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + restriction.setRequiredRoleForCall(address(0), bytes4(0), role); + vm.stopPrank(); + } + function test_setRequiredRoleForCallByNotDefaultAdmin(bytes32 role) public { vm.assume(role != DEFAULT_ADMIN_ROLE); @@ -111,6 +120,15 @@ contract AccessRestrictionTest is Test { restriction.validateCall(call, randomCaller); } + function test_setRequiredRoleForFallbackZeroTarget(bytes32 role) public { + vm.assume(role != DEFAULT_ADMIN_ROLE); + + vm.startPrank(owner); + vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); + restriction.setRequiredRoleForFallback(address(0), role); + vm.stopPrank(); + } + function test_setRequiredRoleForFallbackByNotDefaultAdmin(bytes32 role) public { vm.assume(role != DEFAULT_ADMIN_ROLE); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Governance/ChainAdmin.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Governance/ChainAdmin.t.sol index 27624d503..47e9a7912 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Governance/ChainAdmin.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Governance/ChainAdmin.t.sol @@ -9,13 +9,15 @@ import {IChainAdmin} from "contracts/governance/IChainAdmin.sol"; import {ChainAdmin} from "contracts/governance/ChainAdmin.sol"; import {GettersFacet} from "contracts/state-transition/chain-deps/facets/Getters.sol"; import {Call} from "contracts/governance/Common.sol"; -import {NoCallsProvided, RestrictionWasAlreadyPresent, RestrictionWasNotPresent, AccessToFallbackDenied, AccessToFunctionDenied} from "contracts/common/L1ContractErrors.sol"; +import {DummyRestriction} from "contracts/dev-contracts/DummyRestriction.sol"; +import {NotARestriction, NoCallsProvided, RestrictionWasAlreadyPresent, RestrictionWasNotPresent, AccessToFallbackDenied, AccessToFunctionDenied} from "contracts/common/L1ContractErrors.sol"; import {Utils} from "test/foundry/l1/unit/concrete/Utils/Utils.sol"; contract ChainAdminTest is Test { ChainAdmin internal chainAdmin; AccessControlRestriction internal restriction; GettersFacet internal gettersFacet; + DummyRestriction internal dummyRestriction; address internal owner; uint32 internal major; @@ -33,6 +35,7 @@ contract ChainAdminTest is Test { chainAdmin = new ChainAdmin(restrictions); gettersFacet = new GettersFacet(); + dummyRestriction = new DummyRestriction(true); } function test_getRestrictions() public { @@ -49,18 +52,42 @@ contract ChainAdminTest is Test { address[] memory restrictions = chainAdmin.getRestrictions(); vm.expectEmit(true, false, false, true); - emit IChainAdmin.RestrictionAdded(owner); + emit IChainAdmin.RestrictionAdded(address(dummyRestriction)); vm.prank(address(chainAdmin)); - chainAdmin.addRestriction(owner); + chainAdmin.addRestriction(address(dummyRestriction)); + } + + function test_addRestrictionRevertInvalidRestriction() public { + vm.startPrank(address(chainAdmin)); + vm.expectRevert(); + chainAdmin.addRestriction(makeAddr("emptyRestriction")); + vm.stopPrank(); + } + + function test_addRestrictionRevertInvalidRestrictionMagic() public { + DummyRestriction badRestriction = new DummyRestriction(false); + + vm.startPrank(address(chainAdmin)); + vm.expectRevert(abi.encodeWithSelector(NotARestriction.selector, address(badRestriction))); + chainAdmin.addRestriction(address(badRestriction)); + vm.stopPrank(); + } + + function test_addRestrictionZeroAddress() public { + address[] memory restrictions = chainAdmin.getRestrictions(); + + vm.prank(address(chainAdmin)); + vm.expectRevert(); + chainAdmin.addRestriction(address(0)); } function test_addRestrictionRevert() public { vm.startPrank(address(chainAdmin)); - chainAdmin.addRestriction(owner); + chainAdmin.addRestriction(address(dummyRestriction)); - vm.expectRevert(abi.encodeWithSelector(RestrictionWasAlreadyPresent.selector, owner)); - chainAdmin.addRestriction(owner); + vm.expectRevert(abi.encodeWithSelector(RestrictionWasAlreadyPresent.selector, address(dummyRestriction))); + chainAdmin.addRestriction(address(dummyRestriction)); vm.stopPrank(); } @@ -68,12 +95,12 @@ contract ChainAdminTest is Test { address[] memory restrictions = chainAdmin.getRestrictions(); vm.startPrank(address(chainAdmin)); - chainAdmin.addRestriction(owner); + chainAdmin.addRestriction(address(dummyRestriction)); vm.expectEmit(true, false, false, true); - emit IChainAdmin.RestrictionRemoved(owner); + emit IChainAdmin.RestrictionRemoved(address(dummyRestriction)); - chainAdmin.removeRestriction(owner); + chainAdmin.removeRestriction(address(dummyRestriction)); vm.stopPrank(); } @@ -81,11 +108,11 @@ contract ChainAdminTest is Test { address[] memory restrictions = chainAdmin.getRestrictions(); vm.startPrank(address(chainAdmin)); - chainAdmin.addRestriction(owner); - chainAdmin.removeRestriction(owner); + chainAdmin.addRestriction(address(dummyRestriction)); + chainAdmin.removeRestriction(address(dummyRestriction)); - vm.expectRevert(abi.encodeWithSelector(RestrictionWasNotPresent.selector, owner)); - chainAdmin.removeRestriction(owner); + vm.expectRevert(abi.encodeWithSelector(RestrictionWasNotPresent.selector, dummyRestriction)); + chainAdmin.removeRestriction(address(dummyRestriction)); vm.stopPrank(); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Governance/PermanentRestriction.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Governance/PermanentRestriction.t.sol index bcfe6ae2c..54a576cb7 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Governance/PermanentRestriction.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Governance/PermanentRestriction.t.sol @@ -7,9 +7,9 @@ import {L2TransactionRequestTwoBridgesOuter, BridgehubBurnCTMAssetData} from "co import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; import {ChainTypeManager} from "contracts/state-transition/ChainTypeManager.sol"; import {DiamondInit} from "contracts/state-transition/chain-deps/DiamondInit.sol"; -import {PermanentRestriction, MIN_GAS_FOR_FALLABLE_CALL} from "contracts/governance/PermanentRestriction.sol"; +import {PermanentRestriction} from "contracts/governance/PermanentRestriction.sol"; import {IPermanentRestriction} from "contracts/governance/IPermanentRestriction.sol"; -import {NotAllowed, NotEnoughGas, InvalidAddress, UnsupportedEncodingVersion, InvalidSelector, NotBridgehub, ZeroAddress, ChainZeroAddress, NotAnAdmin, UnallowedImplementation, RemovingPermanentRestriction, CallNotAllowed} from "contracts/common/L1ContractErrors.sol"; +import {NotAllowed, NotEnoughGas, UnsupportedEncodingVersion, InvalidSelector, ZeroAddress, UnallowedImplementation, RemovingPermanentRestriction, CallNotAllowed} from "contracts/common/L1ContractErrors.sol"; import {Call} from "contracts/governance/Common.sol"; import {IZKChain} from "contracts/state-transition/chain-interfaces/IZKChain.sol"; import {VerifierParams, FeeParams, PubdataPricingMode} from "contracts/state-transition/chain-deps/ZKChainStorage.sol"; @@ -26,11 +26,25 @@ import {IL1AssetRouter} from "contracts/bridge/asset-router/IL1AssetRouter.sol"; import {IL1Nullifier} from "contracts/bridge/interfaces/IL1Nullifier.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; import {L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; +import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; +import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; + +contract TestPermanentRestriction is PermanentRestriction { + constructor(IBridgehub _bridgehub, address _l2AdminFactory) PermanentRestriction(_bridgehub, _l2AdminFactory) {} + + function isAdminOfAChain(address _chain) external view returns (bool) { + return _isAdminOfAChain(_chain); + } + + function getNewAdminFromMigration(Call calldata _call) external view returns (address, bool) { + return _getNewAdminFromMigration(_call); + } +} contract PermanentRestrictionTest is ChainTypeManagerTest { ChainAdmin internal chainAdmin; AccessControlRestriction internal restriction; - PermanentRestriction internal permRestriction; + TestPermanentRestriction internal permRestriction; address constant L2_FACTORY_ADDR = address(0); @@ -55,19 +69,19 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { IBridgehub _bridgehub, address _l2AdminFactory, address _owner - ) internal returns (PermanentRestriction proxy, PermanentRestriction impl) { - impl = new PermanentRestriction(_bridgehub, _l2AdminFactory); + ) internal returns (TestPermanentRestriction proxy, TestPermanentRestriction impl) { + impl = new TestPermanentRestriction(_bridgehub, _l2AdminFactory); TransparentUpgradeableProxy tup = new TransparentUpgradeableProxy( address(impl), address(uint160(1)), abi.encodeCall(PermanentRestriction.initialize, (_owner)) ); - proxy = PermanentRestriction(address(tup)); + proxy = TestPermanentRestriction(address(tup)); } function test_ownerAsAddressZero() public { - PermanentRestriction impl = new PermanentRestriction(bridgehub, L2_FACTORY_ADDR); + TestPermanentRestriction impl = new TestPermanentRestriction(bridgehub, L2_FACTORY_ADDR); vm.expectRevert(ZeroAddress.selector); new TransparentUpgradeableProxy( address(impl), @@ -76,12 +90,12 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { ); } - function test_allowAdminImplementation(bytes32 implementationHash) public { + function test_setAllowedAdminImplementation(bytes32 implementationHash) public { vm.expectEmit(true, false, false, true); emit IPermanentRestriction.AdminImplementationAllowed(implementationHash, true); vm.prank(owner); - permRestriction.allowAdminImplementation(implementationHash, true); + permRestriction.setAllowedAdminImplementation(implementationHash, true); } function test_setAllowedData(bytes memory data) public { @@ -92,31 +106,35 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { permRestriction.setAllowedData(data, true); } - function test_setSelectorIsValidated(bytes4 selector) public { + function test_setSelectorShouldBeValidated(bytes4 selector) public { vm.expectEmit(true, false, false, true); emit IPermanentRestriction.SelectorValidationChanged(selector, true); vm.prank(owner); - permRestriction.setSelectorIsValidated(selector, true); + permRestriction.setSelectorShouldBeValidated(selector, true); } - function test_tryCompareAdminOfAChainIsAddressZero() public { - vm.expectRevert(ChainZeroAddress.selector); - permRestriction.tryCompareAdminOfAChain(address(0), owner); + function isAddressAdmin(address chainAddr, address _potentialAdmin) internal returns (bool) { + // The permanent restriction compares it only against the msg.sender, + // so we have to use `prank` to test the function + vm.prank(_potentialAdmin); + return permRestriction.isAdminOfAChain(chainAddr); } - function test_tryCompareAdminOfAChainNotAHyperchain() public { - vm.expectRevert(); - permRestriction.tryCompareAdminOfAChain(makeAddr("random"), owner); + function test_isAdminOfAChainIsAddressZero() public { + assertFalse(permRestriction.isAdminOfAChain(address(0))); } - function test_tryCompareAdminOfAChainNotAnAdmin() public { - vm.expectRevert(abi.encodeWithSelector(NotAnAdmin.selector, IZKChain(hyperchain).getAdmin(), owner)); - permRestriction.tryCompareAdminOfAChain(hyperchain, owner); + function test_isAdminOfAChainNotAHyperchain() public { + assertFalse(permRestriction.isAdminOfAChain(makeAddr("random"))); + } + + function test_isAdminOfAChainOfAChainNotAnAdmin() public { + assertFalse(permRestriction.isAdminOfAChain(hyperchain)); } function test_tryCompareAdminOfAChain() public { - permRestriction.tryCompareAdminOfAChain(hyperchain, newChainAdmin); + assertTrue(isAddressAdmin(hyperchain, newChainAdmin)); } function test_validateCallTooShortData() public { @@ -143,7 +161,7 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { function test_validateCallSetPendingAdminRemovingPermanentRestriction() public { vm.prank(owner); - permRestriction.allowAdminImplementation(address(chainAdmin).codehash, true); + permRestriction.setAllowedAdminImplementation(address(chainAdmin).codehash, true); Call memory call = Call({ target: hyperchain, @@ -160,7 +178,7 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { function test_validateCallSetPendingAdmin() public { vm.prank(owner); - permRestriction.allowAdminImplementation(address(chainAdmin).codehash, true); + permRestriction.setAllowedAdminImplementation(address(chainAdmin).codehash, true); vm.prank(address(chainAdmin)); chainAdmin.addRestriction(address(permRestriction)); @@ -190,7 +208,7 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { function test_validateCallCallNotAllowed() public { vm.prank(owner); - permRestriction.setSelectorIsValidated(IAdmin.acceptAdmin.selector, true); + permRestriction.setSelectorShouldBeValidated(IAdmin.acceptAdmin.selector, true); Call memory call = Call({ target: hyperchain, value: 0, @@ -206,7 +224,7 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { function test_validateCall() public { vm.prank(owner); - permRestriction.setSelectorIsValidated(IAdmin.acceptAdmin.selector, true); + permRestriction.setSelectorShouldBeValidated(IAdmin.acceptAdmin.selector, true); Call memory call = Call({ target: hyperchain, value: 0, @@ -275,47 +293,49 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { call.data = abi.encodeCall(Bridgehub.requestL2TransactionTwoBridges, (outer)); } + function assertInvalidMigrationCall(Call memory call) public { + (address newAdmin, bool migration) = permRestriction.getNewAdminFromMigration(call); + assertFalse(migration); + assertEq(newAdmin, address(0)); + } + function test_tryGetNewAdminFromMigrationRevertWhenInvalidSelector() public { Call memory call = _encodeMigraationCall(false, true, true, true, true, address(0)); - vm.expectRevert(abi.encodeWithSelector(NotBridgehub.selector, address(0))); - permRestriction.tryGetNewAdminFromMigration(call); + assertInvalidMigrationCall(call); } function test_tryGetNewAdminFromMigrationRevertWhenNotBridgehub() public { Call memory call = _encodeMigraationCall(true, false, true, true, true, address(0)); - vm.expectRevert(abi.encodeWithSelector(InvalidSelector.selector, bytes4(0))); - permRestriction.tryGetNewAdminFromMigration(call); + assertInvalidMigrationCall(call); } function test_tryGetNewAdminFromMigrationRevertWhenNotSharedBridge() public { Call memory call = _encodeMigraationCall(true, true, false, true, true, address(0)); - vm.expectRevert(abi.encodeWithSelector(InvalidAddress.selector, address(sharedBridge), address(0))); - permRestriction.tryGetNewAdminFromMigration(call); + assertInvalidMigrationCall(call); } function test_tryGetNewAdminFromMigrationRevertWhenIncorrectEncoding() public { Call memory call = _encodeMigraationCall(true, true, true, false, true, address(0)); - vm.expectRevert(abi.encodeWithSelector(UnsupportedEncodingVersion.selector)); - permRestriction.tryGetNewAdminFromMigration(call); + assertInvalidMigrationCall(call); } function test_tryGetNewAdminFromMigrationRevertWhenIncorrectAssetId() public { Call memory call = _encodeMigraationCall(true, true, true, true, false, address(0)); - vm.expectRevert(abi.encodeWithSelector(ZeroAddress.selector)); - permRestriction.tryGetNewAdminFromMigration(call); + assertInvalidMigrationCall(call); } function test_tryGetNewAdminFromMigrationShouldWorkCorrectly() public { address l2Addr = makeAddr("l2Addr"); Call memory call = _encodeMigraationCall(true, true, true, true, true, l2Addr); - address result = permRestriction.tryGetNewAdminFromMigration(call); - assertEq(result, l2Addr); + (address newAdmin, bool migration) = permRestriction.getNewAdminFromMigration(call); + assertTrue(migration); + assertEq(newAdmin, l2Addr); } function test_validateMigrationToL2RevertNotAllowed() public { @@ -343,14 +363,6 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { permRestriction.validateCall(call, owner); } - function test_validateNotEnoughGas() public { - address l2Addr = makeAddr("l2Addr"); - Call memory call = _encodeMigraationCall(true, true, true, true, true, l2Addr); - - vm.expectRevert(abi.encodeWithSelector(NotEnoughGas.selector)); - permRestriction.validateCall{gas: MIN_GAS_FOR_FALLABLE_CALL}(call, address(0)); - } - function createNewChainBridgehub() internal { bytes[] memory factoryDeps = new bytes[](0); vm.stopPrank(); @@ -362,7 +374,7 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { // ctm deployer address is 0 in this test vm.startPrank(address(0)); - bridgehub.setAssetHandlerAddress( + bridgehub.setCTMAssetAddress( bytes32(uint256(uint160(address(chainContractAddress)))), address(chainContractAddress) ); @@ -374,6 +386,19 @@ contract PermanentRestrictionTest is ChainTypeManagerTest { abi.encodeWithSelector(IL1AssetRouter.L1_NULLIFIER.selector), abi.encode(l1Nullifier) ); + vm.mockCall( + address(sharedBridge), + abi.encodeWithSelector(IAssetRouterBase.assetHandlerAddress.selector), + abi.encode(bridgehub) + ); + vm.mockCall( + address(bridgehub), + abi.encodeWithSelector(Bridgehub.baseToken.selector, chainId), + abi.encode(baseToken) + ); + vm.mockCall(address(baseToken), abi.encodeWithSelector(IERC20Metadata.name.selector), abi.encode("TestToken")); + vm.mockCall(address(baseToken), abi.encodeWithSelector(IERC20Metadata.symbol.selector), abi.encode("TT")); + vm.startPrank(governor); bridgehub.createNewChain({ _chainId: chainId, diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Governance/_Governance_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Governance/_Governance_Shared.t.sol index 2a34bc2ff..1c081cd8d 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Governance/_Governance_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Governance/_Governance_Shared.t.sol @@ -10,6 +10,7 @@ import {Call} from "contracts/governance/Common.sol"; import {EventOnFallback} from "contracts/dev-contracts/EventOnFallback.sol"; import {Forwarder} from "contracts/dev-contracts/Forwarder.sol"; import {RevertFallback} from "contracts/dev-contracts/RevertFallback.sol"; +import {EventOnFallbackTargetExpected} from "../../../../L1TestsErrors.sol"; contract GovernanceTest is Test, EventOnFallback { address internal owner; @@ -47,7 +48,9 @@ contract GovernanceTest is Test, EventOnFallback { function _checkEventBeforeExecution(IGovernance.Operation memory op) private { for (uint256 i = 0; i < op.calls.length; i++) { - require(op.calls[i].target == address(eventOnFallback), "EventOnFallback target expected"); + if (op.calls[i].target != address(eventOnFallback)) { + revert EventOnFallbackTargetExpected(); + } // Check event vm.expectEmit(false, false, false, true); emit Called(address(governance), op.calls[i].value, op.calls[i].data); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.sol b/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.sol index 3347e19ef..6af724ace 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.sol @@ -19,6 +19,7 @@ import {IExecutor, SystemLogKey} from "contracts/state-transition/chain-interfac import {L2CanonicalTransaction} from "contracts/common/Messaging.sol"; import {DummyBridgehub} from "contracts/dev-contracts/test/DummyBridgehub.sol"; import {PriorityOpsBatchInfo} from "contracts/state-transition/libraries/PriorityTree.sol"; +import {InvalidBlobCommitmentsLength, InvalidBlobHashesLength} from "test/foundry/L1TestsErrors.sol"; bytes32 constant DEFAULT_L2_LOGS_TREE_ROOT_HASH = 0x0000000000000000000000000000000000000000000000000000000000000000; address constant L2_SYSTEM_CONTEXT_ADDRESS = 0x000000000000000000000000000000000000800B; @@ -74,24 +75,23 @@ library Utils { bytes32("") ); logs[2] = constructL2Log( - true, - L2_SYSTEM_CONTEXT_ADDRESS, - uint256(SystemLogKey.PREV_BATCH_HASH_KEY), - bytes32("") - ); - logs[3] = constructL2Log( true, L2_BOOTLOADER_ADDRESS, uint256(SystemLogKey.CHAINED_PRIORITY_TXN_HASH_KEY), keccak256("") ); - logs[4] = constructL2Log( + logs[3] = constructL2Log( true, L2_BOOTLOADER_ADDRESS, uint256(SystemLogKey.NUMBER_OF_LAYER_1_TXS_KEY), bytes32("") ); - + logs[4] = constructL2Log( + true, + L2_SYSTEM_CONTEXT_ADDRESS, + uint256(SystemLogKey.PREV_BATCH_HASH_KEY), + bytes32("") + ); logs[5] = constructL2Log( true, L2_TO_L1_MESSENGER, @@ -515,8 +515,12 @@ library Utils { ) internal pure returns (bytes32[] memory blobAuxOutputWords) { // These invariants should be checked by the caller of this function, but we double check // just in case. - require(_blobCommitments.length == TOTAL_BLOBS_IN_COMMITMENT, "b10"); - require(_blobHashes.length == TOTAL_BLOBS_IN_COMMITMENT, "b11"); + if (_blobCommitments.length != TOTAL_BLOBS_IN_COMMITMENT) { + revert InvalidBlobCommitmentsLength(); + } + if (_blobHashes.length != TOTAL_BLOBS_IN_COMMITMENT) { + revert InvalidBlobHashesLength(); + } // for each blob we have: // linear hash (hash of preimage from system logs) and diff --git a/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.t.sol index 0c9ad684f..919c14a60 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/Utils/Utils.t.sol @@ -73,9 +73,9 @@ contract UtilsTest is Test { logs[2], Utils.constructL2Log( true, - L2_SYSTEM_CONTEXT_ADDRESS, - uint256(SystemLogKey.PREV_BATCH_HASH_KEY), - bytes32("") + L2_BOOTLOADER_ADDRESS, + uint256(SystemLogKey.CHAINED_PRIORITY_TXN_HASH_KEY), + keccak256("") ), "log[2] should be correct" ); @@ -85,8 +85,8 @@ contract UtilsTest is Test { Utils.constructL2Log( true, L2_BOOTLOADER_ADDRESS, - uint256(SystemLogKey.CHAINED_PRIORITY_TXN_HASH_KEY), - keccak256("") + uint256(SystemLogKey.NUMBER_OF_LAYER_1_TXS_KEY), + bytes32("") ), "log[3] should be correct" ); @@ -95,8 +95,8 @@ contract UtilsTest is Test { logs[4], Utils.constructL2Log( true, - L2_BOOTLOADER_ADDRESS, - uint256(SystemLogKey.NUMBER_OF_LAYER_1_TXS_KEY), + L2_SYSTEM_CONTEXT_ADDRESS, + uint256(SystemLogKey.PREV_BATCH_HASH_KEY), bytes32("") ), "log[4] should be correct" diff --git a/l1-contracts/test/foundry/l1/unit/concrete/ValidatorTimelock/ValidatorTimelock.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/ValidatorTimelock/ValidatorTimelock.t.sol index 3725f54e2..67c769ca2 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/ValidatorTimelock/ValidatorTimelock.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/ValidatorTimelock/ValidatorTimelock.t.sol @@ -46,7 +46,7 @@ contract ValidatorTimelockTest is Test { executionDelay = 10; chainTypeManager = new DummyChainTypeManagerForValidatorTimelock(owner, zkSync); - validator = new ValidatorTimelock(owner, executionDelay, eraChainId); + validator = new ValidatorTimelock(owner, executionDelay); vm.prank(owner); validator.setChainTypeManager(IChainTypeManager(address(chainTypeManager))); vm.prank(owner); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateAllLeaves.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateAllLeaves.t.sol index 5bb127685..5b030f634 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateAllLeaves.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateAllLeaves.t.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.24; import {FullMerkleTest} from "./_FullMerkle_Shared.t.sol"; +import {MerkleWrongLength} from "contracts/common/L1ContractErrors.sol"; contract UpdateAllLeavesTest is FullMerkleTest { function test_revertWhen_wrongLength() public { @@ -18,7 +19,7 @@ contract UpdateAllLeavesTest is FullMerkleTest { newLeaves[2] = keccak256("New Leaf 2"); // Updating all leaves with wrong length - vm.expectRevert(bytes("FMT, wrong length")); + vm.expectRevert(abi.encodeWithSelector(MerkleWrongLength.selector, newLeaves.length, 2)); merkleTest.updateAllLeaves(newLeaves); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateLeaf.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateLeaf.t.sol index ae29641b8..6aee94198 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateLeaf.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/FullMerkle/UpdateLeaf.t.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.24; import {FullMerkleTest} from "./_FullMerkle_Shared.t.sol"; +import {MerkleWrongIndex} from "contracts/common/L1ContractErrors.sol"; contract UpdateLeafTest is FullMerkleTest { function test_revertWhen_wrongIndex() public { @@ -15,7 +16,7 @@ contract UpdateLeafTest is FullMerkleTest { bytes32 newLeaf1 = keccak256("New Leaf 1"); // Updating leaf 1 with wrong index - vm.expectRevert(bytes("FMT, wrong index")); + vm.expectRevert(abi.encodeWithSelector(MerkleWrongIndex.selector, 2, 1)); merkleTest.updateLeaf(2, newLeaf1); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/Merkle/Merkle.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/Merkle/Merkle.t.sol index 88e8c8efa..838608eb9 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/Merkle/Merkle.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/common/libraries/Merkle/Merkle.t.sol @@ -4,7 +4,7 @@ pragma solidity 0.8.24; import {Test} from "forge-std/Test.sol"; import {MerkleTest} from "contracts/dev-contracts/test/MerkleTest.sol"; import {MerkleTreeNoSort} from "./MerkleTreeNoSort.sol"; -import {MerklePathEmpty, MerkleIndexOutOfBounds, MerklePathOutOfBounds} from "contracts/common/L1ContractErrors.sol"; +import {MerklePathEmpty, MerkleIndexOutOfBounds, MerklePathOutOfBounds, MerklePathLengthMismatch, MerkleIndexOrHeightMismatch, MerkleNothingToProve} from "contracts/common/L1ContractErrors.sol"; contract MerkleTestTest is Test { MerkleTreeNoSort merkleTree; @@ -97,7 +97,7 @@ contract MerkleTestTest is Test { (, bytes32[] memory right, bytes32[] memory leaves) = prepareRangeProof(10, 13); bytes32[] memory leftShortened = new bytes32[](right.length - 1); - vm.expectRevert(bytes("Merkle: path length mismatch")); + vm.expectRevert(abi.encodeWithSelector(MerklePathLengthMismatch.selector, 6, 7)); merkleTest.calculateRoot(leftShortened, right, 10, leaves); } @@ -112,7 +112,7 @@ contract MerkleTestTest is Test { function testRangeProofWrongIndex_shouldRevert() public { (bytes32[] memory left, bytes32[] memory right, bytes32[] memory leaves) = prepareRangeProof(10, 13); - vm.expectRevert(bytes("Merkle: index/height mismatch")); + vm.expectRevert(MerkleIndexOrHeightMismatch.selector); merkleTest.calculateRoot(left, right, 128, leaves); } @@ -126,7 +126,7 @@ contract MerkleTestTest is Test { bytes32[] memory left = merkleTree.getProof(elements, 10); bytes32[] memory right = merkleTree.getProof(elements, 10); bytes32[] memory leaves; - vm.expectRevert(bytes("Merkle: nothing to prove")); + vm.expectRevert(MerkleNothingToProve.selector); merkleTest.calculateRoot(left, right, 10, leaves); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/BytecodesSupplier.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/BytecodesSupplier.t.sol new file mode 100644 index 000000000..5c6268d83 --- /dev/null +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/BytecodesSupplier.t.sol @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +import "forge-std/Test.sol"; +import "contracts/upgrades/BytecodesSupplier.sol"; +import "contracts/common/libraries/L2ContractHelper.sol"; +import "contracts/common/L1ContractErrors.sol"; + +contract BytecodesSupplierTest is Test { + BytecodesSupplier bytecodesSupplier; + bytes internal bytecode1 = hex"0000000000000000000000000000000000000000000000000000000000000000"; + bytes internal bytecode2 = hex"1111111111111111111111111111111111111111111111111111111111111111"; + + // Declare the event to use with vm.expectEmit + event BytecodePublished(bytes32 indexed bytecodeHash, bytes bytecode); + + function setUp() public { + bytecodesSupplier = new BytecodesSupplier(); + } + + function testPublishNewBytecode() public { + bytes memory bytecode = bytecode1; + + // Calculate the bytecode hash using the same function as the contract + bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(bytecode); + + // Expect the event to be emitted + vm.expectEmit(true, false, false, true); + emit BytecodePublished(bytecodeHash, bytecode); + + // Publish the bytecode + bytecodesSupplier.publishBytecode(bytecode); + + // Check that the publishingBlock mapping is updated + uint256 publishedBlock = bytecodesSupplier.publishingBlock(bytecodeHash); + assertEq(publishedBlock, block.number); + } + + function testPublishBytecodeAlreadyPublished() public { + bytes memory bytecode = bytecode1; + + // Calculate the bytecode hash + bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(bytecode); + + // Publish the bytecode + bytecodesSupplier.publishBytecode(bytecode); + + // Try to publish the same bytecode again, expect revert + vm.expectRevert(abi.encodeWithSelector(BytecodeAlreadyPublished.selector, bytecodeHash)); + bytecodesSupplier.publishBytecode(bytecode); + } + + function testPublishMultipleBytecodes() public { + bytes[] memory bytecodes = new bytes[](2); + bytecodes[0] = bytecode1; + bytecodes[1] = bytecode2; + + // Expect events for each bytecode published + for (uint256 i = 0; i < bytecodes.length; ++i) { + bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(bytecodes[i]); + vm.expectEmit(true, false, false, true); + emit BytecodePublished(bytecodeHash, bytecodes[i]); + } + + // Publish multiple bytecodes + bytecodesSupplier.publishBytecodes(bytecodes); + + // Check that both bytecodes are published + for (uint256 i = 0; i < bytecodes.length; ++i) { + bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(bytecodes[i]); + uint256 publishedBlock = bytecodesSupplier.publishingBlock(bytecodeHash); + assertEq(publishedBlock, block.number); + } + } + + function testPublishMultipleBytecodesWithDuplicate() public { + bytes[] memory bytecodes = new bytes[](2); + bytecodes[0] = bytecode1; + bytecodes[1] = bytecode2; + + // Publish the first bytecode + bytecodesSupplier.publishBytecode(bytecodes[0]); + + // Calculate the bytecode hash of the first bytecode + bytes32 bytecodeHash = L2ContractHelper.hashL2Bytecode(bytecodes[0]); + + // Now try to publish both bytecodes, one of which is already published + vm.expectRevert(abi.encodeWithSelector(BytecodeAlreadyPublished.selector, bytecodeHash)); + bytecodesSupplier.publishBytecodes(bytecodes); + } +} diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/FreezeChain.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/FreezeChain.t.sol index 73a2dc498..838d7a77f 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/FreezeChain.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/FreezeChain.t.sol @@ -4,7 +4,6 @@ pragma solidity 0.8.24; import {ChainTypeManagerTest} from "./_ChainTypeManager_Shared.t.sol"; import {GettersFacet} from "contracts/state-transition/chain-deps/facets/Getters.sol"; import {IAdmin} from "contracts/state-transition/chain-interfaces/IAdmin.sol"; -import {FacetIsFrozen} from "contracts/common/L1ContractErrors.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; contract freezeChainTest is ChainTypeManagerTest { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/SetValidatorTimelock.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/SetValidatorTimelock.t.sol index cbe0f1c6d..ddf137384 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/SetValidatorTimelock.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/SetValidatorTimelock.t.sol @@ -39,7 +39,7 @@ contract setValidatorTimelockTest is ChainTypeManagerTest { ); vm.prank(notOwner); - vm.expectRevert(abi.encodeWithSelector(Unauthorized.selector, notOwner)); + vm.expectRevert("Ownable: caller is not the owner"); address newValidatorTimelock = address(0x0000000000000000000000000000000000004235); chainContractAddress.setValidatorTimelock(newValidatorTimelock); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/_ChainTypeManager_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/_ChainTypeManager_Shared.t.sol index 5ecaa7407..139d7d2d3 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/_ChainTypeManager_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/ChainTypeManager/_ChainTypeManager_Shared.t.sol @@ -31,6 +31,8 @@ import {ICTMDeploymentTracker} from "contracts/bridgehub/ICTMDeploymentTracker.s import {IMessageRoot} from "contracts/bridgehub/IMessageRoot.sol"; import {L1AssetRouter} from "contracts/bridge/asset-router/L1AssetRouter.sol"; import {RollupL1DAValidator} from "da-contracts/RollupL1DAValidator.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; +import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; contract ChainTypeManagerTest is Test { ChainTypeManager internal chainTypeManager; @@ -81,7 +83,7 @@ contract ChainTypeManagerTest is Test { ); facetCuts.push( Diamond.FacetCut({ - facet: address(new AdminFacet(block.chainid)), + facet: address(new AdminFacet(block.chainid, RollupDAManager(address(0)))), action: Diamond.Action.Add, isFreezable: true, selectors: Utils.getAdminSelectors() @@ -89,7 +91,7 @@ contract ChainTypeManagerTest is Test { ); facetCuts.push( Diamond.FacetCut({ - facet: address(new ExecutorFacet()), + facet: address(new ExecutorFacet(block.chainid)), action: Diamond.Action.Add, isFreezable: true, selectors: Utils.getExecutorSelectors() @@ -175,6 +177,14 @@ contract ChainTypeManagerTest is Test { abi.encode(l1Nullifier) ); + vm.mockCall( + address(bridgehub), + abi.encodeWithSelector(Bridgehub.baseToken.selector, chainId), + abi.encode(baseToken) + ); + vm.mockCall(address(baseToken), abi.encodeWithSelector(IERC20Metadata.name.selector), abi.encode("TestToken")); + vm.mockCall(address(baseToken), abi.encodeWithSelector(IERC20Metadata.symbol.selector), abi.encode("TT")); + return chainContractAddress.createNewChain({ _chainId: chainId, diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondInit/Initialize.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondInit/Initialize.t.sol index 0b7dfbbe9..e31d841b9 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondInit/Initialize.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondInit/Initialize.t.sol @@ -11,7 +11,7 @@ import {DiamondProxy} from "contracts/state-transition/chain-deps/DiamondProxy.s import {InitializeData} from "contracts/state-transition/chain-interfaces/IDiamondInit.sol"; import {IVerifier} from "contracts/state-transition/chain-interfaces/IVerifier.sol"; import {MAX_GAS_PER_TRANSACTION} from "contracts/common/Config.sol"; -import {MalformedCalldata, ZeroAddress, TooMuchGas} from "contracts/common/L1ContractErrors.sol"; +import {ZeroAddress, TooMuchGas} from "contracts/common/L1ContractErrors.sol"; contract InitializeTest is DiamondInitTest { function test_revertWhen_verifierIsZeroAddress() public { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondProxy/DiamondProxy.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondProxy/DiamondProxy.t.sol index d58d81ae5..7c994ec1a 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondProxy/DiamondProxy.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/DiamondProxy/DiamondProxy.t.sol @@ -12,7 +12,7 @@ import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; import {DiamondProxy} from "contracts/state-transition/chain-deps/DiamondProxy.sol"; import {ZKChainBase} from "contracts/state-transition/chain-deps/facets/ZKChainBase.sol"; import {TestnetVerifier} from "contracts/state-transition/TestnetVerifier.sol"; -import {FacetIsFrozen, ValueMismatch, InvalidSelector} from "contracts/common/L1ContractErrors.sol"; +import {ValueMismatch, InvalidSelector} from "contracts/common/L1ContractErrors.sol"; contract TestFacet is ZKChainBase { function func() public pure returns (bool) { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ChangeFeeParams.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ChangeFeeParams.t.sol index 5a1f4cbb0..e12e857c1 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ChangeFeeParams.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ChangeFeeParams.t.sol @@ -6,6 +6,7 @@ import {AdminTest} from "./_Admin_Shared.t.sol"; import {FeeParams, PubdataPricingMode} from "contracts/state-transition/chain-deps/ZKChainStorage.sol"; import {Unauthorized, PriorityTxPubdataExceedsMaxPubDataPerBatch} from "contracts/common/L1ContractErrors.sol"; +import {FeeParamsWereNotChangedCorrectly} from "../../../../../../../L1TestsErrors.sol"; contract ChangeFeeParamsTest is AdminTest { event NewFeeParams(FeeParams oldFeeParams, FeeParams newFeeParams); @@ -82,6 +83,8 @@ contract ChangeFeeParamsTest is AdminTest { bytes32 newFeeParamsHash = keccak256(abi.encode(newFeeParams)); bytes32 currentFeeParamsHash = keccak256(abi.encode(utilsFacet.util_getFeeParams())); - require(currentFeeParamsHash == newFeeParamsHash, "Fee params were not changed correctly"); + if (currentFeeParamsHash != newFeeParamsHash) { + revert FeeParamsWereNotChangedCorrectly(); + } } } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ExecuteUpgrade.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ExecuteUpgrade.t.sol index de559f27b..19724c16b 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ExecuteUpgrade.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/ExecuteUpgrade.t.sol @@ -42,7 +42,6 @@ contract ExecuteUpgradeTest is AdminTest { ProposedUpgrade memory proposedUpgrade = ProposedUpgrade({ l2ProtocolUpgradeTx: Utils.makeEmptyL2CanonicalTransaction(), - factoryDeps: new bytes[](0), bootloaderHash: bytes32(0), defaultAccountHash: bytes32(0), verifier: address(0), diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/UnfreezeDiamond.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/UnfreezeDiamond.t.sol index 88af27533..a2c1debf4 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/UnfreezeDiamond.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/UnfreezeDiamond.t.sol @@ -3,7 +3,7 @@ pragma solidity 0.8.24; import {AdminTest} from "./_Admin_Shared.t.sol"; -import {Unauthorized, DiamondFreezeIncorrectState, DiamondNotFrozen} from "contracts/common/L1ContractErrors.sol"; +import {Unauthorized, DiamondNotFrozen} from "contracts/common/L1ContractErrors.sol"; contract UnfreezeDiamondTest is AdminTest { event Unfreeze(); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/_Admin_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/_Admin_Shared.t.sol index 7c45f8e8b..2903ba0f1 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/_Admin_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Admin/_Admin_Shared.t.sol @@ -10,6 +10,7 @@ import {AdminFacet} from "contracts/state-transition/chain-deps/facets/Admin.sol import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; import {IAdmin} from "contracts/state-transition/chain-interfaces/IAdmin.sol"; import {TestnetVerifier} from "contracts/state-transition/TestnetVerifier.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; contract AdminTest is Test { IAdmin internal adminFacet; @@ -36,7 +37,7 @@ contract AdminTest is Test { function setUp() public virtual { Diamond.FacetCut[] memory facetCuts = new Diamond.FacetCut[](2); facetCuts[0] = Diamond.FacetCut({ - facet: address(new AdminFacet(block.chainid)), + facet: address(new AdminFacet(block.chainid, RollupDAManager(address(0)))), action: Diamond.Action.Add, isFreezable: true, selectors: getAdminSelectors() diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Base/_Base_Shared.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Base/_Base_Shared.t.sol index be93c91df..6894fb1ba 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Base/_Base_Shared.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/chain-deps/facets/Base/_Base_Shared.t.sol @@ -21,8 +21,6 @@ contract TestBaseFacet is ZKChainBase { function functionWithOnlyAdminOrChainTypeManagerModifier() external onlyAdminOrChainTypeManager {} - function functionWithonlyValidatorOrChainTypeManagerModifier() external onlyValidatorOrChainTypeManager {} - // add this to be excluded from coverage report function test() internal virtual {} } @@ -46,7 +44,6 @@ contract ZKChainBaseTest is Test { selectors[2] = TestBaseFacet.functionWithOnlyChainTypeManagerModifier.selector; selectors[3] = TestBaseFacet.functionWithOnlyBridgehubModifier.selector; selectors[4] = TestBaseFacet.functionWithOnlyAdminOrChainTypeManagerModifier.selector; - selectors[5] = TestBaseFacet.functionWithonlyValidatorOrChainTypeManagerModifier.selector; } function setUp() public virtual { diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/CalldataDA.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/CalldataDA.t.sol index 24657a499..7838ba693 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/CalldataDA.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/CalldataDA.t.sol @@ -5,7 +5,8 @@ pragma solidity 0.8.24; import {Test} from "forge-std/Test.sol"; import {Utils} from "../../Utils/Utils.sol"; import {TestCalldataDA} from "contracts/dev-contracts/test/TestCalldataDA.sol"; -import {BLOB_SIZE_BYTES} from "contracts/state-transition/data-availability/CalldataDA.sol"; +import {BLOB_SIZE_BYTES, BLOB_DATA_OFFSET, BLOB_COMMITMENT_SIZE} from "contracts/state-transition/data-availability/CalldataDA.sol"; +import {OperatorDAInputTooSmall, InvalidNumberOfBlobs, InvalidBlobsHashes, InvalidL2DAOutputHash, OnlyOneBlobWithCalldata, PubdataTooSmall, PubdataTooLong, InvalidPubdataHash} from "contracts/state-transition/L1StateTransitionErrors.sol"; contract CalldataDATest is Test { TestCalldataDA calldataDA; @@ -23,7 +24,9 @@ contract CalldataDATest is Test { uint256 maxBlobsSupported = 1; bytes memory operatorDAInput = hex""; - vm.expectRevert("too small"); + vm.expectRevert( + abi.encodeWithSelector(OperatorDAInputTooSmall.selector, operatorDAInput.length, BLOB_DATA_OFFSET) + ); calldataDA.processL2RollupDAValidatorOutputHash(l2DAValidatorOutputHash, maxBlobsSupported, operatorDAInput); } @@ -37,7 +40,13 @@ contract CalldataDATest is Test { bytes memory operatorDAInput = abi.encodePacked(stateDiffHash, fullPubdataHash, blobsProvided); - vm.expectRevert("invalid number of blobs"); + vm.expectRevert( + abi.encodeWithSelector( + InvalidNumberOfBlobs.selector, + uint256(uint8(operatorDAInput[64])), + maxBlobsSupported + ) + ); calldataDA.processL2RollupDAValidatorOutputHash(l2DAValidatorOutputHash, maxBlobsSupported, operatorDAInput); } @@ -51,7 +60,13 @@ contract CalldataDATest is Test { bytes memory operatorDAInput = abi.encodePacked(stateDiffHash, fullPubdataHash, blobsProvided); - vm.expectRevert("invalid blobs hashes"); + vm.expectRevert( + abi.encodeWithSelector( + InvalidBlobsHashes.selector, + operatorDAInput.length, + BLOB_DATA_OFFSET + 32 * uint256(uint8(operatorDAInput[64])) + ) + ); calldataDA.processL2RollupDAValidatorOutputHash(l2DAValidatorOutputHash, maxBlobsSupported, operatorDAInput); } @@ -66,7 +81,7 @@ contract CalldataDATest is Test { bytes memory operatorDAInput = abi.encodePacked(stateDiffHash, fullPubdataHash, blobsProvided, blobLinearHash); - vm.expectRevert("invalid l2 DA output hash"); + vm.expectRevert(abi.encodeWithSelector(InvalidL2DAOutputHash.selector, l2DAValidatorOutputHash)); calldataDA.processL2RollupDAValidatorOutputHash(l2DAValidatorOutputHash, maxBlobsSupported, operatorDAInput); } @@ -108,7 +123,7 @@ contract CalldataDATest is Test { uint256 maxBlobsSupported = 6; bytes memory pubdataInput = ""; - vm.expectRevert("only one blob with calldata"); + vm.expectRevert(OnlyOneBlobWithCalldata.selector); calldataDA.processCalldataDA(blobsProvided, fullPubdataHash, maxBlobsSupported, pubdataInput); } @@ -118,7 +133,7 @@ contract CalldataDATest is Test { bytes calldata pubdataInput = makeBytesArrayOfLength(BLOB_SIZE_BYTES + 33); bytes32 fullPubdataHash = keccak256(pubdataInput); - vm.expectRevert(bytes("cz")); + vm.expectRevert(abi.encodeWithSelector(PubdataTooLong.selector, 126977, blobsProvided * BLOB_SIZE_BYTES)); calldataDA.processCalldataDA(blobsProvided, fullPubdataHash, maxBlobsSupported, pubdataInput); } @@ -128,7 +143,7 @@ contract CalldataDATest is Test { bytes calldata pubdataInput = makeBytesArrayOfLength(31); bytes32 fullPubdataHash = keccak256(pubdataInput); - vm.expectRevert(bytes("pubdata too small")); + vm.expectRevert(abi.encodeWithSelector(PubdataTooSmall.selector, pubdataInput.length, BLOB_COMMITMENT_SIZE)); calldataDA.processCalldataDA(blobsProvided, fullPubdataHash, maxBlobsSupported, pubdataInput); } @@ -140,7 +155,7 @@ contract CalldataDATest is Test { bytes memory pubdataInput = abi.encodePacked(pubdataInputWithoutBlobCommitment, blobCommitment); bytes32 fullPubdataHash = keccak256(pubdataInput); - vm.expectRevert(bytes("wp")); + vm.expectRevert(InvalidPubdataHash.selector); calldataDA.processCalldataDA(blobsProvided, fullPubdataHash, maxBlobsSupported, pubdataInput); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RelayedSLDAValidator.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RelayedSLDAValidator.t.sol index 9d896cf08..de566b0df 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RelayedSLDAValidator.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RelayedSLDAValidator.t.sol @@ -10,6 +10,8 @@ import {L2_TO_L1_MESSENGER_SYSTEM_CONTRACT_ADDR} from "contracts/common/L2Contra import {IL1Messenger} from "contracts/common/interfaces/IL1Messenger.sol"; import {L2_BRIDGEHUB_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; +import {PubdataTooSmall, L1DAValidatorInvalidSender} from "contracts/state-transition/L1StateTransitionErrors.sol"; +import {InvalidPubdataSource} from "contracts/state-transition/L1StateTransitionErrors.sol"; contract RelayedSLDAValidatorTest is Test { uint256 constant CHAIN_ID = 193; @@ -50,7 +52,8 @@ contract RelayedSLDAValidatorTest is Test { bytes memory operatorDAInput = abi.encodePacked(daInput, l1DaInput); vm.prank(CHAIN_ADDRESS); - vm.expectRevert("l1-da-validator/invalid-pubdata-source"); + // 118 is ascii encoding for `v` + vm.expectRevert(abi.encodeWithSelector(InvalidPubdataSource.selector, 118)); daValidator.checkDA(CHAIN_ID, 0, l2DAValidatorOutputHash, operatorDAInput, maxBlobsSupported); } @@ -73,7 +76,7 @@ contract RelayedSLDAValidatorTest is Test { bytes memory operatorDAInput = abi.encodePacked(daInput, pubdataSource, l1DaInput); vm.prank(CHAIN_ADDRESS); - vm.expectRevert("pubdata too small"); + vm.expectRevert(abi.encodeWithSelector(PubdataTooSmall.selector, 15, 32)); daValidator.checkDA(CHAIN_ID, 0, l2DAValidatorOutputHash, operatorDAInput, maxBlobsSupported); } @@ -95,7 +98,7 @@ contract RelayedSLDAValidatorTest is Test { bytes memory operatorDAInput = abi.encodePacked(daInput, pubdataSource, l1DaInput); - vm.expectRevert("l1-da-validator/invalid-sender"); + vm.expectRevert(abi.encodeWithSelector(L1DAValidatorInvalidSender.selector, address(this))); daValidator.checkDA(CHAIN_ID, 0, l2DAValidatorOutputHash, operatorDAInput, maxBlobsSupported); } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RollupDAManager.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RollupDAManager.t.sol new file mode 100644 index 000000000..d16c33a91 --- /dev/null +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/data-availability/RollupDAManager.t.sol @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.18; + +// Import Foundry's Test framework +import {Test} from "forge-std/Test.sol"; + +// Import the RollupDAManager contract +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; + +import {ZeroAddress} from "contracts/common/L1ContractErrors.sol"; + +contract RollupDAManagerTest is Test { + // Instance of the contract under test + RollupDAManager rollupDAManager; + + // Addresses used in tests + address owner = address(0x1); + address newOwner = address(0x2); + address nonOwner = address(0x3); + address l1DAValidator1 = address(0x4); + address l2DAValidator1 = address(0x5); + address l1DAValidator2 = address(0x6); + address l2DAValidator2 = address(0x7); + address zeroAddress = address(0); + + // Events from the RollupDAManager contract + event DAPairUpdated(address indexed l1DAValidator, address indexed l2DAValidator, bool status); + + // setUp is run before each test + function setUp() public { + // Deploy the contract as the owner + vm.startPrank(owner); + rollupDAManager = new RollupDAManager(); + vm.stopPrank(); + } + + /* ========== Deployment Tests ========== */ + + function testOwnerIsSetCorrectly() public { + assertEq(rollupDAManager.owner(), owner, "Owner should be set correctly"); + } + + /* ========== Access Control Tests ========== */ + + function testOnlyOwnerCanUpdateDAPair() public { + // Attempt to update DA pair as owner + vm.startPrank(owner); + vm.expectEmit(true, true, false, true); + emit DAPairUpdated(l1DAValidator1, l2DAValidator1, true); + rollupDAManager.updateDAPair(l1DAValidator1, l2DAValidator1, true); + vm.stopPrank(); + + // Attempt to update DA pair as non-owner + vm.startPrank(nonOwner); + vm.expectRevert("Ownable: caller is not the owner"); + rollupDAManager.updateDAPair(l1DAValidator2, l2DAValidator2, true); + vm.stopPrank(); + } + + function testUpdateDAPairRevertsOnZeroAddresses() public { + vm.startPrank(owner); + + // Both addresses zero + vm.expectRevert(ZeroAddress.selector); + rollupDAManager.updateDAPair(zeroAddress, zeroAddress, true); + + // L1DAValidator zero + vm.expectRevert(ZeroAddress.selector); + rollupDAManager.updateDAPair(zeroAddress, l2DAValidator1, true); + + // L2DAValidator zero + vm.expectRevert(ZeroAddress.selector); + rollupDAManager.updateDAPair(l1DAValidator1, zeroAddress, true); + + vm.stopPrank(); + } + + /* ========== Functionality Tests ========== */ + + function testUpdateDAPairSetsAllowedDAPairsMapping() public { + vm.startPrank(owner); + + // Initially, the pair should not be allowed + bool allowed = rollupDAManager.isPairAllowed(l1DAValidator1, l2DAValidator1); + assertFalse(allowed, "DA pair should initially be disallowed"); + + // Update the DA pair to allowed + vm.expectEmit(true, true, false, true); + emit DAPairUpdated(l1DAValidator1, l2DAValidator1, true); + rollupDAManager.updateDAPair(l1DAValidator1, l2DAValidator1, true); + allowed = rollupDAManager.isPairAllowed(l1DAValidator1, l2DAValidator1); + assertTrue(allowed, "DA pair should be allowed after update"); + + // Update the DA pair to disallowed + vm.expectEmit(true, true, false, true); + emit DAPairUpdated(l1DAValidator1, l2DAValidator1, false); + rollupDAManager.updateDAPair(l1DAValidator1, l2DAValidator1, false); + allowed = rollupDAManager.isPairAllowed(l1DAValidator1, l2DAValidator1); + assertFalse(allowed, "DA pair should be disallowed after update"); + + vm.stopPrank(); + } + + function testUpdateMultipleDAPairs() public { + vm.startPrank(owner); + + // Update multiple DA pairs + rollupDAManager.updateDAPair(l1DAValidator1, l2DAValidator1, true); + rollupDAManager.updateDAPair(l1DAValidator2, l2DAValidator2, true); + + // Check both pairs + bool allowed1 = rollupDAManager.isPairAllowed(l1DAValidator1, l2DAValidator1); + bool allowed2 = rollupDAManager.isPairAllowed(l1DAValidator2, l2DAValidator2); + + assertTrue(allowed1, "First DA pair should be allowed"); + assertTrue(allowed2, "Second DA pair should be allowed"); + + vm.stopPrank(); + } +} diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/PriorityTree/PriorityTree.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/PriorityTree/PriorityTree.t.sol index 447e4e47d..fa5fdfcc4 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/PriorityTree/PriorityTree.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/PriorityTree/PriorityTree.t.sol @@ -4,6 +4,7 @@ pragma solidity 0.8.24; import {PriorityTreeSharedTest, PriorityOpsBatchInfo} from "./_PriorityTree_Shared.t.sol"; import {PriorityTreeCommitment} from "contracts/common/Config.sol"; +import {RootMismatch} from "contracts/state-transition/L1StateTransitionErrors.sol"; bytes32 constant ZERO_LEAF_HASH = keccak256(""); @@ -83,7 +84,7 @@ contract PriorityTreeTest is PriorityTreeSharedTest { function test_processBatch_shouldRevert() public { bytes32[] memory itemHashes = pushMockEntries(3); - vm.expectRevert("PT: root mismatch"); + vm.expectRevert(RootMismatch.selector); priorityTree.processBatch( PriorityOpsBatchInfo({leftPath: new bytes32[](2), rightPath: new bytes32[](2), itemHashes: itemHashes}) ); diff --git a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/TransactionValidator/ValidateL1L2Tx.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/TransactionValidator/ValidateL1L2Tx.t.sol index 8016b62f4..e01b6b4e4 100644 --- a/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/TransactionValidator/ValidateL1L2Tx.t.sol +++ b/l1-contracts/test/foundry/l1/unit/concrete/state-transition/libraries/TransactionValidator/ValidateL1L2Tx.t.sol @@ -4,7 +4,8 @@ pragma solidity 0.8.24; import {TransactionValidatorSharedTest} from "./_TransactionValidator_Shared.t.sol"; import {L2CanonicalTransaction} from "contracts/common/Messaging.sol"; -import {PubdataGreaterThanLimit, TxnBodyGasLimitNotEnoughGas, ValidateTxnNotEnoughGas, NotEnoughGas, TooMuchGas, InvalidPubdataLength} from "contracts/common/L1ContractErrors.sol"; +import {PubdataGreaterThanLimit, TxnBodyGasLimitNotEnoughGas, ValidateTxnNotEnoughGas, NotEnoughGas, TooMuchGas} from "contracts/common/L1ContractErrors.sol"; +import {OverheadForTransactionMustBeEqualToTxSlotOverhead} from "test/foundry/L1TestsErrors.sol"; contract ValidateL1L2TxTest is TransactionValidatorSharedTest { function test_BasicRequestL1L2() public pure { @@ -79,16 +80,14 @@ contract ValidateL1L2TxTest is TransactionValidatorSharedTest { } function test_ShouldReturnCorrectOverhead_ShortTx() public pure { - require( - getOverheadForTransaction(32) == 10_000, - "The overhead for short transaction must be equal to the tx slot overhead" - ); + if (getOverheadForTransaction(32) != 10_000) { + revert OverheadForTransactionMustBeEqualToTxSlotOverhead(getOverheadForTransaction(32)); + } } function test_ShouldReturnCorrectOverhead_LongTx() public pure { - require( - getOverheadForTransaction(1000000) == 1000000 * 10, - "The overhead for long transaction must be equal to the tx slot overhead" - ); + if (getOverheadForTransaction(1000000) != 1000000 * 10) { + revert OverheadForTransactionMustBeEqualToTxSlotOverhead(getOverheadForTransaction(1000000)); + } } } diff --git a/l1-contracts/test/foundry/l1/unit/concrete/upgrades/GovernanceUpgradeTimer.t.sol b/l1-contracts/test/foundry/l1/unit/concrete/upgrades/GovernanceUpgradeTimer.t.sol new file mode 100644 index 000000000..5feb00e0e --- /dev/null +++ b/l1-contracts/test/foundry/l1/unit/concrete/upgrades/GovernanceUpgradeTimer.t.sol @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.18; + +// Import Foundry's Test framework +import {Test} from "forge-std/Test.sol"; + +import {GovernanceUpgradeTimer} from "contracts/upgrades/GovernanceUpgradeTimer.sol"; + +import {ZeroAddress, TimerAlreadyStarted, CallerNotTimerAdmin, DeadlineNotYetPassed, NewDeadlineNotGreaterThanCurrent, NewDeadlineExceedsMaxDeadline} from "contracts/common/L1ContractErrors.sol"; + +contract GovernanceUpgradeTimerTest is Test { + // Instance of the contract under test + GovernanceUpgradeTimer timer; + + // Addresses used in tests + address owner = address(0x1); + address newOwner = address(0x2); + address timerGovernance = address(0x3); + address nonAdmin = address(0x4); + address anotherAddress = address(0x5); + + // Immutable parameters for the contract + uint256 initialDelay = 1000; // seconds + uint256 maxAdditionalDelay = 2000; // seconds + + // Events from the GovernanceUpgradeTimer contract + event TimerStarted(uint256 deadline, uint256 maxDeadline); + event DeadlineChanged(uint256 newDeadline); + + // setUp is run before each test + function setUp() public { + // Deploy the contract as the owner + vm.startPrank(owner); + timer = new GovernanceUpgradeTimer(initialDelay, maxAdditionalDelay, timerGovernance, owner); + vm.stopPrank(); + } + + /* ========== Deployment Tests ========== */ + + function testDeploymentSetsImmutableVariablesCorrectly() public { + assertEq(timer.INITIAL_DELAY(), initialDelay, "INITIAL_DELAY should be set correctly"); + assertEq(timer.MAX_ADDITIONAL_DELAY(), maxAdditionalDelay, "MAX_ADDITIONAL_DELAY should be set correctly"); + assertEq(timer.TIMER_GOVERNANCE(), timerGovernance, "TIMER_GOVERNANCE should be set correctly"); + } + + function testDeploymentSetsOwnerCorrectly() public { + assertEq(timer.owner(), owner, "Owner should be set correctly"); + } + + function testDeploymentRevertsIfTimerGovernanceIsZero() public { + vm.startPrank(owner); + vm.expectRevert(ZeroAddress.selector); + new GovernanceUpgradeTimer(initialDelay, maxAdditionalDelay, address(0), owner); + vm.stopPrank(); + } + + /* ========== Access Control Tests ========== */ + + function testOnlyTimerGovernanceCanStartTimer() public { + // Attempt to start timer as TIMER_GOVERNANCE + vm.startPrank(timerGovernance); + vm.expectEmit(true, true, false, true); + emit TimerStarted(block.timestamp + initialDelay, block.timestamp + initialDelay + maxAdditionalDelay); + timer.startTimer(); + vm.stopPrank(); + + // Attempt to start timer as non-TIMER_GOVERNANCE + vm.startPrank(nonAdmin); + vm.expectRevert(CallerNotTimerAdmin.selector); + timer.startTimer(); + vm.stopPrank(); + } + + function testOnlyOwnerCanChangeDeadline() public { + // Start the timer first + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 newDeadline = timer.deadline() + 500; + + // Attempt to change deadline as owner + vm.startPrank(owner); + vm.expectEmit(true, false, false, true); + emit DeadlineChanged(newDeadline); + timer.changeDeadline(newDeadline); + vm.stopPrank(); + + // Attempt to change deadline as non-owner + vm.startPrank(nonAdmin); + vm.expectRevert("Ownable: caller is not the owner"); + timer.changeDeadline(newDeadline + 100); + vm.stopPrank(); + } + + /* ========== Functionality Tests ========== */ + + function testStartTimerSetsDeadlineAndMaxDeadlineCorrectly() public { + uint256 currentBlockTimestamp = block.timestamp; + + vm.startPrank(timerGovernance); + vm.expectEmit(true, true, false, true); + emit TimerStarted( + currentBlockTimestamp + initialDelay, + currentBlockTimestamp + initialDelay + maxAdditionalDelay + ); + timer.startTimer(); + vm.stopPrank(); + + assertEq(timer.deadline(), currentBlockTimestamp + initialDelay, "Deadline should be set correctly"); + assertEq( + timer.maxDeadline(), + currentBlockTimestamp + initialDelay + maxAdditionalDelay, + "MaxDeadline should be set correctly" + ); + } + + function testStartTimerCanNotBeCalledMultipleTimesByTimerGovernance() public { + uint256 firstBlockTimestamp = block.timestamp; + + // First timer start + vm.startPrank(timerGovernance); + vm.expectEmit(true, true, false, true); + emit TimerStarted(firstBlockTimestamp + initialDelay, firstBlockTimestamp + initialDelay + maxAdditionalDelay); + timer.startTimer(); + vm.stopPrank(); + + // Second timer start + vm.startPrank(timerGovernance); + vm.expectRevert(TimerAlreadyStarted.selector); + timer.startTimer(); + vm.stopPrank(); + } + + function testCheckDeadlineRevertsIfDeadlineNotPassed() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + // Attempt to check deadline before it has passed + vm.expectRevert(DeadlineNotYetPassed.selector); + timer.checkDeadline(); + } + + function testCheckDeadlineDoesNotRevertIfDeadlinePassed() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + // Advance time past the deadline + vm.warp(timer.deadline() + 1); + + // Check deadline should not revert + timer.checkDeadline(); + } + + function testChangeDeadlineRevertsIfNewDeadlineNotGreater() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 originalDeadline = timer.deadline(); + uint256 invalidNewDeadline = originalDeadline - 100; + + // Attempt to change deadline to a value not greater than current + vm.startPrank(owner); + vm.expectRevert(NewDeadlineNotGreaterThanCurrent.selector); + timer.changeDeadline(invalidNewDeadline); + vm.stopPrank(); + } + + function testChangeDeadlineRevertsIfNewDeadlineExceedsMaxDeadline() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 maxDeadline = timer.maxDeadline(); + uint256 invalidNewDeadline = maxDeadline + 1; + + // Attempt to change deadline to exceed maxDeadline + vm.startPrank(owner); + vm.expectRevert(NewDeadlineExceedsMaxDeadline.selector); + timer.changeDeadline(invalidNewDeadline); + vm.stopPrank(); + } + + /* ========== Edge Case Tests ========== */ + + function testChangeDeadlineToMaxDeadline() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 maxDeadline = timer.maxDeadline(); + + // Change deadline to maxDeadline + vm.startPrank(owner); + vm.expectEmit(true, false, false, true); + emit DeadlineChanged(maxDeadline); + timer.changeDeadline(maxDeadline); + vm.stopPrank(); + + assertEq(timer.deadline(), maxDeadline, "Deadline should be set to maxDeadline"); + } + + function testChangeDeadlineRevertsIfNewDeadlineEqualsCurrent() public { + // Start the timer + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 currentDeadline = timer.deadline(); + + // Attempt to change deadline to the current deadline + vm.startPrank(owner); + vm.expectRevert(NewDeadlineNotGreaterThanCurrent.selector); + timer.changeDeadline(currentDeadline); + vm.stopPrank(); + } + + /* ========== Unauthorized Function Calls ========== */ + + function testNonTimerGovernanceCannotStartTimer() public { + vm.startPrank(owner); + vm.expectRevert(CallerNotTimerAdmin.selector); + timer.startTimer(); + vm.stopPrank(); + } + + function testNonOwnerCannotChangeDeadline() public { + // Start the timer first + vm.startPrank(timerGovernance); + timer.startTimer(); + vm.stopPrank(); + + uint256 newDeadline = timer.deadline() + 500; + + vm.startPrank(nonAdmin); + vm.expectRevert("Ownable: caller is not the owner"); + timer.changeDeadline(newDeadline); + vm.stopPrank(); + } +} diff --git a/l1-contracts/test/foundry/l2/integration/L2Utils.sol b/l1-contracts/test/foundry/l2/integration/L2Utils.sol index d10105734..cdda458cd 100644 --- a/l1-contracts/test/foundry/l2/integration/L2Utils.sol +++ b/l1-contracts/test/foundry/l2/integration/L2Utils.sol @@ -5,9 +5,7 @@ pragma solidity ^0.8.20; import {Vm} from "forge-std/Vm.sol"; import "forge-std/console.sol"; -import {UpgradeableBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/UpgradeableBeacon.sol"; -import {BeaconProxy} from "@openzeppelin/contracts-v4/proxy/beacon/BeaconProxy.sol"; -import {DEPLOYER_SYSTEM_CONTRACT, L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR, L2_BRIDGEHUB_ADDR, L2_MESSAGE_ROOT_ADDR} from "contracts/common/L2ContractAddresses.sol"; +import {L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, L2_ASSET_ROUTER_ADDR, L2_NATIVE_TOKEN_VAULT_ADDR, L2_BRIDGEHUB_ADDR, L2_MESSAGE_ROOT_ADDR} from "contracts/common/L2ContractAddresses.sol"; import {IContractDeployer, L2ContractHelper} from "contracts/common/libraries/L2ContractHelper.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; @@ -70,7 +68,7 @@ library L2Utils { */ function initSystemContracts(SystemContractsArgs memory _args) internal { bytes memory contractDeployerBytecode = readSystemContractsBytecode("ContractDeployer"); - vm.etch(DEPLOYER_SYSTEM_CONTRACT, contractDeployerBytecode); + vm.etch(L2_DEPLOYER_SYSTEM_CONTRACT_ADDR, contractDeployerBytecode); forceDeploySystemContracts(_args); } @@ -213,7 +211,7 @@ library L2Utils { }); vm.prank(L2_FORCE_DEPLOYER_ADDR); - IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).forceDeployOnAddresses(deployments); + IContractDeployer(L2_DEPLOYER_SYSTEM_CONTRACT_ADDR).forceDeployOnAddresses(deployments); } function deployViaCreat2L2( diff --git a/l1-contracts/test/foundry/l2/unit/GatewayCTMDeployer/GatewayCTMDeployer.t.sol b/l1-contracts/test/foundry/l2/unit/GatewayCTMDeployer/GatewayCTMDeployer.t.sol new file mode 100644 index 000000000..f016b6559 --- /dev/null +++ b/l1-contracts/test/foundry/l2/unit/GatewayCTMDeployer/GatewayCTMDeployer.t.sol @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.20; + +import {Test} from "forge-std/Test.sol"; + +import {GatewayCTMDeployer, GatewayCTMDeployerConfig, DeployedContracts, StateTransitionContracts, DAContracts} from "contracts/state-transition/chain-deps/GatewayCTMDeployer.sol"; +import {VerifierParams, IVerifier} from "contracts/state-transition/chain-interfaces/IVerifier.sol"; +import {FeeParams, PubdataPricingMode} from "contracts/state-transition/chain-deps/ZKChainStorage.sol"; + +import {MailboxFacet} from "contracts/state-transition/chain-deps/facets/Mailbox.sol"; +import {ExecutorFacet} from "contracts/state-transition/chain-deps/facets/Executor.sol"; +import {GettersFacet} from "contracts/state-transition/chain-deps/facets/Getters.sol"; +import {AdminFacet} from "contracts/state-transition/chain-deps/facets/Admin.sol"; + +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; +import {RelayedSLDAValidator} from "contracts/state-transition/data-availability/RelayedSLDAValidator.sol"; +import {ValidiumL1DAValidator} from "contracts/state-transition/data-availability/ValidiumL1DAValidator.sol"; + +import {Verifier} from "contracts/state-transition/Verifier.sol"; +import {TestnetVerifier} from "contracts/state-transition/TestnetVerifier.sol"; +import {ValidatorTimelock} from "contracts/state-transition/ValidatorTimelock.sol"; + +import {DiamondInit} from "contracts/state-transition/chain-deps/DiamondInit.sol"; +import {L1GenesisUpgrade} from "contracts/upgrades/L1GenesisUpgrade.sol"; +import {Diamond} from "contracts/state-transition/libraries/Diamond.sol"; + +import {ChainTypeManager} from "contracts/state-transition/ChainTypeManager.sol"; + +import {L2_BRIDGEHUB_ADDR} from "contracts/common/L2ContractAddresses.sol"; + +import {ProxyAdmin} from "@openzeppelin/contracts-v4/proxy/transparent/ProxyAdmin.sol"; +import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; +import {RollupDAManager} from "contracts/state-transition/data-availability/RollupDAManager.sol"; + +import {GatewayCTMDeployerHelper} from "deploy-scripts/GatewayCTMDeployerHelper.sol"; + +import {L2_CREATE2_FACTORY_ADDRESS} from "deploy-scripts/Utils.sol"; + +// We need to use contract the zkfoundry consistently uses +// zk environment only within a deployed contract +contract GatewayCTMDeployerTester { + function deployCTMDeployer( + bytes memory data + ) external returns (DeployedContracts memory deployedContracts, address addr) { + (bool success, bytes memory result) = L2_CREATE2_FACTORY_ADDRESS.call(data); + require(success, "failed to deploy"); + + addr = abi.decode(result, (address)); + + deployedContracts = GatewayCTMDeployer(addr).getDeployedContracts(); + } +} + +contract GatewayCTMDeployerTest is Test { + GatewayCTMDeployerConfig deployerConfig; + + // This is done merely to publish the respective bytecodes. + function _predeployContracts() internal { + new MailboxFacet(1, 1); + new ExecutorFacet(1); + new GettersFacet(); + new AdminFacet(1, RollupDAManager(address(0))); + + new DiamondInit(); + new L1GenesisUpgrade(); + new RollupDAManager(); + new ValidiumL1DAValidator(); + new RelayedSLDAValidator(); + new ChainTypeManager(address(0)); + new ProxyAdmin(); + + new TestnetVerifier(); + new Verifier(); + + new ValidatorTimelock(address(0), 0); + + // This call will likely fail due to various checks, but we just need to get the bytecode published + try new TransparentUpgradeableProxy(address(0), address(0), hex"") {} catch {} + } + + function setUp() external { + // Initialize the configuration with sample data + GatewayCTMDeployerConfig memory config = GatewayCTMDeployerConfig({ + aliasedGovernanceAddress: address(0x123), + salt: keccak256("test-salt"), + eraChainId: 1001, + l1ChainId: 1, + rollupL2DAValidatorAddress: address(0x456), + testnetVerifier: true, + adminSelectors: new bytes4[](2), + executorSelectors: new bytes4[](2), + mailboxSelectors: new bytes4[](2), + gettersSelectors: new bytes4[](2), + verifierParams: VerifierParams({ + recursionNodeLevelVkHash: bytes32(0), + recursionLeafLevelVkHash: bytes32(0), + recursionCircuitsSetVksHash: bytes32(0) + }), + feeParams: FeeParams({ + // Just random values + pubdataPricingMode: PubdataPricingMode.Rollup, + batchOverheadL1Gas: uint32(1_000_000), + maxPubdataPerBatch: uint32(500_000), + maxL2GasPerBatch: uint32(2_000_000_000), + priorityTxMaxPubdata: uint32(99_000), + minimalL2GasPrice: uint64(20000000) + }), + bootloaderHash: bytes32(uint256(0xabc)), + defaultAccountHash: bytes32(uint256(0xdef)), + priorityTxMaxGasLimit: 100000, + genesisRoot: bytes32(uint256(0x123)), + genesisRollupLeafIndex: 10, + genesisBatchCommitment: bytes32(uint256(0x456)), + forceDeploymentsData: hex"deadbeef", + protocolVersion: 1 + }); + + // Initialize selectors with sample function selectors + config.adminSelectors[0] = bytes4(keccak256("adminFunction1()")); + config.adminSelectors[1] = bytes4(keccak256("adminFunction2()")); + config.executorSelectors[0] = bytes4(keccak256("executorFunction1()")); + config.executorSelectors[1] = bytes4(keccak256("executorFunction2()")); + config.mailboxSelectors[0] = bytes4(keccak256("mailboxFunction1()")); + config.mailboxSelectors[1] = bytes4(keccak256("mailboxFunction2()")); + config.gettersSelectors[0] = bytes4(keccak256("gettersFunction1()")); + config.gettersSelectors[1] = bytes4(keccak256("gettersFunction2()")); + + deployerConfig = config; + + _predeployContracts(); + } + + // It is more a smoke test that indeed the deployment works + function testGatewayCTMDeployer() external { + // Just to publish bytecode + new GatewayCTMDeployer(deployerConfig); + + ( + DeployedContracts memory calculatedDeployedContracts, + bytes memory create2Calldata, + address ctmDeployerAddress + ) = GatewayCTMDeployerHelper.calculateAddresses(bytes32(0), deployerConfig); + + GatewayCTMDeployerTester tester = new GatewayCTMDeployerTester(); + (DeployedContracts memory deployedContracts, address correctCTMDeployerAddress) = tester.deployCTMDeployer( + create2Calldata + ); + + require(ctmDeployerAddress == correctCTMDeployerAddress, "Incorrect address"); + + DeployedContractsComparator.compareDeployedContracts(calculatedDeployedContracts, deployedContracts); + + // require(keccak256(abi.encode(calculatedDeployedContracts)) == keccak256(abi.encode(deployedContracts)), "Incorrect calculated addresses"); + + // GatewayCTMDeployer deployer = new GatewayCTMDeployer( + // deployerConfig + // ); + + // DeployedContracts memory deployedContracts = deployer.getDeployedContracts(); + } +} + +library DeployedContractsComparator { + function compareDeployedContracts(DeployedContracts memory a, DeployedContracts memory b) internal pure { + compareStateTransitionContracts(a.stateTransition, b.stateTransition); + compareDAContracts(a.daContracts, b.daContracts); + compareBytes(a.diamondCutData, b.diamondCutData, "diamondCutData"); + } + + function compareStateTransitionContracts( + StateTransitionContracts memory a, + StateTransitionContracts memory b + ) internal pure { + require(a.chainTypeManagerProxy == b.chainTypeManagerProxy, "chainTypeManagerProxy differs"); + require( + a.chainTypeManagerImplementation == b.chainTypeManagerImplementation, + "chainTypeManagerImplementation differs" + ); + require(a.verifier == b.verifier, "verifier differs"); + require(a.adminFacet == b.adminFacet, "adminFacet differs"); + require(a.mailboxFacet == b.mailboxFacet, "mailboxFacet differs"); + require(a.executorFacet == b.executorFacet, "executorFacet differs"); + require(a.gettersFacet == b.gettersFacet, "gettersFacet differs"); + require(a.diamondInit == b.diamondInit, "diamondInit differs"); + require(a.genesisUpgrade == b.genesisUpgrade, "genesisUpgrade differs"); + require(a.validatorTimelock == b.validatorTimelock, "validatorTimelock differs"); + require(a.chainTypeManagerProxyAdmin == b.chainTypeManagerProxyAdmin, "chainTypeManagerProxyAdmin differs"); + } + + function compareDAContracts(DAContracts memory a, DAContracts memory b) internal pure { + require(a.rollupDAManager == b.rollupDAManager, "rollupDAManager differs"); + require(a.relayedSLDAValidator == b.relayedSLDAValidator, "relayedSLDAValidator differs"); + require(a.validiumDAValidator == b.validiumDAValidator, "validiumDAValidator differs"); + } + + function compareBytes(bytes memory a, bytes memory b, string memory fieldName) internal pure { + require(keccak256(a) == keccak256(b), string(abi.encodePacked(fieldName, " differs"))); + } +} diff --git a/l1-contracts/test/foundry/l2/unit/L2AdminFactory/L2AdminFactory.t.sol b/l1-contracts/test/foundry/l2/unit/L2AdminFactory/L2AdminFactory.t.sol index 7b85a8c54..95bcb8304 100644 --- a/l1-contracts/test/foundry/l2/unit/L2AdminFactory/L2AdminFactory.t.sol +++ b/l1-contracts/test/foundry/l2/unit/L2AdminFactory/L2AdminFactory.t.sol @@ -8,16 +8,51 @@ import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; import {L2AdminFactory} from "contracts/governance/L2AdminFactory.sol"; import {PermanentRestriction} from "contracts/governance/PermanentRestriction.sol"; import {IPermanentRestriction} from "contracts/governance/IPermanentRestriction.sol"; +import {DummyRestriction} from "contracts/dev-contracts/DummyRestriction.sol"; +import {NotARestriction} from "contracts/common/L1ContractErrors.sol"; contract L2AdminFactoryTest is Test { + address validRestriction1; + address validRestriction2; + + address invalidRestriction; + + function setUp() public { + validRestriction1 = address(new DummyRestriction(true)); + validRestriction2 = address(new DummyRestriction(true)); + + invalidRestriction = address(new DummyRestriction(false)); + } + + function test_invalidInitialRestriction() public { + address[] memory requiredRestrictions = new address[](1); + requiredRestrictions[0] = invalidRestriction; + + vm.expectRevert(abi.encodeWithSelector(NotARestriction.selector, address(invalidRestriction))); + L2AdminFactory factory = new L2AdminFactory(requiredRestrictions); + } + + function test_invalidAdditionalRestriction() public { + address[] memory requiredRestrictions = new address[](1); + requiredRestrictions[0] = validRestriction1; + + L2AdminFactory factory = new L2AdminFactory(requiredRestrictions); + + address[] memory additionalRestrictions = new address[](1); + additionalRestrictions[0] = invalidRestriction; + + vm.expectRevert(abi.encodeWithSelector(NotARestriction.selector, address(invalidRestriction))); + factory.deployAdmin(additionalRestrictions, bytes32(0)); + } + function testL2AdminFactory() public { address[] memory requiredRestrictions = new address[](1); - requiredRestrictions[0] = makeAddr("required"); + requiredRestrictions[0] = validRestriction1; L2AdminFactory factory = new L2AdminFactory(requiredRestrictions); address[] memory additionalRestrictions = new address[](1); - additionalRestrictions[0] = makeAddr("additional"); + additionalRestrictions[0] = validRestriction2; address[] memory allRestrictions = new address[](2); allRestrictions[0] = requiredRestrictions[0]; diff --git a/l1-contracts/test/foundry/unit/concrete/GatewayTransactionFilterer/CheckTransaction.sol b/l1-contracts/test/foundry/unit/concrete/GatewayTransactionFilterer/CheckTransaction.sol index 3231a7144..f9e22907f 100644 --- a/l1-contracts/test/foundry/unit/concrete/GatewayTransactionFilterer/CheckTransaction.sol +++ b/l1-contracts/test/foundry/unit/concrete/GatewayTransactionFilterer/CheckTransaction.sol @@ -4,13 +4,16 @@ pragma solidity 0.8.24; import {GatewayTransactionFiltererTest} from "./_GatewayTransactionFilterer_Shared.t.sol"; import {IGetters} from "contracts/state-transition/chain-interfaces/IGetters.sol"; -import {IL2Bridge} from "contracts/bridge/interfaces/IL2Bridge.sol"; import {IBridgehub} from "contracts/bridgehub/IBridgehub.sol"; +import {IAssetRouterBase} from "contracts/bridge/asset-router/IAssetRouterBase.sol"; import {AlreadyWhitelisted, InvalidSelector, NotWhitelisted} from "contracts/common/L1ContractErrors.sol"; contract CheckTransactionTest is GatewayTransactionFiltererTest { function test_TransactionAllowedOnlyFromWhitelistedSenderWhichIsNotAssetRouter() public { - bytes memory txCalladata = abi.encodeCall(IL2Bridge.finalizeDeposit, (bytes32("0x12345"), bytes("0x23456"))); + bytes memory txCalladata = abi.encodeCall( + IAssetRouterBase.finalizeDeposit, + (uint256(10), bytes32("0x12345"), bytes("0x23456")) + ); vm.startPrank(owner); vm.mockCall( bridgehub, @@ -50,7 +53,10 @@ contract CheckTransactionTest is GatewayTransactionFiltererTest { function test_TransactionAllowedFromWhitelistedSenderForChainBridging() public { address stm = address(0x6060606); - bytes memory txCalladata = abi.encodeCall(IL2Bridge.finalizeDeposit, (bytes32("0x12345"), bytes("0x23456"))); + bytes memory txCalladata = abi.encodeCall( + IAssetRouterBase.finalizeDeposit, + (uint256(10), bytes32("0x12345"), bytes("0x23456")) + ); vm.startPrank(owner); vm.mockCall( bridgehub, @@ -74,9 +80,14 @@ contract CheckTransactionTest is GatewayTransactionFiltererTest { } function test_TransactionFailsWithInvalidSelectorEvenIfTheSenderIsAR() public { - bytes memory txCalladata = abi.encodeCall(IL2Bridge.withdraw, (bytes32("0x12345"), bytes("0x23456"))); + bytes memory txCalladata = abi.encodeCall( + IAssetRouterBase.setAssetHandlerAddressThisChain, + (bytes32("0x12345"), address(0x01234567890123456789)) + ); vm.prank(owner); - vm.expectRevert(abi.encodeWithSelector(InvalidSelector.selector, IL2Bridge.withdraw.selector)); + vm.expectRevert( + abi.encodeWithSelector(InvalidSelector.selector, IAssetRouterBase.setAssetHandlerAddressThisChain.selector) + ); bool isTxAllowed = transactionFiltererProxy.isTransactionAllowed( assetRouter, address(0), diff --git a/l1-contracts/test/unit_tests/l2-upgrade.test.spec.ts b/l1-contracts/test/unit_tests/l2-upgrade.test.spec.ts index 4d04f6695..5aade6ad9 100644 --- a/l1-contracts/test/unit_tests/l2-upgrade.test.spec.ts +++ b/l1-contracts/test/unit_tests/l2-upgrade.test.spec.ts @@ -364,56 +364,17 @@ describe("L2 upgrade test", function () { expect(revertReason).contains("PubdataGreaterThanLimit"); }); - it("Should validate factory deps", async () => { - const myFactoryDep = ethers.utils.hexlify(ethers.utils.randomBytes(32)); - const wrongFactoryDepHash = ethers.utils.hexlify(hashBytecode(ethers.utils.randomBytes(32))); - const wrongTx = buildL2CanonicalTransaction({ - factoryDeps: [wrongFactoryDepHash], - nonce: 4 + initialMinorProtocolVersion, - }); - - const revertReason = await getCallRevertReason( - executeUpgrade(chainId, proxyGetters, chainTypeManager, proxyAdmin, { - l2ProtocolUpgradeTx: wrongTx, - factoryDeps: [myFactoryDep], - newProtocolVersion: addToProtocolVersion(initialProtocolVersion, 4, 0), - }) - ); - - expect(revertReason).contains("L2BytecodeHashMismatch"); - }); - - it("Should validate factory deps length match", async () => { - const myFactoryDep = ethers.utils.hexlify(ethers.utils.randomBytes(32)); - const wrongTx = buildL2CanonicalTransaction({ - factoryDeps: [], - nonce: 4 + initialMinorProtocolVersion, - }); - - const revertReason = await getCallRevertReason( - executeUpgrade(chainId, proxyGetters, chainTypeManager, proxyAdmin, { - l2ProtocolUpgradeTx: wrongTx, - factoryDeps: [myFactoryDep], - newProtocolVersion: addToProtocolVersion(initialProtocolVersion, 4, 0), - }) - ); - - expect(revertReason).contains("UnexpectedNumberOfFactoryDeps"); - }); - it("Should validate factory deps length isn't too large", async () => { - const myFactoryDep = ethers.utils.hexlify(ethers.utils.randomBytes(32)); const randomDepHash = ethers.utils.hexlify(hashBytecode(ethers.utils.randomBytes(32))); const wrongTx = buildL2CanonicalTransaction({ - factoryDeps: Array(33).fill(randomDepHash), + factoryDeps: Array(65).fill(randomDepHash), nonce: 4 + initialMinorProtocolVersion, }); const revertReason = await getCallRevertReason( executeUpgrade(chainId, proxyGetters, chainTypeManager, proxyAdmin, { l2ProtocolUpgradeTx: wrongTx, - factoryDeps: Array(33).fill(myFactoryDep), newProtocolVersion: addToProtocolVersion(initialProtocolVersion, 4, 0), }) ); @@ -448,7 +409,6 @@ describe("L2 upgrade test", function () { verifierParams: newerVerifierParams, executeUpgradeTx: true, l2ProtocolUpgradeTx: upgradeTx, - factoryDeps: [myFactoryDep], newProtocolVersion: addToProtocolVersion(initialProtocolVersion, 5, 0), }; @@ -996,7 +956,6 @@ function buildProposeUpgrade(proposedUpgrade: PartialProposedUpgrade): ProposedU l1ContractsUpgradeCalldata: "0x", postUpgradeCalldata: "0x", upgradeTimestamp: ethers.constants.Zero, - factoryDeps: [], newProtocolVersion, ...proposedUpgrade, }; diff --git a/l1-contracts/test/unit_tests/proxy_test.spec.ts b/l1-contracts/test/unit_tests/proxy_test.spec.ts index 46067e16f..836942760 100644 --- a/l1-contracts/test/unit_tests/proxy_test.spec.ts +++ b/l1-contracts/test/unit_tests/proxy_test.spec.ts @@ -45,7 +45,7 @@ describe("Diamond proxy tests", function () { diamondInit = DiamondInitFactory.connect(diamondInitContract.address, diamondInitContract.signer); const adminFactory = await hardhat.ethers.getContractFactory("AdminFacet"); - const adminContract = await adminFactory.deploy(await owner.getChainId()); + const adminContract = await adminFactory.deploy(await owner.getChainId(), ethers.constants.AddressZero); adminFacet = AdminFacetFactory.connect(adminContract.address, adminContract.signer); const gettersFacetFactory = await hardhat.ethers.getContractFactory("GettersFacet"); @@ -57,7 +57,7 @@ describe("Diamond proxy tests", function () { mailboxFacet = MailboxFacetFactory.connect(mailboxFacetContract.address, mailboxFacetContract.signer); const executorFactory = await hardhat.ethers.getContractFactory("ExecutorFacet"); - const executorContract = await executorFactory.deploy(); + const executorContract = await executorFactory.deploy(await owner.getChainId()); executorFacet = ExecutorFacetFactory.connect(executorContract.address, executorContract.signer); const diamondProxyTestFactory = await hardhat.ethers.getContractFactory("DiamondProxyTest"); diff --git a/l1-contracts/test/unit_tests/utils.ts b/l1-contracts/test/unit_tests/utils.ts index af74fa28f..1114ed5f4 100644 --- a/l1-contracts/test/unit_tests/utils.ts +++ b/l1-contracts/test/unit_tests/utils.ts @@ -47,9 +47,12 @@ export function randomAddress() { export enum SYSTEM_LOG_KEYS { L2_TO_L1_LOGS_TREE_ROOT_KEY, PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, - PREV_BATCH_HASH_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, @@ -223,12 +226,6 @@ export function createSystemLogs( SYSTEM_LOG_KEYS.PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, ethers.constants.HashZero ), - constructL2Log( - true, - L2_SYSTEM_CONTEXT_ADDRESS, - SYSTEM_LOG_KEYS.PREV_BATCH_HASH_KEY, - previousBatchHash ? ethers.utils.hexlify(previousBatchHash) : ethers.constants.HashZero - ), constructL2Log( true, L2_BOOTLOADER_ADDRESS, @@ -241,7 +238,12 @@ export function createSystemLogs( SYSTEM_LOG_KEYS.NUMBER_OF_LAYER_1_TXS_KEY, numberOfLayer1Txs ? numberOfLayer1Txs.toString() : ethers.constants.HashZero ), - + constructL2Log( + true, + L2_SYSTEM_CONTEXT_ADDRESS, + SYSTEM_LOG_KEYS.PREV_BATCH_HASH_KEY, + previousBatchHash ? ethers.utils.hexlify(previousBatchHash) : ethers.constants.HashZero + ), constructL2Log( true, L2_TO_L1_MESSENGER, diff --git a/l2-contracts/contracts/ConsensusRegistry.sol b/l2-contracts/contracts/ConsensusRegistry.sol index de5af6340..6d05a4909 100644 --- a/l2-contracts/contracts/ConsensusRegistry.sol +++ b/l2-contracts/contracts/ConsensusRegistry.sol @@ -5,6 +5,7 @@ pragma solidity 0.8.24; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable-v4/access/Ownable2StepUpgradeable.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable-v4/proxy/utils/Initializable.sol"; import {IConsensusRegistry} from "./interfaces/IConsensusRegistry.sol"; +import {ZeroAddress} from "./errors/L2ContractErrors.sol"; /// @author Matter Labs /// @custom:security-contact security@matterlabs.dev @@ -21,8 +22,14 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg /// @dev A mapping of node owners => nodes. mapping(address => Node) public nodes; /// @dev A mapping for enabling efficient lookups when checking whether a given attester public key exists. + /// @dev Initially, the mappings mark the public keys used by the attesters in the current committee. However, + /// @dev after calling the changeAttesterKey functions, the mappings might also contain public keys of attesters + /// @dev that will only be part of the committee once the contract owner updates the attestersCommit state variable. mapping(bytes32 => bool) public attesterPubKeyHashes; /// @dev A mapping for enabling efficient lookups when checking whether a given validator public key exists. + /// @dev Initially, the mappings mark the public keys used by the validators in the current committee. However, + /// @dev after calling the changeValidatorKey functions, the mappings might also contain public keys of validators + /// @dev that will only be part of the committee once the contract owner updates the validatorsCommit state variable. mapping(bytes32 => bool) public validatorPubKeyHashes; /// @dev Counter that increments with each new commit to the attester committee. uint32 public attestersCommit; @@ -36,9 +43,14 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg _; } + /// @custom:oz-upgrades-unsafe-allow constructor + constructor() { + _disableInitializers(); + } + function initialize(address _initialOwner) external initializer { if (_initialOwner == address(0)) { - revert InvalidInputNodeOwnerAddress(); + revert ZeroAddress(); } _transferOwnership(_initialOwner); } @@ -47,16 +59,20 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg /// @dev Fails if node owner already exists. /// @dev Fails if a validator/attester with the same public key already exists. /// @param _nodeOwner The address of the new node's owner. + /// @param _isValidatorActive A flag stating if the validator starts activated. /// @param _validatorWeight The voting weight of the validator. /// @param _validatorPubKey The BLS12-381 public key of the validator. /// @param _validatorPoP The proof-of-possession (PoP) of the validator's public key. + /// @param _isAttesterActive A flag stating if the attester starts activated. /// @param _attesterWeight The voting weight of the attester. /// @param _attesterPubKey The ECDSA public key of the attester. function add( address _nodeOwner, + bool _isValidatorActive, uint32 _validatorWeight, BLS12_381PublicKey calldata _validatorPubKey, BLS12_381Signature calldata _validatorPoP, + bool _isAttesterActive, uint32 _attesterWeight, Secp256k1PublicKey calldata _attesterPubKey ) external onlyOwner { @@ -65,6 +81,12 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg _verifyInputBLS12_381PublicKey(_validatorPubKey); _verifyInputBLS12_381Signature(_validatorPoP); _verifyInputSecp256k1PublicKey(_attesterPubKey); + if (_attesterWeight == 0) { + revert ZeroAttesterWeight(); + } + if (_validatorWeight == 0) { + revert ZeroValidatorWeight(); + } // Verify storage. _verifyNodeOwnerDoesNotExist(_nodeOwner); @@ -77,8 +99,8 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg nodeOwners.push(_nodeOwner); nodes[_nodeOwner] = Node({ attesterLatest: AttesterAttr({ - active: true, removed: false, + active: _isAttesterActive, weight: _attesterWeight, pubKey: _attesterPubKey }), @@ -90,8 +112,8 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg }), attesterLastUpdateCommit: attestersCommit, validatorLatest: ValidatorAttr({ - active: true, removed: false, + active: _isValidatorActive, weight: _validatorWeight, pubKey: _validatorPubKey, proofOfPossession: _validatorPoP @@ -111,50 +133,82 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg emit NodeAdded({ nodeOwner: _nodeOwner, + isValidatorActive: _isValidatorActive, validatorWeight: _validatorWeight, validatorPubKey: _validatorPubKey, validatorPoP: _validatorPoP, + isAttesterActive: _isAttesterActive, attesterWeight: _attesterWeight, attesterPubKey: _attesterPubKey }); } - /// @notice Deactivates a node, preventing it from participating in committees. + /// @notice Deactivates an attester, preventing it from participating in attester committees. /// @dev Only callable by the contract owner or the node owner. /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner to be inactivated. - function deactivate(address _nodeOwner) external onlyOwnerOrNodeOwner(_nodeOwner) { + function deactivateAttester(address _nodeOwner) external onlyOwnerOrNodeOwner(_nodeOwner) { _verifyNodeOwnerExists(_nodeOwner); (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); if (deleted) { return; } - _ensureAttesterSnapshot(node); + _snapshotAttesterIfOutdated(node); node.attesterLatest.active = false; - _ensureValidatorSnapshot(node); - node.validatorLatest.active = false; - emit NodeDeactivated(_nodeOwner); + emit AttesterDeactivated(_nodeOwner); } - /// @notice Activates a previously inactive node, allowing it to participate in committees. + /// @notice Deactivates a validator, preventing it from participating in validator committees. /// @dev Only callable by the contract owner or the node owner. /// @dev Verifies that the node owner exists in the registry. + /// @param _nodeOwner The address of the node's owner to be inactivated. + function deactivateValidator(address _nodeOwner) external onlyOwnerOrNodeOwner(_nodeOwner) { + _verifyNodeOwnerExists(_nodeOwner); + (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); + if (deleted) { + return; + } + + _snapshotValidatorIfOutdated(node); + node.validatorLatest.active = false; + + emit ValidatorDeactivated(_nodeOwner); + } + + /// @notice Activates a previously inactive attester, allowing it to participate in attester committees. + /// @dev Only callable by the contract owner. + /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner to be activated. - function activate(address _nodeOwner) external onlyOwnerOrNodeOwner(_nodeOwner) { + function activateAttester(address _nodeOwner) external onlyOwner { _verifyNodeOwnerExists(_nodeOwner); (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); if (deleted) { return; } - _ensureAttesterSnapshot(node); + _snapshotAttesterIfOutdated(node); node.attesterLatest.active = true; - _ensureValidatorSnapshot(node); + + emit AttesterActivated(_nodeOwner); + } + + /// @notice Activates a previously inactive validator, allowing it to participate in validator committees. + /// @dev Only callable by the contract owner. + /// @dev Verifies that the node owner exists in the registry. + /// @param _nodeOwner The address of the node's owner to be activated. + function activateValidator(address _nodeOwner) external onlyOwner { + _verifyNodeOwnerExists(_nodeOwner); + (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); + if (deleted) { + return; + } + + _snapshotValidatorIfOutdated(node); node.validatorLatest.active = true; - emit NodeActivated(_nodeOwner); + emit ValidatorActivated(_nodeOwner); } /// @notice Removes a node from the registry. @@ -168,9 +222,9 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg return; } - _ensureAttesterSnapshot(node); + _snapshotAttesterIfOutdated(node); node.attesterLatest.removed = true; - _ensureValidatorSnapshot(node); + _snapshotValidatorIfOutdated(node); node.validatorLatest.removed = true; emit NodeRemoved(_nodeOwner); @@ -180,15 +234,18 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg /// @dev Only callable by the contract owner. /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner whose validator weight will be changed. - /// @param _weight The new validator weight to assign to the node. + /// @param _weight The new validator weight to assign to the node, must be greater than 0. function changeValidatorWeight(address _nodeOwner, uint32 _weight) external onlyOwner { + if (_weight == 0) { + revert ZeroValidatorWeight(); + } _verifyNodeOwnerExists(_nodeOwner); (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); if (deleted) { return; } - _ensureValidatorSnapshot(node); + _snapshotValidatorIfOutdated(node); node.validatorLatest.weight = _weight; emit NodeValidatorWeightChanged(_nodeOwner, _weight); @@ -198,22 +255,25 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg /// @dev Only callable by the contract owner. /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner whose attester weight will be changed. - /// @param _weight The new attester weight to assign to the node. + /// @param _weight The new attester weight to assign to the node, must be greater than 0. function changeAttesterWeight(address _nodeOwner, uint32 _weight) external onlyOwner { + if (_weight == 0) { + revert ZeroAttesterWeight(); + } _verifyNodeOwnerExists(_nodeOwner); (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); if (deleted) { return; } - _ensureAttesterSnapshot(node); + _snapshotAttesterIfOutdated(node); node.attesterLatest.weight = _weight; emit NodeAttesterWeightChanged(_nodeOwner, _weight); } /// @notice Changes the validator's public key and proof-of-possession in the registry. - /// @dev Only callable by the contract owner or the node owner. + /// @dev Only callable by the contract owner. /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner whose validator key and PoP will be changed. /// @param _pubKey The new BLS12-381 public key to assign to the node's validator. @@ -222,7 +282,7 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg address _nodeOwner, BLS12_381PublicKey calldata _pubKey, BLS12_381Signature calldata _pop - ) external onlyOwnerOrNodeOwner(_nodeOwner) { + ) external onlyOwner { _verifyInputBLS12_381PublicKey(_pubKey); _verifyInputBLS12_381Signature(_pop); _verifyNodeOwnerExists(_nodeOwner); @@ -236,7 +296,7 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg bytes32 newHash = _hashValidatorPubKey(_pubKey); _verifyValidatorPubKeyDoesNotExist(newHash); validatorPubKeyHashes[newHash] = true; - _ensureValidatorSnapshot(node); + _snapshotValidatorIfOutdated(node); node.validatorLatest.pubKey = _pubKey; node.validatorLatest.proofOfPossession = _pop; @@ -244,14 +304,11 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg } /// @notice Changes the attester's public key of a node in the registry. - /// @dev Only callable by the contract owner or the node owner. + /// @dev Only callable by the contract owner. /// @dev Verifies that the node owner exists in the registry. /// @param _nodeOwner The address of the node's owner whose attester public key will be changed. /// @param _pubKey The new ECDSA public key to assign to the node's attester. - function changeAttesterKey( - address _nodeOwner, - Secp256k1PublicKey calldata _pubKey - ) external onlyOwnerOrNodeOwner(_nodeOwner) { + function changeAttesterKey(address _nodeOwner, Secp256k1PublicKey calldata _pubKey) external onlyOwner { _verifyInputSecp256k1PublicKey(_pubKey); _verifyNodeOwnerExists(_nodeOwner); (Node storage node, bool deleted) = _getNodeAndDeleteIfRequired(_nodeOwner); @@ -265,7 +322,7 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg _verifyAttesterPubKeyDoesNotExist(newHash); attesterPubKeyHashes[newHash] = true; - _ensureAttesterSnapshot(node); + _snapshotAttesterIfOutdated(node); node.attesterLatest.pubKey = _pubKey; emit NodeAttesterKeyChanged(_nodeOwner, _pubKey); @@ -293,9 +350,9 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg emit ValidatorsCommitted(validatorsCommit); } - /// @notice Returns an array of `AttesterAttr` structs representing the current attester committee. + /// @notice Returns an array of `CommitteeAttester` structs representing the current attester committee. /// @dev Collects active and non-removed attesters based on the latest commit to the committee. - function getAttesterCommittee() public view returns (CommitteeAttester[] memory) { + function getAttesterCommittee() external view returns (CommitteeAttester[] memory) { uint256 len = nodeOwners.length; CommitteeAttester[] memory committee = new CommitteeAttester[](len); uint256 count = 0; @@ -318,9 +375,9 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg return committee; } - /// @notice Returns an array of `ValidatorAttr` structs representing the current attester committee. + /// @notice Returns an array of `CommitteeValidator` structs representing the current attester committee. /// @dev Collects active and non-removed validators based on the latest commit to the committee. - function getValidatorCommittee() public view returns (CommitteeValidator[] memory) { + function getValidatorCommittee() external view returns (CommitteeValidator[] memory) { uint256 len = nodeOwners.length; CommitteeValidator[] memory committee = new CommitteeValidator[](len); uint256 count = 0; @@ -347,7 +404,7 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg return committee; } - function numNodes() public view returns (uint256) { + function numNodes() external view returns (uint256) { return nodeOwners.length; } @@ -386,21 +443,21 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg emit NodeDeleted(_nodeOwner); } - function _ensureAttesterSnapshot(Node storage _node) private { + function _snapshotAttesterIfOutdated(Node storage _node) private { if (_node.attesterLastUpdateCommit < attestersCommit) { _node.attesterSnapshot = _node.attesterLatest; _node.attesterLastUpdateCommit = attestersCommit; } } - function _ensureValidatorSnapshot(Node storage _node) private { + function _snapshotValidatorIfOutdated(Node storage _node) private { if (_node.validatorLastUpdateCommit < validatorsCommit) { _node.validatorSnapshot = _node.validatorLatest; _node.validatorLastUpdateCommit = validatorsCommit; } } - function _isNodeOwnerExists(address _nodeOwner) private view returns (bool) { + function _doesNodeOwnerExist(address _nodeOwner) private view returns (bool) { BLS12_381PublicKey storage pubKey = nodes[_nodeOwner].validatorLatest.pubKey; if (pubKey.a == bytes32(0) && pubKey.b == bytes32(0) && pubKey.c == bytes32(0)) { return false; @@ -409,13 +466,13 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg } function _verifyNodeOwnerExists(address _nodeOwner) private view { - if (!_isNodeOwnerExists(_nodeOwner)) { + if (!_doesNodeOwnerExist(_nodeOwner)) { revert NodeOwnerDoesNotExist(); } } function _verifyNodeOwnerDoesNotExist(address _nodeOwner) private view { - if (_isNodeOwnerExists(_nodeOwner)) { + if (_doesNodeOwnerExist(_nodeOwner)) { revert NodeOwnerExists(); } } @@ -438,7 +495,7 @@ contract ConsensusRegistry is IConsensusRegistry, Initializable, Ownable2StepUpg function _verifyInputAddress(address _nodeOwner) private pure { if (_nodeOwner == address(0)) { - revert InvalidInputNodeOwnerAddress(); + revert ZeroAddress(); } } diff --git a/l2-contracts/contracts/L2ContractHelper.sol b/l2-contracts/contracts/L2ContractHelper.sol index 620e9b3ee..f367e33ab 100644 --- a/l2-contracts/contracts/L2ContractHelper.sol +++ b/l2-contracts/contracts/L2ContractHelper.sol @@ -55,6 +55,12 @@ interface IContractDeployer { /// @param _input the calldata to be sent to the constructor of the new contract function create2(bytes32 _salt, bytes32 _bytecodeHash, bytes calldata _input) external returns (address); + /// @notice Calculates the address of a create2 contract deployment + /// @param _sender The address of the sender. + /// @param _bytecodeHash The bytecode hash of the new contract to be deployed. + /// @param _salt a unique value to create the deterministic address of the new contract + /// @param _input the calldata to be sent to the constructor of the new contract + /// @return newAddress The derived address of the account. function getNewAddressCreate2( address _sender, bytes32 _bytecodeHash, @@ -82,6 +88,11 @@ interface IBaseToken { * the compression of the state diffs and bytecodes. */ interface ICompressor { + /// @notice Verifies that the compression of state diffs has been done correctly for the {_stateDiffs} param. + /// @param _numberOfStateDiffs The number of state diffs being checked. + /// @param _enumerationIndexSize Number of bytes used to represent an enumeration index for repeated writes. + /// @param _stateDiffs Encoded full state diff structs. See the first dev comment below for encoding. + /// @param _compressedStateDiffs The compressed state diffs function verifyCompressedStateDiffs( uint256 _numberOfStateDiffs, uint256 _enumerationIndexSize, @@ -170,7 +181,7 @@ library L2ContractHelper { /// - Bytecode bytes length is not a multiple of 32 /// - Bytecode bytes length is not less than 2^21 bytes (2^16 words) /// - Bytecode words length is not odd - function hashL2Bytecode(bytes calldata _bytecode) internal view returns (bytes32 hashedBytecode) { + function hashL2BytecodeCalldata(bytes calldata _bytecode) internal view returns (bytes32 hashedBytecode) { // Note that the length of the bytecode must be provided in 32-byte words. if (_bytecode.length % 32 != 0) { revert MalformedBytecode(BytecodeError.Length); @@ -201,7 +212,7 @@ library L2ContractHelper { /// - Bytecode bytes length is not a multiple of 32 /// - Bytecode bytes length is not less than 2^21 bytes (2^16 words) /// - Bytecode words length is not odd - function hashL2BytecodeMemory(bytes memory _bytecode) internal view returns (bytes32 hashedBytecode) { + function hashL2Bytecode(bytes memory _bytecode) internal pure returns (bytes32 hashedBytecode) { // Note that the length of the bytecode must be provided in 32-byte words. if (_bytecode.length % 32 != 0) { revert MalformedBytecode(BytecodeError.Length); diff --git a/l2-contracts/contracts/data-availability/StateDiffL2DAValidator.sol b/l2-contracts/contracts/data-availability/StateDiffL2DAValidator.sol index ab7d48636..249924058 100644 --- a/l2-contracts/contracts/data-availability/StateDiffL2DAValidator.sol +++ b/l2-contracts/contracts/data-availability/StateDiffL2DAValidator.sol @@ -68,7 +68,7 @@ abstract contract StateDiffL2DAValidator { reconstructedChainedL1BytecodesRevealDataHash = keccak256( abi.encode( reconstructedChainedL1BytecodesRevealDataHash, - L2ContractHelper.hashL2Bytecode( + L2ContractHelper.hashL2BytecodeCalldata( _totalL2ToL1PubdataAndStateDiffs[calldataPtr:calldataPtr + currentBytecodeLength] ) ) diff --git a/l2-contracts/contracts/errors/L2ContractErrors.sol b/l2-contracts/contracts/errors/L2ContractErrors.sol index bb16f38c6..89e548ea0 100644 --- a/l2-contracts/contracts/errors/L2ContractErrors.sol +++ b/l2-contracts/contracts/errors/L2ContractErrors.sol @@ -4,35 +4,25 @@ pragma solidity ^0.8.20; // 0x1f73225f error AddressMismatch(address expected, address supplied); +// 0x1294e9e1 error AssetIdMismatch(bytes32 expected, bytes32 supplied); // 0x5e85ae73 error AmountMustBeGreaterThanZero(); -// 0xb4f54111 -error DeployFailed(); // 0x7138356f error EmptyAddress(); -// 0x1c25715b -error EmptyBytes32(); // 0x1bdfd505 error FailedToTransferTokens(address tokenContract, address to, uint256 amount); // 0x2a1b2dd8 error InsufficientAllowance(uint256 providedAllowance, uint256 requiredAmount); -// 0xcbd9d2e0 -error InvalidCaller(address); // 0xb4fa3fb3 error InvalidInput(); -// 0x0ac76f01 -error NonSequentialVersion(); // 0x8e4a23d6 error Unauthorized(address); -// 0x6e128399 -error Unimplemented(); -// 0xa4dde386 -error UnimplementedMessage(string message); // 0xff15b069 error UnsupportedPaymasterFlow(); // 0x750b219c error WithdrawFailed(); +// 0xcea34703 error MalformedBytecode(BytecodeError); enum BytecodeError { diff --git a/l2-contracts/contracts/interfaces/IConsensusRegistry.sol b/l2-contracts/contracts/interfaces/IConsensusRegistry.sol index a5e017484..632bdd60e 100644 --- a/l2-contracts/contracts/interfaces/IConsensusRegistry.sol +++ b/l2-contracts/contracts/interfaces/IConsensusRegistry.sol @@ -8,12 +8,12 @@ pragma solidity ^0.8.20; interface IConsensusRegistry { /// @dev Represents a consensus node. /// @param attesterLastUpdateCommit The latest `attestersCommit` where the node's attester attributes were updated. + /// @param validatorLastUpdateCommit The latest `validatorsCommit` where the node's validator attributes were updated. + /// @param nodeOwnerIdx Index of the node owner within the array of node owners. /// @param attesterLatest Attester attributes to read if `node.attesterLastUpdateCommit` < `attestersCommit`. /// @param attesterSnapshot Attester attributes to read if `node.attesterLastUpdateCommit` == `attestersCommit`. - /// @param validatorLastUpdateCommit The latest `validatorsCommit` where the node's validator attributes were updated. /// @param validatorLatest Validator attributes to read if `node.validatorLastUpdateCommit` < `validatorsCommit`. /// @param validatorSnapshot Validator attributes to read if `node.validatorLastUpdateCommit` == `validatorsCommit`. - /// @param nodeOwnerIdx Index of the node owner within the array of node owners. struct Node { uint32 attesterLastUpdateCommit; uint32 validatorLastUpdateCommit; @@ -97,24 +97,28 @@ interface IConsensusRegistry { error UnauthorizedOnlyOwnerOrNodeOwner(); error NodeOwnerExists(); error NodeOwnerDoesNotExist(); - error NodeOwnerNotFound(); error ValidatorPubKeyExists(); error AttesterPubKeyExists(); - error InvalidInputNodeOwnerAddress(); error InvalidInputBLS12_381PublicKey(); error InvalidInputBLS12_381Signature(); error InvalidInputSecp256k1PublicKey(); + error ZeroAttesterWeight(); + error ZeroValidatorWeight(); event NodeAdded( address indexed nodeOwner, + bool isValidatorActive, uint32 validatorWeight, BLS12_381PublicKey validatorPubKey, BLS12_381Signature validatorPoP, + bool isAttesterActive, uint32 attesterWeight, Secp256k1PublicKey attesterPubKey ); - event NodeDeactivated(address indexed nodeOwner); - event NodeActivated(address indexed nodeOwner); + event AttesterDeactivated(address indexed nodeOwner); + event ValidatorDeactivated(address indexed nodeOwner); + event AttesterActivated(address indexed nodeOwner); + event ValidatorActivated(address indexed nodeOwner); event NodeRemoved(address indexed nodeOwner); event NodeDeleted(address indexed nodeOwner); event NodeValidatorWeightChanged(address indexed nodeOwner, uint32 newWeight); @@ -126,16 +130,22 @@ interface IConsensusRegistry { function add( address _nodeOwner, + bool _isValidatorActive, uint32 _validatorWeight, BLS12_381PublicKey calldata _validatorPubKey, BLS12_381Signature calldata _validatorPoP, + bool _isAttesterActive, uint32 _attesterWeight, Secp256k1PublicKey calldata _attesterPubKey ) external; - function deactivate(address _nodeOwner) external; + function deactivateAttester(address _nodeOwner) external; - function activate(address _nodeOwner) external; + function deactivateValidator(address _nodeOwner) external; + + function activateAttester(address _nodeOwner) external; + + function activateValidator(address _nodeOwner) external; function remove(address _nodeOwner) external; @@ -158,4 +168,6 @@ interface IConsensusRegistry { function getAttesterCommittee() external view returns (CommitteeAttester[] memory); function getValidatorCommittee() external view returns (CommitteeValidator[] memory); + + function numNodes() external view returns (uint256); } diff --git a/l2-contracts/hardhat.config.ts b/l2-contracts/hardhat.config.ts index 235930123..5aa44b527 100644 --- a/l2-contracts/hardhat.config.ts +++ b/l2-contracts/hardhat.config.ts @@ -1,6 +1,7 @@ import "@matterlabs/hardhat-zksync-solc"; import "@matterlabs/hardhat-zksync-verify"; import "@nomicfoundation/hardhat-chai-matchers"; +import "@matterlabs/hardhat-zksync-node"; import "@nomiclabs/hardhat-ethers"; import "hardhat-typechain"; diff --git a/l2-contracts/package.json b/l2-contracts/package.json index 3c871ee3b..706d74bdb 100644 --- a/l2-contracts/package.json +++ b/l2-contracts/package.json @@ -6,6 +6,7 @@ "@matterlabs/hardhat-zksync-deploy": "^0.7.0", "@matterlabs/hardhat-zksync-solc": "^0.3.15", "@matterlabs/hardhat-zksync-verify": "^0.4.0", + "@matterlabs/hardhat-zksync-node": "^1.2.0", "@matterlabs/zksync-contracts": "^0.6.1", "@nomicfoundation/hardhat-chai-matchers": "^1.0.6", "@nomicfoundation/hardhat-ethers": "^3.0.4", @@ -36,6 +37,7 @@ "test:foundry": "forge test --zksync --gas-limit 2000000000", "clean": "hardhat clean", "test": "hardhat test", + "test-node": "hardhat node-zksync --tag 0.1.0-alpha.29", "verify": "hardhat run src/verify.ts", "deploy-testnet-paymaster-through-l1": "ts-node src/deploy-testnet-paymaster-through-l1.ts", "deploy-force-deploy-upgrader-through-l1": "ts-node src/deploy-force-deploy-upgrader-through-l1.ts", diff --git a/l2-contracts/test/consensusRegistry.test.ts b/l2-contracts/test/consensusRegistry.test.ts index 66c0309bd..e6c4fa639 100644 --- a/l2-contracts/test/consensusRegistry.test.ts +++ b/l2-contracts/test/consensusRegistry.test.ts @@ -49,8 +49,8 @@ describe("ConsensusRegistry", function () { // Prepare the node list. const numNodes = 10; for (let i = 0; i < numNodes; i++) { - const node = makeRandomNode(provider); - const nodeEntry = makeRandomNodeEntry(node, i); + const node = makeRandomNode(); + const nodeEntry = makeRandomNodeEntry(node, i + 1); nodes.push(node); nodeEntries.push(nodeEntry); } @@ -73,11 +73,14 @@ describe("ConsensusRegistry", function () { await ( await registry.add( nodeEntries[i].ownerAddr, + true, nodeEntries[i].validatorWeight, nodeEntries[i].validatorPubKey, nodeEntries[i].validatorPoP, + true, nodeEntries[i].attesterWeight, - nodeEntries[i].attesterPubKey + nodeEntries[i].attesterPubKey, + { gasLimit } ) ).wait(); } @@ -130,9 +133,11 @@ describe("ConsensusRegistry", function () { .connect(nonOwner) .add( ethers.Wallet.createRandom().address, + true, 0, { a: new Uint8Array(32), b: new Uint8Array(32), c: new Uint8Array(32) }, { a: new Uint8Array(32), b: new Uint8Array(16) }, + true, 0, { tag: new Uint8Array(1), x: new Uint8Array(32) }, { gasLimit } @@ -140,20 +145,36 @@ describe("ConsensusRegistry", function () { ).to.be.reverted; }); - it("Should allow owner to deactivate", async function () { + it("Should allow owner to deactivate attester", async function () { + const nodeOwner = nodeEntries[0].ownerAddr; + expect((await registry.nodes(nodeOwner)).attesterLatest.active).to.equal(true); + + await (await registry.connect(owner).deactivateAttester(nodeOwner, { gasLimit })).wait(); + expect((await registry.nodes(nodeOwner)).attesterLatest.active).to.equal(false); + + // Restore state. + await (await registry.connect(owner).activateAttester(nodeOwner, { gasLimit })).wait(); + }); + + it("Should allow owner to deactivate validator", async function () { const nodeOwner = nodeEntries[0].ownerAddr; expect((await registry.nodes(nodeOwner)).validatorLatest.active).to.equal(true); - await (await registry.connect(owner).deactivate(nodeOwner, { gasLimit })).wait(); + await (await registry.connect(owner).deactivateValidator(nodeOwner, { gasLimit })).wait(); expect((await registry.nodes(nodeOwner)).validatorLatest.active).to.equal(false); // Restore state. - await (await registry.connect(owner).activate(nodeOwner, { gasLimit })).wait(); + await (await registry.connect(owner).activateValidator(nodeOwner, { gasLimit })).wait(); + }); + + it("Should not allow nonOwner, nonNodeOwner to deactivate attester", async function () { + const nodeOwner = nodeEntries[0].ownerAddr; + await expect(registry.connect(nonOwner).deactivateAttester(nodeOwner, { gasLimit })).to.be.reverted; }); - it("Should not allow nonOwner, nonNodeOwner to deactivate", async function () { + it("Should not allow nonOwner, nonNodeOwner to deactivate validator", async function () { const nodeOwner = nodeEntries[0].ownerAddr; - await expect(registry.connect(nonOwner).deactivate(nodeOwner, { gasLimit })).to.be.reverted; + await expect(registry.connect(nonOwner).deactivateValidator(nodeOwner, { gasLimit })).to.be.reverted; }); it("Should change validator weight", async function () { @@ -209,13 +230,15 @@ describe("ConsensusRegistry", function () { }); it("Should not allow to add a node with a validator public key which already exist", async function () { - const newEntry = makeRandomNodeEntry(makeRandomNode(), 0); + const newEntry = makeRandomNodeEntry(makeRandomNode(), 1); await expect( registry.add( newEntry.ownerAddr, + true, newEntry.validatorWeight, nodeEntries[0].validatorPubKey, newEntry.validatorPoP, + true, newEntry.attesterWeight, newEntry.attesterPubKey, { gasLimit } @@ -224,13 +247,15 @@ describe("ConsensusRegistry", function () { }); it("Should not allow to add a node with an attester public key which already exist", async function () { - const newEntry = makeRandomNodeEntry(makeRandomNode(), 0); + const newEntry = makeRandomNodeEntry(makeRandomNode(), 1); await expect( registry.add( newEntry.ownerAddr, + true, newEntry.validatorWeight, newEntry.validatorPubKey, newEntry.validatorPoP, + true, newEntry.attesterWeight, nodeEntries[0].attesterPubKey, { gasLimit } @@ -284,7 +309,8 @@ describe("ConsensusRegistry", function () { const entry = nodeEntries[idx]; // Deactivate attribute. - await (await registry.deactivate(entry.ownerAddr, { gasLimit })).wait(); + await (await registry.deactivateAttester(entry.ownerAddr, { gasLimit })).wait(); + await (await registry.deactivateValidator(entry.ownerAddr, { gasLimit })).wait(); // Verify no change. expect((await registry.getAttesterCommittee()).length).to.equal(nodes.length); @@ -301,7 +327,8 @@ describe("ConsensusRegistry", function () { expect((await registry.getValidatorCommittee()).length).to.equal(nodes.length - 1); // Restore state. - await (await registry.activate(entry.ownerAddr, { gasLimit })).wait(); + await (await registry.activateAttester(entry.ownerAddr, { gasLimit })).wait(); + await (await registry.activateValidator(entry.ownerAddr, { gasLimit })).wait(); await (await registry.commitAttesterCommittee({ gasLimit })).wait(); await (await registry.commitValidatorCommittee({ gasLimit })).wait(); }); @@ -332,9 +359,11 @@ describe("ConsensusRegistry", function () { await ( await registry.add( entry.ownerAddr, + true, entry.validatorWeight, entry.validatorPubKey, entry.validatorPoP, + true, entry.attesterWeight, entry.attesterPubKey ) @@ -426,9 +455,11 @@ describe("ConsensusRegistry", function () { await ( await registry.add( entry.ownerAddr, + true, entry.validatorWeight, entry.validatorPubKey, entry.validatorPoP, + true, entry.attesterWeight, entry.attesterPubKey ) diff --git a/l2-contracts/test/foundry/unit/data-availability/TestStateDiffComposer.sol b/l2-contracts/test/foundry/unit/data-availability/TestStateDiffComposer.sol index 05c639818..1806ed255 100644 --- a/l2-contracts/test/foundry/unit/data-availability/TestStateDiffComposer.sol +++ b/l2-contracts/test/foundry/unit/data-availability/TestStateDiffComposer.sol @@ -51,12 +51,12 @@ contract TestStateDiffComposer { ++bytecodesNumber; bytecodes = bytes.concat(bytecodes, bytes4(uint32(bytecode.length)), bytecode); currentRollingBytecodesHash = keccak256( - abi.encode(currentRollingBytecodesHash, L2ContractHelper.hashL2BytecodeMemory(bytecode)) + abi.encode(currentRollingBytecodesHash, L2ContractHelper.hashL2Bytecode(bytecode)) ); } if (includeToCorrectHash) { correctRollingBytecodesHash = keccak256( - abi.encode(correctRollingBytecodesHash, L2ContractHelper.hashL2BytecodeMemory(bytecode)) + abi.encode(correctRollingBytecodesHash, L2ContractHelper.hashL2Bytecode(bytecode)) ); } } diff --git a/l2-contracts/test/foundry/unit/data-availability/ValidiumL2DAValidator.t.sol b/l2-contracts/test/foundry/unit/data-availability/ValidiumL2DAValidator.t.sol index 3374e1acc..a0ab30720 100644 --- a/l2-contracts/test/foundry/unit/data-availability/ValidiumL2DAValidator.t.sol +++ b/l2-contracts/test/foundry/unit/data-availability/ValidiumL2DAValidator.t.sol @@ -2,8 +2,6 @@ pragma solidity ^0.8.20; -// solhint-disable gas-custom-errors - import {Test} from "forge-std/Test.sol"; import {ValidiumL2DAValidator} from "contracts/data-availability/ValidiumL2DAValidator.sol"; diff --git a/system-contracts/README.md b/system-contracts/README.md index 4058a356b..95006fe79 100644 --- a/system-contracts/README.md +++ b/system-contracts/README.md @@ -148,12 +148,6 @@ Since scripts, READMEs, etc., are code that is not subject to audits, these are branch. The rest of the release branches as well as the `dev` branch should merge `main` to synchronize with these changes. -## License - -The ZKsync Era system-contracts are distributed under the terms of the MIT license. - -See [LICENSE-MIT](LICENSE-MIT) for details. - ## Official Links - [Website](https://zksync.io/) diff --git a/system-contracts/SystemContractsHashes.json b/system-contracts/SystemContractsHashes.json index 163458f1f..a6dec1ede 100644 --- a/system-contracts/SystemContractsHashes.json +++ b/system-contracts/SystemContractsHashes.json @@ -3,49 +3,49 @@ "contractName": "AccountCodeStorage", "bytecodePath": "artifacts-zk/contracts-preprocessed/AccountCodeStorage.sol/AccountCodeStorage.json", "sourceCodePath": "contracts-preprocessed/AccountCodeStorage.sol", - "bytecodeHash": "0x0100005d3ae95fb62791ed4693e614755bd780011ffc3d2dea8344fb1284f9df", + "bytecodeHash": "0x0100005df535e7d1e6f3933b26076778d9c44fd6e7faf546732f08290d8c8f94", "sourceCodeHash": "0x2e0e09d57a04bd1e722d8bf8c6423fdf3f8bca44e5e8c4f6684f987794be066e" }, { "contractName": "BootloaderUtilities", "bytecodePath": "artifacts-zk/contracts-preprocessed/BootloaderUtilities.sol/BootloaderUtilities.json", "sourceCodePath": "contracts-preprocessed/BootloaderUtilities.sol", - "bytecodeHash": "0x010007c7daac9a547e1e20ed650b09b21668c3fb49e23cea5113dd8cb224b9ac", + "bytecodeHash": "0x010007c72b7f29a0e1954ee4c65e6598d0934d33c692faedd7ac4fe30b508fa3", "sourceCodeHash": "0x0f1213c4b95acb71f4ab5d4082cc1aeb2bd5017e1cccd46afc66e53268609d85" }, { "contractName": "ComplexUpgrader", "bytecodePath": "artifacts-zk/contracts-preprocessed/ComplexUpgrader.sol/ComplexUpgrader.json", "sourceCodePath": "contracts-preprocessed/ComplexUpgrader.sol", - "bytecodeHash": "0x0100004de3ddc8c5296fed145323ba1d6874af80469e40657bf0ff79d113ccb5", - "sourceCodeHash": "0x796046a914fb676ba2bbd337b2924311ee2177ce54571c18a2c3945755c83614" + "bytecodeHash": "0x010000bf6fcec0995b82b1c51133a507c8f63111234530b69fe7dadaae0c8172", + "sourceCodeHash": "0xfcc74aefbc7cbde7945c29bad0e47527ac443bd6b75251a4ae520e28c714af37" }, { "contractName": "Compressor", "bytecodePath": "artifacts-zk/contracts-preprocessed/Compressor.sol/Compressor.json", "sourceCodePath": "contracts-preprocessed/Compressor.sol", - "bytecodeHash": "0x0100014b3784efd0fbc6825fa84f3dcf9fc1dcbed37a681c57098c347527ba21", + "bytecodeHash": "0x0100014b2cac967629cb05fb59a5c77cb5a077b74c50521ed9216a59511bf182", "sourceCodeHash": "0x7240b5fb2ea8e184522e731fb14f764ebae52b8a69d1870a55daedac9a3ed617" }, { "contractName": "ContractDeployer", "bytecodePath": "artifacts-zk/contracts-preprocessed/ContractDeployer.sol/ContractDeployer.json", "sourceCodePath": "contracts-preprocessed/ContractDeployer.sol", - "bytecodeHash": "0x010004e522c95733920e0a1f072b5dc36dd3d6a1b30515de48423575c10a8f7e", + "bytecodeHash": "0x010004e5a266e697bb45bc90ff310dcb293725006146ff83e46bde8f3c6b44fa", "sourceCodeHash": "0x92bc09da23ed9d86ba7a84f0dbf48503c99582ae58cdbebbdcc5f14ea1fcf014" }, { "contractName": "Create2Factory", "bytecodePath": "artifacts-zk/contracts-preprocessed/Create2Factory.sol/Create2Factory.json", "sourceCodePath": "contracts-preprocessed/Create2Factory.sol", - "bytecodeHash": "0x01000049a4e4beb07895adcdcf34186af3d28a9f3c1d9b56c72c8464730755f1", - "sourceCodeHash": "0x114d9322a9ca654989f3e0b3b21f1311dbc4db84f443d054cd414f6414d84de3" + "bytecodeHash": "0x010000493a391e65a70dea42442132cf7c7001dac94388b9c4218ce9b1491b57", + "sourceCodeHash": "0x97392413259e6aae5187768cefd734507460ae818d6975709cc9b4e15a9af906" }, { "contractName": "DefaultAccount", "bytecodePath": "artifacts-zk/contracts-preprocessed/DefaultAccount.sol/DefaultAccount.json", "sourceCodePath": "contracts-preprocessed/DefaultAccount.sol", - "bytecodeHash": "0x0100055d3993e14104994ca4d8cfa91beb9b544ee86894b45708b4824d832ff2", + "bytecodeHash": "0x0100055d74f7387e03ecbb5209bea7e0318aea05cfaaa1c195a85df100115cea", "sourceCodeHash": "0xebffe840ebbd9329edb1ebff8ca50f6935e7dabcc67194a896fcc2e968d46dfb" }, { @@ -59,78 +59,85 @@ "contractName": "ImmutableSimulator", "bytecodePath": "artifacts-zk/contracts-preprocessed/ImmutableSimulator.sol/ImmutableSimulator.json", "sourceCodePath": "contracts-preprocessed/ImmutableSimulator.sol", - "bytecodeHash": "0x010000394846da43b9adfe72f0820c19d39daaf861e2eae55d6fe248840f641e", + "bytecodeHash": "0x0100003946a9e538157e73717201b8cd17af70998602a3692b0ac1eff6ad850e", "sourceCodeHash": "0x9659e69f7db09e8f60a8bb95314b1ed26afcc689851665cf27f5408122f60c98" }, { "contractName": "KnownCodesStorage", "bytecodePath": "artifacts-zk/contracts-preprocessed/KnownCodesStorage.sol/KnownCodesStorage.json", "sourceCodePath": "contracts-preprocessed/KnownCodesStorage.sol", - "bytecodeHash": "0x0100006f1fa761c40d5b3325482c8bc9a577ac65278b624523b67eb99cf7e51c", + "bytecodeHash": "0x0100006f1ab2c7415de3914a2b9c53942cd3ff6471f698e7383b59f51e33e4d3", "sourceCodeHash": "0xb39b5b81168653e0c5062f7b8e1d6d15a4e186df3317f192f0cb2fc3a74f5448" }, { "contractName": "L1Messenger", "bytecodePath": "artifacts-zk/contracts-preprocessed/L1Messenger.sol/L1Messenger.json", "sourceCodePath": "contracts-preprocessed/L1Messenger.sol", - "bytecodeHash": "0x010001f74edfe69d83816cc586cbb42b2a37d2649dcd1cab88052a37dffaadf3", - "sourceCodeHash": "0x8d22a4019347a45cb0c27bed9e98f7033637a7bdcd90fafb1922caa48f2b05de" + "bytecodeHash": "0x010001f74f7e45f40e1acbae30507ef94ea2775026a6ba0d0eb38cce10e4a472", + "sourceCodeHash": "0xe97846e4ff5f1cfffd6a454f5ad278deecf6fd7a67525908dea9af877dc822a9" }, { "contractName": "L2BaseToken", "bytecodePath": "artifacts-zk/contracts-preprocessed/L2BaseToken.sol/L2BaseToken.json", "sourceCodePath": "contracts-preprocessed/L2BaseToken.sol", - "bytecodeHash": "0x0100010395d69e52583bf981c6eb16a7f45a4e930671c69df04e24c58dba3648", + "bytecodeHash": "0x01000103bbfa393b49b9f8a7adcfedf1273b7928750f3ea8798347dfd8ca0d6f", "sourceCodeHash": "0x8bdd2b4d0b53dba84c9f0af250bbaa2aad10b3de6747bba957f0bd3721090dfa" }, { "contractName": "L2GatewayUpgrade", "bytecodePath": "artifacts-zk/contracts-preprocessed/L2GatewayUpgrade.sol/L2GatewayUpgrade.json", "sourceCodePath": "contracts-preprocessed/L2GatewayUpgrade.sol", - "bytecodeHash": "0x0100019db8d039fb6ef02a7aea5eb8cbfd917afdf3dc88659f28e18b6a43e5df", - "sourceCodeHash": "0xc69d0c1819a366fc91a43a9ad2d747540a7b8ee2071b48e4adfd301ec40e8600" + "bytecodeHash": "0x0100038b3b4065d2682996020e14177a9b4632e054b6718f68d46ff13c012b20", + "sourceCodeHash": "0x9248f46f491b8853da77e8f9787cfc1a136abee90fde18a3b8f47dcb8859c63c" + }, + { + "contractName": "L2GatewayUpgradeHelper", + "bytecodePath": "artifacts-zk/contracts-preprocessed/L2GatewayUpgradeHelper.sol/L2GatewayUpgradeHelper.json", + "sourceCodePath": "contracts-preprocessed/L2GatewayUpgradeHelper.sol", + "bytecodeHash": "0x010000071330ec1656098ed33e28b475e101394550c02907d7ee2abbae9b762e", + "sourceCodeHash": "0xd1c42c4d338697b8effbfe22a0f07d8d9c5a06c8ec8f45deae77765af48a355b" }, { "contractName": "L2GenesisUpgrade", "bytecodePath": "artifacts-zk/contracts-preprocessed/L2GenesisUpgrade.sol/L2GenesisUpgrade.json", "sourceCodePath": "contracts-preprocessed/L2GenesisUpgrade.sol", - "bytecodeHash": "0x010000fbf45473bbd4c0ef708beb28c5f40c10b22b0a289feb4ccbce9b7ae825", - "sourceCodeHash": "0xe21a58d96b2727020958e95605764b84f7f2f3cc4e0c01c4cdf2854f882d41ca" - }, - { - "contractName": "L2GenesisUpgradeHelper", - "bytecodePath": "artifacts-zk/contracts-preprocessed/L2GenesisUpgradeHelper.sol/L2GenesisUpgradeHelper.json", - "sourceCodePath": "contracts-preprocessed/L2GenesisUpgradeHelper.sol", - "bytecodeHash": "0x01000007e61dc52f7aff33c2c209b51ab7fbaf9b4668980f076fdabb24934f97", - "sourceCodeHash": "0xc2fd787a23e7935f8109f3eb35b71853fe3a9acf5cd96138afcb0e5b65002ba3" + "bytecodeHash": "0x010001b386e0ed48ce9fbaad09c7865a58c28c8350d9bc9446b3beaee4aee999", + "sourceCodeHash": "0x2aaddd8a8ef3f56b4f4e6ba52c0035572145b0ea562fbf218a2eb5fc462f988d" }, { "contractName": "MsgValueSimulator", "bytecodePath": "artifacts-zk/contracts-preprocessed/MsgValueSimulator.sol/MsgValueSimulator.json", "sourceCodePath": "contracts-preprocessed/MsgValueSimulator.sol", - "bytecodeHash": "0x0100005d895eb5ad625c93a99c3796c18e8fda2e34e9af6997c5208aea197cc2", + "bytecodeHash": "0x0100005df63cf8940e407a67346b406dcddf4788cba9792ecd6a0edb8d8b3bd8", "sourceCodeHash": "0x082f3dcbc2fe4d93706c86aae85faa683387097d1b676e7ebd00f71ee0f13b71" }, { "contractName": "NonceHolder", "bytecodePath": "artifacts-zk/contracts-preprocessed/NonceHolder.sol/NonceHolder.json", "sourceCodePath": "contracts-preprocessed/NonceHolder.sol", - "bytecodeHash": "0x010000d9515266d6a161d41fe0789fe8e75a31a3d8c0ce915ed09fa4ffcd7c61", + "bytecodeHash": "0x010000d9e79c30aeda9b823f1a0161c7637ed50848e6287e2a34e37cf2e7e4e8", "sourceCodeHash": "0xcd0c0366effebf2c98c58cf96322cc242a2d1c675620ef5514b7ed1f0a869edc" }, { "contractName": "PubdataChunkPublisher", "bytecodePath": "artifacts-zk/contracts-preprocessed/PubdataChunkPublisher.sol/PubdataChunkPublisher.json", "sourceCodePath": "contracts-preprocessed/PubdataChunkPublisher.sol", - "bytecodeHash": "0x010000491ab9335e1a112a136580f1f1b2c2929d11be12aed00fd94925bc3fc1", - "sourceCodeHash": "0x04d3d2e4019081c87aae5c22a060d84ae2e9d631ebce59801ecce37b9c87e4c7" + "bytecodeHash": "0x01000049377ba719b2d7493420854f12ebe67b75e21338777fb22b73e58ec057", + "sourceCodeHash": "0x398b1b9325b39d4c31e672866d4cbdf1cab453fae8d29f438262d921d427f094" + }, + { + "contractName": "SloadContract", + "bytecodePath": "artifacts-zk/contracts-preprocessed/SloadContract.sol/SloadContract.json", + "sourceCodePath": "contracts-preprocessed/SloadContract.sol", + "bytecodeHash": "0x01000011322222fc9712efbf569d3477e80ca5903c708b395142e88f654641b4", + "sourceCodeHash": "0xb4debf46dd512f6cf4fb349bf2ce680f73fe25eb3550590261f31b8f00f78c03" }, { "contractName": "SystemContext", "bytecodePath": "artifacts-zk/contracts-preprocessed/SystemContext.sol/SystemContext.json", "sourceCodePath": "contracts-preprocessed/SystemContext.sol", - "bytecodeHash": "0x010001a7baaabeaf80186c0dec134f606186fa9f73f91e753806b424ca8f171f", - "sourceCodeHash": "0xb3b8c1f57928938ac590984442bc96c2c888282793014845d5ce2f90bbf2677f" + "bytecodeHash": "0x0100017f235b172e9a808764229a777b027e179eacc88a7ea48ef81cb193630a", + "sourceCodeHash": "0x22406893d61abd477ce071dce506cf2534cca7b7717d015769fc8af1f1b80e06" }, { "contractName": "EventWriter", @@ -199,35 +206,35 @@ "contractName": "bootloader_test", "bytecodePath": "bootloader/build/artifacts/bootloader_test.yul.zbin", "sourceCodePath": "bootloader/build/bootloader_test.yul", - "bytecodeHash": "0x010003cb2fe407ac312db0aa6a6e746ca41cd19ab0eea216a14ec725f5cc7444", - "sourceCodeHash": "0xd7748f25eeb4f17b5d5bc09172f09ffdd9b8a34d011b3fb62aac5b494231b168" + "bytecodeHash": "0x010003d74b175f9f9721d181430a694a7d1e6714a523072141a4a96010e2ae42", + "sourceCodeHash": "0xf44341122d04745a6935f5070a3e53d99ef4e8d1ff8c8e4337e0ea4dfe31a69b" }, { "contractName": "fee_estimate", "bytecodePath": "bootloader/build/artifacts/fee_estimate.yul.zbin", "sourceCodePath": "bootloader/build/fee_estimate.yul", - "bytecodeHash": "0x01000931a58a1d205bdf0b87674e56f96bb5f2192173c96a07886121b6867c47", - "sourceCodeHash": "0x67877a2bd129d189c32e63333325fff1e0ee19650a270b6bfa55906e1eaa79d6" + "bytecodeHash": "0x01000931efb40296b642759fe7e440e92dcff1be45ef1288e78b72c88c629f8b", + "sourceCodeHash": "0xae273f1f71c1fd425d781f8286fde074274664c14b7f48265169679bef8c9e49" }, { "contractName": "gas_test", "bytecodePath": "bootloader/build/artifacts/gas_test.yul.zbin", "sourceCodePath": "bootloader/build/gas_test.yul", - "bytecodeHash": "0x010008b7e13ae7b54e537ea6f7b4e030f7b3c81e44b05f41dea2eb13c19e6235", - "sourceCodeHash": "0xa173ad90cabe1b3431ee803b2c9b3943ece686c98df1600dad4cec28f5a027c8" + "bytecodeHash": "0x010008b754dd6c69f0f480639f44e73ab7fd933b2929c0d000725687ccb1222f", + "sourceCodeHash": "0x8bd6c1bf35cf6204967ea50d98da4088524502a9363c57c9e4b1d0a0d31372d8" }, { "contractName": "playground_batch", "bytecodePath": "bootloader/build/artifacts/playground_batch.yul.zbin", "sourceCodePath": "bootloader/build/playground_batch.yul", - "bytecodeHash": "0x010009358206ce648b88a76f3199a3ea0c0e1183a9ebfca11cdcba924453db98", - "sourceCodeHash": "0xda17354bca78e6b816ce8f7d1d7ff45e1c5ed0cd9f6ea0437b7cac614ff2019c" + "bytecodeHash": "0x01000935c8fb0c8b01322788e8f82e13344199d56139becd3e5392a682f5f43f", + "sourceCodeHash": "0xaabdd037c9ebc7541c8a847ebb4dd16624eb18450e4faec65026992b86d8f294" }, { "contractName": "proved_batch", "bytecodePath": "bootloader/build/artifacts/proved_batch.yul.zbin", "sourceCodePath": "bootloader/build/proved_batch.yul", - "bytecodeHash": "0x010008c753336bc8d1ddca235602b9f31d346412b2d463cd342899f7bfb73baf", - "sourceCodeHash": "0x7a5776e8001a2d93e14165af0b08cadcf1170354401d0c31fdc0d2a8f8439989" + "bytecodeHash": "0x010008c79fe70427642db69b14314af076e5d54f1dada975b905bcbb5feb9f9e", + "sourceCodeHash": "0xf8f84fe15ef78e170f6649f12920266c9afe3d29b867d2f5fd28b672bd13e9a3" } ] diff --git a/system-contracts/bootloader/bootloader.yul b/system-contracts/bootloader/bootloader.yul index 1c58a3bf7..36d2697f2 100644 --- a/system-contracts/bootloader/bootloader.yul +++ b/system-contracts/bootloader/bootloader.yul @@ -193,7 +193,7 @@ object "Bootloader" { /// @dev The maximum number of new factory deps that are allowed in a transaction function MAX_NEW_FACTORY_DEPS() -> ret { - ret := 32 + ret := 64 } /// @dev Besides the factory deps themselves, we also need another 4 slots for: @@ -3900,12 +3900,12 @@ object "Bootloader" { /// @dev Log key used by Executor.sol for processing. See Constants.sol::SystemLogKey enum function chainedPriorityTxnHashLogKey() -> ret { - ret := 3 + ret := 2 } /// @dev Log key used by Executor.sol for processing. See Constants.sol::SystemLogKey enum function numberOfLayer1TxsLogKey() -> ret { - ret := 4 + ret := 3 } /// @dev Log key used by Executor.sol for processing. See Constants.sol::SystemLogKey enum diff --git a/system-contracts/contracts/ComplexUpgrader.sol b/system-contracts/contracts/ComplexUpgrader.sol index a69545148..8c965d6a5 100644 --- a/system-contracts/contracts/ComplexUpgrader.sol +++ b/system-contracts/contracts/ComplexUpgrader.sol @@ -3,7 +3,8 @@ pragma solidity 0.8.24; import {IComplexUpgrader} from "./interfaces/IComplexUpgrader.sol"; -import {FORCE_DEPLOYER} from "./Constants.sol"; +import {ForceDeployment} from "./interfaces/IContractDeployer.sol"; +import {FORCE_DEPLOYER, DEPLOYER_SYSTEM_CONTRACT} from "./Constants.sol"; import {Unauthorized, AddressHasNoCode} from "./SystemContractErrors.sol"; /** @@ -13,17 +14,42 @@ import {Unauthorized, AddressHasNoCode} from "./SystemContractErrors.sol"; * this logic should be deployed into the user space and then this contract will delegatecall to the deployed contract. */ contract ComplexUpgrader is IComplexUpgrader { + /// @notice Ensures that only the `FORCE_DEPLOYER` can call the function. + /// @dev Note that it is vital to put this modifier at the start of *each* function, + /// since even temporary anauthorized access can be dangerous. + modifier onlyForceDeployer() { + // Note, that it is not + if (msg.sender != FORCE_DEPLOYER) { + revert Unauthorized(msg.sender); + } + _; + } + /// @notice Executes an upgrade process by delegating calls to another contract. /// @dev This function allows only the `FORCE_DEPLOYER` to initiate the upgrade. /// If the delegate call fails, the function will revert the transaction, returning the error message /// provided by the delegated contract. + /// @param _forceDeployments the list of initial deployments that should be performed before the upgrade. + /// They would typically, though not necessarily include the deployment of the upgrade implementation itself. /// @param _delegateTo the address of the contract to which the calls will be delegated /// @param _calldata the calldata to be delegate called in the `_delegateTo` contract - function upgrade(address _delegateTo, bytes calldata _calldata) external payable { - if (msg.sender != FORCE_DEPLOYER) { - revert Unauthorized(msg.sender); - } + function forceDeployAndUpgrade( + ForceDeployment[] calldata _forceDeployments, + address _delegateTo, + bytes calldata _calldata + ) external payable override onlyForceDeployer { + DEPLOYER_SYSTEM_CONTRACT.forceDeployOnAddresses(_forceDeployments); + upgrade(_delegateTo, _calldata); + } + + /// @notice Executes an upgrade process by delegating calls to another contract. + /// @dev This function allows only the `FORCE_DEPLOYER` to initiate the upgrade. + /// If the delegate call fails, the function will revert the transaction, returning the error message + /// provided by the delegated contract. + /// @param _delegateTo the address of the contract to which the calls will be delegated + /// @param _calldata the calldata to be delegate called in the `_delegateTo` contract + function upgrade(address _delegateTo, bytes calldata _calldata) public payable onlyForceDeployer { if (_delegateTo.code.length == 0) { revert AddressHasNoCode(_delegateTo); } diff --git a/system-contracts/contracts/Constants.sol b/system-contracts/contracts/Constants.sol index 072c6eab9..4d1d5dad8 100644 --- a/system-contracts/contracts/Constants.sol +++ b/system-contracts/contracts/Constants.sol @@ -16,6 +16,7 @@ import {IComplexUpgrader} from "./interfaces/IComplexUpgrader.sol"; import {IBootloaderUtilities} from "./interfaces/IBootloaderUtilities.sol"; import {IPubdataChunkPublisher} from "./interfaces/IPubdataChunkPublisher.sol"; import {IMessageRoot} from "./interfaces/IMessageRoot.sol"; +import {ICreate2Factory} from "./interfaces/ICreate2Factory.sol"; /// @dev All the system contracts introduced by ZKsync have their addresses /// started from 2^15 in order to avoid collision with Ethereum precompiles. @@ -73,10 +74,16 @@ address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0 IBaseToken constant BASE_TOKEN_SYSTEM_CONTRACT = IBaseToken(address(SYSTEM_CONTRACTS_OFFSET + 0x0a)); IBaseToken constant REAL_BASE_TOKEN_SYSTEM_CONTRACT = IBaseToken(address(REAL_SYSTEM_CONTRACTS_OFFSET + 0x0a)); +ICreate2Factory constant L2_CREATE2_FACTORY = ICreate2Factory(address(USER_CONTRACTS_OFFSET)); address constant L2_ASSET_ROUTER = address(USER_CONTRACTS_OFFSET + 0x03); IBridgehub constant L2_BRIDGE_HUB = IBridgehub(address(USER_CONTRACTS_OFFSET + 0x02)); address constant L2_NATIVE_TOKEN_VAULT_ADDR = address(USER_CONTRACTS_OFFSET + 0x04); IMessageRoot constant L2_MESSAGE_ROOT = IMessageRoot(address(USER_CONTRACTS_OFFSET + 0x05)); +// Note, that on its own this contract does not provide much functionality, but having it on a constant address +// serves as a convenient storage for its bytecode to be accessible via `extcodehash`. +address constant SLOAD_CONTRACT_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x06); + +address constant WRAPPED_BASE_TOKEN_IMPL_ADDRESS = address(USER_CONTRACTS_OFFSET + 0x07); // Hardcoded because even for tests we should keep the address. (Instead `SYSTEM_CONTRACTS_OFFSET + 0x10`) // Precompile call depends on it. @@ -119,9 +126,12 @@ uint256 constant STATE_DIFF_ENTRY_SIZE = 272; enum SystemLogKey { L2_TO_L1_LOGS_TREE_ROOT_KEY, PACKED_BATCH_AND_L2_BLOCK_TIMESTAMP_KEY, - PREV_BATCH_HASH_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 diff --git a/system-contracts/contracts/Create2Factory.sol b/system-contracts/contracts/Create2Factory.sol index 868de66fa..8541e3406 100644 --- a/system-contracts/contracts/Create2Factory.sol +++ b/system-contracts/contracts/Create2Factory.sol @@ -5,11 +5,12 @@ pragma solidity 0.8.24; import {REAL_DEPLOYER_SYSTEM_CONTRACT} from "./Constants.sol"; import {EfficientCall} from "./libraries/EfficientCall.sol"; import {IContractDeployer} from "./interfaces/IContractDeployer.sol"; +import {ICreate2Factory} from "./interfaces/ICreate2Factory.sol"; /// @custom:security-contact security@matterlabs.dev /// @author Matter Labs /// @notice The contract that can be used for deterministic contract deployment. -contract Create2Factory { +contract Create2Factory is ICreate2Factory { /// @notice Function that calls the `create2` method of the `ContractDeployer` contract. /// @dev This function accepts the same parameters as the `create2` function of the ContractDeployer system contract, /// so that we could efficiently relay the calldata. diff --git a/system-contracts/contracts/L1Messenger.sol b/system-contracts/contracts/L1Messenger.sol index 0f9242ef1..1f0cfe8e5 100644 --- a/system-contracts/contracts/L1Messenger.sol +++ b/system-contracts/contracts/L1Messenger.sol @@ -186,6 +186,7 @@ contract L1Messenger is IL1Messenger, SystemContractBase { /// @notice Verifies that the {_operatorInput} reflects what occurred within the L1Batch and that /// the compressed statediffs are equivalent to the full state diffs. + /// @param _l2DAValidator the address of the l2 da validator /// @param _operatorInput The total pubdata and uncompressed state diffs of transactions that were /// processed in the current L1 Batch. Pubdata consists of L2 to L1 Logs, messages, deployed bytecode, and state diffs. /// @dev Function that should be called exactly once per L1 Batch by the bootloader. diff --git a/system-contracts/contracts/L2GatewayUpgrade.sol b/system-contracts/contracts/L2GatewayUpgrade.sol index bef6009ae..e16629e77 100644 --- a/system-contracts/contracts/L2GatewayUpgrade.sol +++ b/system-contracts/contracts/L2GatewayUpgrade.sol @@ -2,37 +2,42 @@ pragma solidity 0.8.24; -import {DEPLOYER_SYSTEM_CONTRACT} from "./Constants.sol"; -import {IContractDeployer, ForceDeployment} from "./interfaces/IContractDeployer.sol"; import {SystemContractHelper} from "./libraries/SystemContractHelper.sol"; import {FixedForceDeploymentsData, ZKChainSpecificForceDeploymentsData} from "./interfaces/IL2GenesisUpgrade.sol"; -import {L2GenesisUpgradeHelper} from "./L2GenesisUpgradeHelper.sol"; +import {L2GatewayUpgradeHelper} from "./L2GatewayUpgradeHelper.sol"; import {ITransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; import {IL2SharedBridgeLegacy} from "./interfaces/IL2SharedBridgeLegacy.sol"; import {UpgradeableBeacon} from "@openzeppelin/contracts-v4/proxy/beacon/UpgradeableBeacon.sol"; +import {IERC20Metadata} from "@openzeppelin/contracts-v4/token/ERC20/extensions/IERC20Metadata.sol"; +import {WRAPPED_BASE_TOKEN_IMPL_ADDRESS} from "./Constants.sol"; + +/// @dev Storage slot with the admin of the contract used for EIP1967 proxies (e.g., TUP, BeaconProxy, etc.). +bytes32 constant PROXY_ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /// @custom:security-contact security@matterlabs.dev /// @author Matter Labs -/// @notice The contract that is used for facilitating the upgrade of the L2 -/// to the protocol version that supports gateway -/// @dev This contract is neither predeployed nor a system contract. It is located -/// in this folder due to very overlapping functionality with `L2GenesisUpgrade` and -/// facilitating reusage of the code. -/// @dev During the upgrade, it will be delegate-called by the `ComplexUpgrader` contract. +/// @title L2GatewayUpgrade +/// @notice Facilitates the upgrade of the L2 protocol to a version that supports the gateway. +/// @dev This contract is neither predeployed nor a system contract. It resides in this folder due to overlapping functionality with `L2GenesisUpgrade` and to facilitate code reuse. +/// @dev During the upgrade process, this contract will be force-deployed onto the address of the `ComplexUpgrader` system contract, so +/// `this` will take the address of the `ComplexUpgrader`. This approach is used instead of delegate-calling `ComplexUpgrader` +/// to alleviate the need to predeploy the implementation. In the future this limitation will be removed with the new `ComplexUpgrader` +/// functionality. +/// @dev All the logic happens inside the constructor, since once the constructor execution is done, the normal `ComplexUpgrader` +/// bytecode will be deployed back in its place. contract L2GatewayUpgrade { - function upgrade( - ForceDeployment[] calldata _forceDeployments, + /// @notice Initializes the `L2GatewayUpgrade` contract. + /// @dev This constructor is intended to be delegate-called by the `ComplexUpgrader` contract. + /// @param _ctmDeployer Address of the CTM Deployer contract. + /// @param _fixedForceDeploymentsData Encoded data for fixed force deployments. + /// @param _additionalForceDeploymentsData Encoded data for ZK-Chain specific force deployments. + constructor( address _ctmDeployer, - bytes calldata _fixedForceDeploymentsData, - bytes calldata _additionalForceDeploymentsData - ) external payable { - // Firstly, we force deploy the main set of contracts. - // Those will be deployed without any contract invocation. - IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).forceDeployOnAddresses{value: msg.value}(_forceDeployments); - - // Secondly, we perform the more complex deployment of the gateway contracts. - L2GenesisUpgradeHelper.performForceDeployedContractsInit( + bytes memory _fixedForceDeploymentsData, + bytes memory _additionalForceDeploymentsData + ) { + L2GatewayUpgradeHelper.performForceDeployedContractsInit( _ctmDeployer, _fixedForceDeploymentsData, _additionalForceDeploymentsData @@ -43,36 +48,82 @@ contract L2GatewayUpgrade { (ZKChainSpecificForceDeploymentsData) ); - address l2LegacyBridgeAddress = additionalForceDeploymentsData.l2LegacySharedBridge; + FixedForceDeploymentsData memory fixedForceDeploymentsData = abi.decode( + _fixedForceDeploymentsData, + (FixedForceDeploymentsData) + ); + address l2LegacyBridgeAddress = additionalForceDeploymentsData.l2LegacySharedBridge; if (l2LegacyBridgeAddress != address(0)) { - FixedForceDeploymentsData memory fixedForceDeploymentsData = abi.decode( - _fixedForceDeploymentsData, - (FixedForceDeploymentsData) - ); - - // Firstly, upgrade the legacy L2SharedBridge - bytes memory bridgeUpgradeData = abi.encodeCall( - ITransparentUpgradeableProxy.upgradeTo, - (fixedForceDeploymentsData.l2SharedBridgeLegacyImpl) - ); - SystemContractHelper.mimicCallWithPropagatedRevert( + // Force upgrade the TransparentUpgradeableProxy for the legacy bridge. + forceUpgradeTransparentProxy( l2LegacyBridgeAddress, - fixedForceDeploymentsData.l2BridgeProxyOwnerAddress, - bridgeUpgradeData + // We are sure that `impl` is deployed, since it is supposed to be included + // as part of the "usual" force deployments array. + fixedForceDeploymentsData.l2SharedBridgeLegacyImpl, + hex"" ); - // Secondly, upgrade the tokens - UpgradeableBeacon upgradableBeacon = IL2SharedBridgeLegacy(l2LegacyBridgeAddress).l2TokenBeacon(); - bytes memory beaconUpgradeData = abi.encodeCall( - UpgradeableBeacon.upgradeTo, - (fixedForceDeploymentsData.l2BridgedStandardERC20Impl) + // Force upgrade the UpgradeableBeacon proxy for the bridged standard ERC20. + forceUpgradeBeaconProxy( + address(IL2SharedBridgeLegacy(l2LegacyBridgeAddress).l2TokenBeacon()), + // We are sure that `impl` is deployed, since it is supposed to be included + // as part of the "usual" force deployments array. + fixedForceDeploymentsData.l2BridgedStandardERC20Impl ); - SystemContractHelper.mimicCallWithPropagatedRevert( - address(upgradableBeacon), - fixedForceDeploymentsData.l2BridgedStandardERC20ProxyOwnerAddress, - beaconUpgradeData + } + + if (additionalForceDeploymentsData.predeployedL2WethAddress != address(0)) { + // Query the old data to avoid accidentally overwriting it. + string memory name = IERC20Metadata(additionalForceDeploymentsData.predeployedL2WethAddress).name(); + string memory symbol = IERC20Metadata(additionalForceDeploymentsData.predeployedL2WethAddress).symbol(); + + // Force upgrade the TransparentUpgradeableProxy for the predeployed L2 WETH. + forceUpgradeTransparentProxy( + additionalForceDeploymentsData.predeployedL2WethAddress, + WRAPPED_BASE_TOKEN_IMPL_ADDRESS, + L2GatewayUpgradeHelper.getWethInitData( + name, + symbol, + additionalForceDeploymentsData.baseTokenL1Address, + additionalForceDeploymentsData.baseTokenAssetId + ) ); } } + + /// @notice Forces an upgrade of a TransparentUpgradeableProxy contract. + /// @dev Constructs the appropriate calldata for upgrading the proxy and executes the upgrade + /// by mimicCall-ing the admin of the proxy. + /// @param _proxyAddr Address of the TransparentUpgradeableProxy to upgrade. + /// @param _newImpl Address of the new implementation contract. + /// @param _additionalData Additional calldata to pass to the `upgradeToAndCall` function, if any. + function forceUpgradeTransparentProxy(address _proxyAddr, address _newImpl, bytes memory _additionalData) internal { + bytes memory upgradeData; + if (_additionalData.length > 0) { + upgradeData = abi.encodeCall(ITransparentUpgradeableProxy.upgradeToAndCall, (_newImpl, _additionalData)); + } else { + upgradeData = abi.encodeCall(ITransparentUpgradeableProxy.upgradeTo, (_newImpl)); + } + + // Retrieve the proxy admin address from the proxy's storage slot. + address proxyAdmin = address(uint160(uint256(SystemContractHelper.forcedSload(_proxyAddr, PROXY_ADMIN_SLOT)))); + + SystemContractHelper.mimicCallWithPropagatedRevert(_proxyAddr, proxyAdmin, upgradeData); + } + + /// @notice Forces an upgrade of an UpgradeableBeacon proxy contract. + /// @dev Constructs the appropriate calldata for upgrading the proxy and executes the upgrade + /// by mimicCall-ing the admin of the proxy. + /// @param _proxyAddr Address of the UpgradeableBeacon proxy to upgrade. + /// @param _newImpl Address of the new implementation contract. + function forceUpgradeBeaconProxy(address _proxyAddr, address _newImpl) internal { + bytes memory upgradeData = abi.encodeCall(UpgradeableBeacon.upgradeTo, (_newImpl)); + + // Retrieve the owner of the beacon. + address owner = UpgradeableBeacon(_proxyAddr).owner(); + + // Execute the upgrade via a low-level call, propagating any revert. + SystemContractHelper.mimicCallWithPropagatedRevert(_proxyAddr, owner, upgradeData); + } } diff --git a/system-contracts/contracts/L2GatewayUpgradeHelper.sol b/system-contracts/contracts/L2GatewayUpgradeHelper.sol new file mode 100644 index 000000000..75ad2e876 --- /dev/null +++ b/system-contracts/contracts/L2GatewayUpgradeHelper.sol @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: MIT + +pragma solidity 0.8.24; + +import {DEPLOYER_SYSTEM_CONTRACT, L2_BRIDGE_HUB, L2_ASSET_ROUTER, L2_MESSAGE_ROOT, L2_NATIVE_TOKEN_VAULT_ADDR} from "./Constants.sol"; +import {IContractDeployer, ForceDeployment} from "./interfaces/IContractDeployer.sol"; +import {SystemContractHelper} from "./libraries/SystemContractHelper.sol"; +import {FixedForceDeploymentsData, ZKChainSpecificForceDeploymentsData} from "./interfaces/IL2GenesisUpgrade.sol"; +import {IL2SharedBridgeLegacy} from "./interfaces/IL2SharedBridgeLegacy.sol"; +import {WRAPPED_BASE_TOKEN_IMPL_ADDRESS, L2_ASSET_ROUTER} from "./Constants.sol"; +import {IL2WrappedBaseToken} from "./interfaces/IL2WrappedBaseToken.sol"; + +import {TransparentUpgradeableProxy} from "@openzeppelin/contracts-v4/proxy/transparent/TransparentUpgradeableProxy.sol"; + +/// @title L2GatewayUpgradeHelper +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice A helper library for initializing and managing force-deployed contracts during either the L2 gateway upgrade or +/// the genesis after the gateway protocol upgrade. +library L2GatewayUpgradeHelper { + /// @notice Initializes force-deployed contracts required for the L2 genesis upgrade. + /// @param _ctmDeployer Address of the CTM Deployer contract. + /// @param _fixedForceDeploymentsData Encoded data for forced deployment that + /// is the same for all the chains. + /// @param _additionalForceDeploymentsData Encoded data for force deployments that + /// is specific for each ZK Chain. + function performForceDeployedContractsInit( + address _ctmDeployer, + bytes memory _fixedForceDeploymentsData, + bytes memory _additionalForceDeploymentsData + ) internal { + // Decode and retrieve the force deployments data. + ForceDeployment[] memory forceDeployments = _getForceDeploymentsData( + _fixedForceDeploymentsData, + _additionalForceDeploymentsData + ); + + // Force deploy the contracts on specified addresses. + IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).forceDeployOnAddresses{value: msg.value}(forceDeployments); + + // It is expected that either through the force deployments above + // or upon initialization, both the L2 deployment of BridgeHub, AssetRouter, and MessageRoot are deployed. + // However, there is still some follow-up finalization that needs to be done. + + // Retrieve the owner of the BridgeHub contract. + address bridgehubOwner = L2_BRIDGE_HUB.owner(); + + // Prepare calldata to set addresses in BridgeHub. + bytes memory data = abi.encodeCall( + L2_BRIDGE_HUB.setAddresses, + (L2_ASSET_ROUTER, _ctmDeployer, address(L2_MESSAGE_ROOT)) + ); + + // Execute the call to set addresses in BridgeHub. + (bool success, bytes memory returnData) = SystemContractHelper.mimicCall( + address(L2_BRIDGE_HUB), + bridgehubOwner, + data + ); + + // Revert with the original revert reason if the call failed. + if (!success) { + /// @dev Propagate the revert reason from the failed call. + assembly { + revert(add(returnData, 0x20), returndatasize()) + } + } + } + + /// @notice Retrieves and constructs the force deployments array. + /// @dev Decodes the provided force deployments data and organizes them into an array of `ForceDeployment` to + /// to execute. + /// @param _fixedForceDeploymentsData Encoded data for forced deployment that + /// is the same for all the chains. + /// @param _additionalForceDeploymentsData Encoded data for force deployments that + /// is specific for each ZK Chain. + /// @return forceDeployments An array of `ForceDeployment` structs containing deployment details. + function _getForceDeploymentsData( + bytes memory _fixedForceDeploymentsData, + bytes memory _additionalForceDeploymentsData + ) internal returns (ForceDeployment[] memory forceDeployments) { + // Decode the fixed and additional force deployments data. + FixedForceDeploymentsData memory fixedForceDeploymentsData = abi.decode( + _fixedForceDeploymentsData, + (FixedForceDeploymentsData) + ); + ZKChainSpecificForceDeploymentsData memory additionalForceDeploymentsData = abi.decode( + _additionalForceDeploymentsData, + (ZKChainSpecificForceDeploymentsData) + ); + + forceDeployments = new ForceDeployment[](4); + + // Configure the MessageRoot deployment. + forceDeployments[0] = ForceDeployment({ + bytecodeHash: fixedForceDeploymentsData.messageRootBytecodeHash, + newAddress: address(L2_MESSAGE_ROOT), + callConstructor: true, + value: 0, + // solhint-disable-next-line func-named-parameters + input: abi.encode(address(L2_BRIDGE_HUB)) + }); + + // Configure the BridgeHub deployment. + forceDeployments[1] = ForceDeployment({ + bytecodeHash: fixedForceDeploymentsData.bridgehubBytecodeHash, + newAddress: address(L2_BRIDGE_HUB), + callConstructor: true, + value: 0, + input: abi.encode( + fixedForceDeploymentsData.l1ChainId, + fixedForceDeploymentsData.aliasedL1Governance, + fixedForceDeploymentsData.maxNumberOfZKChains + ) + }); + + // Configure the AssetRouter deployment. + forceDeployments[2] = ForceDeployment({ + bytecodeHash: fixedForceDeploymentsData.l2AssetRouterBytecodeHash, + newAddress: address(L2_ASSET_ROUTER), + callConstructor: true, + value: 0, + // solhint-disable-next-line func-named-parameters + input: abi.encode( + fixedForceDeploymentsData.l1ChainId, + fixedForceDeploymentsData.eraChainId, + fixedForceDeploymentsData.l1AssetRouter, + additionalForceDeploymentsData.l2LegacySharedBridge, + additionalForceDeploymentsData.baseTokenAssetId, + fixedForceDeploymentsData.aliasedL1Governance + ) + }); + + // Ensure the WETH token is deployed and retrieve its address. + address wrappedBaseTokenAddress = _ensureWethToken({ + _predeployedWethToken: additionalForceDeploymentsData.predeployedL2WethAddress, + _aliasedL1Governance: fixedForceDeploymentsData.aliasedL1Governance, + _baseTokenL1Address: additionalForceDeploymentsData.baseTokenL1Address, + _baseTokenAssetId: additionalForceDeploymentsData.baseTokenAssetId, + _baseTokenName: additionalForceDeploymentsData.baseTokenName, + _baseTokenSymbol: additionalForceDeploymentsData.baseTokenSymbol + }); + + address deployedTokenBeacon; + if (additionalForceDeploymentsData.l2LegacySharedBridge != address(0)) { + deployedTokenBeacon = address( + IL2SharedBridgeLegacy(additionalForceDeploymentsData.l2LegacySharedBridge).l2TokenBeacon() + ); + } + + bool shouldDeployBeacon = deployedTokenBeacon == address(0); + + // Configure the Native Token Vault deployment. + forceDeployments[3] = ForceDeployment({ + bytecodeHash: fixedForceDeploymentsData.l2NtvBytecodeHash, + newAddress: L2_NATIVE_TOKEN_VAULT_ADDR, + callConstructor: true, + value: 0, + // solhint-disable-next-line func-named-parameters + input: abi.encode( + fixedForceDeploymentsData.l1ChainId, + fixedForceDeploymentsData.aliasedL1Governance, + fixedForceDeploymentsData.l2TokenProxyBytecodeHash, + additionalForceDeploymentsData.l2LegacySharedBridge, + deployedTokenBeacon, + shouldDeployBeacon, + wrappedBaseTokenAddress, + additionalForceDeploymentsData.baseTokenAssetId + ) + }); + } + + /// @notice Constructs the initialization calldata for the L2WrappedBaseToken. + /// @param _wrappedBaseTokenName The name of the wrapped base token. + /// @param _wrappedBaseTokenSymbol The symbol of the wrapped base token. + /// @param _baseTokenL1Address The L1 address of the base token. + /// @param _baseTokenAssetId The asset ID of the base token. + /// @return initData The encoded initialization calldata. + function getWethInitData( + string memory _wrappedBaseTokenName, + string memory _wrappedBaseTokenSymbol, + address _baseTokenL1Address, + bytes32 _baseTokenAssetId + ) internal pure returns (bytes memory initData) { + initData = abi.encodeCall( + IL2WrappedBaseToken.initializeV3, + (_wrappedBaseTokenName, _wrappedBaseTokenSymbol, L2_ASSET_ROUTER, _baseTokenL1Address, _baseTokenAssetId) + ); + } + + /// @notice Ensures that the WETH token is deployed. If not predeployed, deploys it. + /// @param _predeployedWethToken The potential address of the predeployed WETH token. + /// @param _aliasedL1Governance Address of the aliased L1 governance. + /// @param _baseTokenL1Address L1 address of the base token. + /// @param _baseTokenAssetId Asset ID of the base token. + /// @param _baseTokenName Name of the base token. + /// @param _baseTokenSymbol Symbol of the base token. + /// @return The address of the ensured WETH token. + function _ensureWethToken( + address _predeployedWethToken, + address _aliasedL1Governance, + address _baseTokenL1Address, + bytes32 _baseTokenAssetId, + string memory _baseTokenName, + string memory _baseTokenSymbol + ) private returns (address) { + if (_predeployedWethToken != address(0)) { + return _predeployedWethToken; + } + + string memory wrappedBaseTokenName = string.concat("Wrapped ", _baseTokenName); + string memory wrappedBaseTokenSymbol = string.concat("W", _baseTokenSymbol); + + bytes memory initData = getWethInitData( + wrappedBaseTokenName, + wrappedBaseTokenSymbol, + _baseTokenL1Address, + _baseTokenAssetId + ); + + bytes memory constructorParams = abi.encode(WRAPPED_BASE_TOKEN_IMPL_ADDRESS, _aliasedL1Governance, initData); + + TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy{salt: bytes32(0)}( + WRAPPED_BASE_TOKEN_IMPL_ADDRESS, + _aliasedL1Governance, + constructorParams + ); + + return address(proxy); + } +} diff --git a/system-contracts/contracts/L2GenesisUpgrade.sol b/system-contracts/contracts/L2GenesisUpgrade.sol index 585ff14f1..00a22c799 100644 --- a/system-contracts/contracts/L2GenesisUpgrade.sol +++ b/system-contracts/contracts/L2GenesisUpgrade.sol @@ -4,25 +4,33 @@ pragma solidity 0.8.24; import {SYSTEM_CONTEXT_CONTRACT} from "./Constants.sol"; import {ISystemContext} from "./interfaces/ISystemContext.sol"; +import {InvalidChainId} from "contracts/SystemContractErrors.sol"; import {IL2GenesisUpgrade} from "./interfaces/IL2GenesisUpgrade.sol"; -import {L2GenesisUpgradeHelper} from "./L2GenesisUpgradeHelper.sol"; +import {L2GatewayUpgradeHelper} from "./L2GatewayUpgradeHelper.sol"; /// @custom:security-contact security@matterlabs.dev /// @author Matter Labs -/// @notice The contract that can be used for deterministic contract deployment. +/// @notice The l2 component of the genesis upgrade. contract L2GenesisUpgrade is IL2GenesisUpgrade { + /// @notice The function that is delegateCalled from the complex upgrader. + /// @dev It is used to set the chainId and to deploy the force deployments. + /// @param _chainId the chain id + /// @param _ctmDeployer the address of the ctm deployer + /// @param _fixedForceDeploymentsData the force deployments data + /// @param _additionalForceDeploymentsData the additional force deployments data function genesisUpgrade( uint256 _chainId, address _ctmDeployer, bytes calldata _fixedForceDeploymentsData, bytes calldata _additionalForceDeploymentsData ) external payable { - // solhint-disable-next-line gas-custom-errors - require(_chainId != 0, "Invalid chainId"); + if (_chainId == 0) { + revert InvalidChainId(); + } ISystemContext(SYSTEM_CONTEXT_CONTRACT).setChainId(_chainId); - L2GenesisUpgradeHelper.performForceDeployedContractsInit( + L2GatewayUpgradeHelper.performForceDeployedContractsInit( _ctmDeployer, _fixedForceDeploymentsData, _additionalForceDeploymentsData diff --git a/system-contracts/contracts/L2GenesisUpgradeHelper.sol b/system-contracts/contracts/L2GenesisUpgradeHelper.sol deleted file mode 100644 index 30752c948..000000000 --- a/system-contracts/contracts/L2GenesisUpgradeHelper.sol +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-License-Identifier: MIT - -pragma solidity 0.8.24; - -import {DEPLOYER_SYSTEM_CONTRACT, L2_BRIDGE_HUB, L2_ASSET_ROUTER, L2_MESSAGE_ROOT, L2_NATIVE_TOKEN_VAULT_ADDR} from "./Constants.sol"; -import {IContractDeployer, ForceDeployment} from "./interfaces/IContractDeployer.sol"; -import {SystemContractHelper} from "./libraries/SystemContractHelper.sol"; -import {FixedForceDeploymentsData, ZKChainSpecificForceDeploymentsData} from "./interfaces/IL2GenesisUpgrade.sol"; - -library L2GenesisUpgradeHelper { - function performForceDeployedContractsInit( - address _ctmDeployer, - bytes calldata _fixedForceDeploymentsData, - bytes calldata _additionalForceDeploymentsData - ) internal { - ForceDeployment[] memory forceDeployments = _getForceDeploymentsData( - _fixedForceDeploymentsData, - _additionalForceDeploymentsData - ); - IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).forceDeployOnAddresses{value: msg.value}(forceDeployments); - - // It is expected that either via to the force deployments above - // or upon init both the L2 deployment of Bridgehub, AssetRouter and MessageRoot are deployed. - // (The comment does not mention the exact order in case it changes) - // However, there is still some follow up finalization that needs to be done. - - address bridgehubOwner = L2_BRIDGE_HUB.owner(); - - bytes memory data = abi.encodeCall( - L2_BRIDGE_HUB.setAddresses, - (L2_ASSET_ROUTER, _ctmDeployer, address(L2_MESSAGE_ROOT)) - ); - - (bool success, bytes memory returnData) = SystemContractHelper.mimicCall( - address(L2_BRIDGE_HUB), - bridgehubOwner, - data - ); - if (!success) { - // Progapatate revert reason - assembly { - revert(add(returnData, 0x20), returndatasize()) - } - } - } - - function _getForceDeploymentsData( - bytes calldata _fixedForceDeploymentsData, - bytes calldata _additionalForceDeploymentsData - ) internal view returns (ForceDeployment[] memory forceDeployments) { - FixedForceDeploymentsData memory fixedForceDeploymentsData = abi.decode( - _fixedForceDeploymentsData, - (FixedForceDeploymentsData) - ); - ZKChainSpecificForceDeploymentsData memory additionalForceDeploymentsData = abi.decode( - _additionalForceDeploymentsData, - (ZKChainSpecificForceDeploymentsData) - ); - - forceDeployments = new ForceDeployment[](4); - - forceDeployments[0] = ForceDeployment({ - bytecodeHash: fixedForceDeploymentsData.messageRootBytecodeHash, - newAddress: address(L2_MESSAGE_ROOT), - callConstructor: true, - value: 0, - // solhint-disable-next-line func-named-parameters - input: abi.encode(address(L2_BRIDGE_HUB)) - }); - - forceDeployments[1] = ForceDeployment({ - bytecodeHash: fixedForceDeploymentsData.bridgehubBytecodeHash, - newAddress: address(L2_BRIDGE_HUB), - callConstructor: true, - value: 0, - input: abi.encode( - fixedForceDeploymentsData.l1ChainId, - fixedForceDeploymentsData.aliasedL1Governance, - fixedForceDeploymentsData.maxNumberOfZKChains - ) - }); - - forceDeployments[2] = ForceDeployment({ - bytecodeHash: fixedForceDeploymentsData.l2AssetRouterBytecodeHash, - newAddress: address(L2_ASSET_ROUTER), - callConstructor: true, - value: 0, - // solhint-disable-next-line func-named-parameters - input: abi.encode( - fixedForceDeploymentsData.l1ChainId, - fixedForceDeploymentsData.eraChainId, - fixedForceDeploymentsData.l1AssetRouter, - additionalForceDeploymentsData.l2LegacySharedBridge, - additionalForceDeploymentsData.baseTokenAssetId, - fixedForceDeploymentsData.aliasedL1Governance - ) - }); - - forceDeployments[3] = ForceDeployment({ - bytecodeHash: fixedForceDeploymentsData.l2NtvBytecodeHash, - newAddress: L2_NATIVE_TOKEN_VAULT_ADDR, - callConstructor: true, - value: 0, - // solhint-disable-next-line func-named-parameters - input: abi.encode( - fixedForceDeploymentsData.l1ChainId, - fixedForceDeploymentsData.aliasedL1Governance, - fixedForceDeploymentsData.l2TokenProxyBytecodeHash, - additionalForceDeploymentsData.l2LegacySharedBridge, - address(0), // this is used if the contract were already deployed, so for the migration of Era. - false, - additionalForceDeploymentsData.l2Weth, - additionalForceDeploymentsData.baseTokenAssetId - ) - }); - } -} diff --git a/system-contracts/contracts/PubdataChunkPublisher.sol b/system-contracts/contracts/PubdataChunkPublisher.sol index f61f0b5ac..7c2abf2e1 100644 --- a/system-contracts/contracts/PubdataChunkPublisher.sol +++ b/system-contracts/contracts/PubdataChunkPublisher.sol @@ -2,7 +2,6 @@ pragma solidity 0.8.24; import {IPubdataChunkPublisher} from "./interfaces/IPubdataChunkPublisher.sol"; -import {SystemContractBase} from "./abstract/SystemContractBase.sol"; import {BLOB_SIZE_BYTES, MAX_NUMBER_OF_BLOBS} from "./Constants.sol"; import {TooMuchPubdata} from "./SystemContractErrors.sol"; @@ -11,7 +10,7 @@ import {TooMuchPubdata} from "./SystemContractErrors.sol"; * @custom:security-contact security@matterlabs.dev * @notice Smart contract for chunking pubdata into the appropriate size for EIP-4844 blobs. */ -contract PubdataChunkPublisher is IPubdataChunkPublisher, SystemContractBase { +contract PubdataChunkPublisher is IPubdataChunkPublisher { /// @notice Chunks pubdata into pieces that can fit into blobs. /// @param _pubdata The total l2 to l1 pubdata that will be sent via L1 blobs. /// @dev Note: This is an early implementation, in the future we plan to support up to 16 blobs per l1 batch. diff --git a/system-contracts/contracts/SloadContract.sol b/system-contracts/contracts/SloadContract.sol new file mode 100644 index 000000000..23a80ae7d --- /dev/null +++ b/system-contracts/contracts/SloadContract.sol @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.24; + +/// @title SloadContract +/// @author Matter Labs +/// @custom:security-contact security@matterlabs.dev +/// @notice This contract provides a method to read values from arbitrary storage slots +/// @dev It is used by the `SystemContractHelper` library to help system contracts read +/// arbitrary slots of contracts. +contract SloadContract { + /// @notice Reads the value stored at a specific storage slot + /// @param slot The storage slot number to read from + /// @return value The value stored at the specified slot as a bytes32 type + function sload(bytes32 slot) external view returns (bytes32 value) { + assembly { + // sload retrieves the value at the given storage slot + value := sload(slot) + } + } +} diff --git a/system-contracts/contracts/SystemContext.sol b/system-contracts/contracts/SystemContext.sol index 18a2dc143..b4e696350 100644 --- a/system-contracts/contracts/SystemContext.sol +++ b/system-contracts/contracts/SystemContext.sol @@ -1,7 +1,5 @@ // SPDX-License-Identifier: MIT -// solhint-disable reason-string, gas-custom-errors - pragma solidity 0.8.24; import {ISystemContext} from "./interfaces/ISystemContext.sol"; @@ -9,6 +7,7 @@ import {SystemContractBase} from "./abstract/SystemContractBase.sol"; import {ISystemContextDeprecated} from "./interfaces/ISystemContextDeprecated.sol"; import {SystemContractHelper} from "./libraries/SystemContractHelper.sol"; import {BOOTLOADER_FORMAL_ADDRESS, SystemLogKey, COMPLEX_UPGRADER_CONTRACT} from "./Constants.sol"; +import {InconsistentNewBatchTimestamp, InvalidNewL2BlockNumber, IncorrectVirtualBlockInsideMiniblock, IncorrectSameL2BlockPrevBlockHash, IncorrectSameL2BlockTimestamp, CannotReuseL2BlockNumberFromPreviousBatch, NoVirtualBlocks, L2BlockAndBatchTimestampMismatch, UpgradeTransactionMustBeFirst, L2BlockNumberZero, PreviousL2BlockHashIsIncorrect, CannotInitializeFirstVirtualBlock, IncorrectL2BlockHash, NonMonotonicL2BlockTimestamp, CurrentBatchNumberMustBeGreaterThanZero, TimestampsShouldBeIncremental, ProvidedBatchNumberIsNotCorrect} from "contracts/SystemContractErrors.sol"; /** * @author Matter Labs @@ -245,14 +244,20 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra /// @param _expectedPrevL2BlockHash The expected hash of the previous L2 block. /// @param _isFirstInBatch Whether this method is called for the first time in the batch. function _upgradeL2Blocks(uint128 _l2BlockNumber, bytes32 _expectedPrevL2BlockHash, bool _isFirstInBatch) internal { - require(_isFirstInBatch, "Upgrade transaction must be first"); + if (!_isFirstInBatch) { + revert UpgradeTransactionMustBeFirst(); + } // This is how it will be commonly done in practice, but it will simplify some logic later - require(_l2BlockNumber > 0, "L2 block number is never expected to be zero"); + if (_l2BlockNumber == 0) { + revert L2BlockNumberZero(); + } unchecked { bytes32 correctPrevBlockHash = _calculateLegacyL2BlockHash(_l2BlockNumber - 1); - require(correctPrevBlockHash == _expectedPrevL2BlockHash, "The previous L2 block hash is incorrect"); + if (correctPrevBlockHash != _expectedPrevL2BlockHash) { + revert PreviousL2BlockHashIsIncorrect(correctPrevBlockHash, _expectedPrevL2BlockHash); + } // Whenever we'll be queried about the hashes of the blocks before the upgrade, // we'll use batches' hashes, so we don't need to store 256 previous hashes. @@ -290,7 +295,9 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra // Remembering the batch number on which the upgrade to the virtual blocks has been done. virtualBlockUpgradeInfo.virtualBlockStartBatch = currentBatchNumber; - require(_maxVirtualBlocksToCreate > 0, "Can't initialize the first virtual block"); + if (_maxVirtualBlocksToCreate == 0) { + revert CannotInitializeFirstVirtualBlock(); + } // solhint-disable-next-line gas-increment-by-one _maxVirtualBlocksToCreate -= 1; } else if (_maxVirtualBlocksToCreate == 0) { @@ -355,11 +362,12 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra // We check that the timestamp of the L2 block is consistent with the timestamp of the batch. if (_isFirstInBatch) { uint128 currentBatchTimestamp = currentBatchInfo.timestamp; - require( - _l2BlockTimestamp >= currentBatchTimestamp, - "The timestamp of the L2 block must be greater than or equal to the timestamp of the current batch" - ); - require(_maxVirtualBlocksToCreate > 0, "There must be a virtual block created at the start of the batch"); + if (_l2BlockTimestamp < currentBatchTimestamp) { + revert L2BlockAndBatchTimestampMismatch(_l2BlockTimestamp, currentBatchTimestamp); + } + if (_maxVirtualBlocksToCreate == 0) { + revert NoVirtualBlocks(); + } } (uint128 currentL2BlockNumber, uint128 currentL2BlockTimestamp) = getL2BlockNumberAndTimestamp(); @@ -371,13 +379,21 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra _setNewL2BlockData(_l2BlockNumber, _l2BlockTimestamp, _expectedPrevL2BlockHash); } else if (currentL2BlockNumber == _l2BlockNumber) { - require(!_isFirstInBatch, "Can not reuse L2 block number from the previous batch"); - require(currentL2BlockTimestamp == _l2BlockTimestamp, "The timestamp of the same L2 block must be same"); - require( - _expectedPrevL2BlockHash == _getLatest257L2blockHash(_l2BlockNumber - 1), - "The previous hash of the same L2 block must be same" - ); - require(_maxVirtualBlocksToCreate == 0, "Can not create virtual blocks in the middle of the miniblock"); + if (_isFirstInBatch) { + revert CannotReuseL2BlockNumberFromPreviousBatch(); + } + if (currentL2BlockTimestamp != _l2BlockTimestamp) { + revert IncorrectSameL2BlockTimestamp(_l2BlockTimestamp, currentL2BlockTimestamp); + } + if (_expectedPrevL2BlockHash != _getLatest257L2blockHash(_l2BlockNumber - 1)) { + revert IncorrectSameL2BlockPrevBlockHash( + _expectedPrevL2BlockHash, + _getLatest257L2blockHash(_l2BlockNumber - 1) + ); + } + if (_maxVirtualBlocksToCreate != 0) { + revert IncorrectVirtualBlockInsideMiniblock(); + } } else if (currentL2BlockNumber + 1 == _l2BlockNumber) { // From the checks in _upgradeL2Blocks it is known that currentL2BlockNumber can not be 0 bytes32 prevL2BlockHash = _getLatest257L2blockHash(currentL2BlockNumber - 1); @@ -389,16 +405,17 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra currentL2BlockTxsRollingHash ); - require(_expectedPrevL2BlockHash == pendingL2BlockHash, "The current L2 block hash is incorrect"); - require( - _l2BlockTimestamp > currentL2BlockTimestamp, - "The timestamp of the new L2 block must be greater than the timestamp of the previous L2 block" - ); + if (_expectedPrevL2BlockHash != pendingL2BlockHash) { + revert IncorrectL2BlockHash(_expectedPrevL2BlockHash, pendingL2BlockHash); + } + if (_l2BlockTimestamp <= currentL2BlockTimestamp) { + revert NonMonotonicL2BlockTimestamp(_l2BlockTimestamp, currentL2BlockTimestamp); + } // Since the new block is created, we'll clear out the rolling hash _setNewL2BlockData(_l2BlockNumber, _l2BlockTimestamp, _expectedPrevL2BlockHash); } else { - revert("Invalid new L2 block number"); + revert InvalidNewL2BlockNumber(_l2BlockNumber); } _setVirtualBlock(_l2BlockNumber, _maxVirtualBlocksToCreate, _l2BlockTimestamp); @@ -417,7 +434,9 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra (, uint128 currentL2BlockTimestamp) = getL2BlockNumberAndTimestamp(); // The structure of the "setNewBatch" implies that currentBatchNumber > 0, but we still double check it - require(currentBatchNumber > 0, "The current batch number must be greater than 0"); + if (currentBatchNumber == 0) { + revert CurrentBatchNumberMustBeGreaterThanZero(); + } // In order to spend less pubdata, the packed version is published uint256 packedTimestamps = (uint256(currentBatchTimestamp) << 128) | currentL2BlockTimestamp; @@ -433,10 +452,9 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra /// @param _newTimestamp The timestamp of the new batch. function _ensureBatchConsistentWithL2Block(uint128 _newTimestamp) internal view { uint128 currentBlockTimestamp = currentL2BlockInfo.timestamp; - require( - _newTimestamp > currentBlockTimestamp, - "The timestamp of the batch must be greater than the timestamp of the previous block" - ); + if (_newTimestamp <= currentBlockTimestamp) { + revert InconsistentNewBatchTimestamp(_newTimestamp, currentBlockTimestamp); + } } /// @notice Increments the current batch number and sets the new timestamp @@ -455,8 +473,12 @@ contract SystemContext is ISystemContext, ISystemContextDeprecated, SystemContra uint256 _baseFee ) external onlyCallFromBootloader { (uint128 previousBatchNumber, uint128 previousBatchTimestamp) = getBatchNumberAndTimestamp(); - require(_newTimestamp > previousBatchTimestamp, "Timestamps should be incremental"); - require(previousBatchNumber + 1 == _expectedNewNumber, "The provided batch number is not correct"); + if (_newTimestamp <= previousBatchTimestamp) { + revert TimestampsShouldBeIncremental(_newTimestamp, previousBatchTimestamp); + } + if (previousBatchNumber + 1 != _expectedNewNumber) { + revert ProvidedBatchNumberIsNotCorrect(previousBatchNumber + 1, _expectedNewNumber); + } _ensureBatchConsistentWithL2Block(_newTimestamp); diff --git a/system-contracts/contracts/SystemContractErrors.sol b/system-contracts/contracts/SystemContractErrors.sol index d61e99c10..c2104e48f 100644 --- a/system-contracts/contracts/SystemContractErrors.sol +++ b/system-contracts/contracts/SystemContractErrors.sol @@ -6,8 +6,6 @@ pragma solidity ^0.8.20; error AddressHasNoCode(address); // 0xefce78c7 error CallerMustBeBootloader(); -// 0xb7549616 -error CallerMustBeForceDeployer(); // 0x9eedbd2b error CallerMustBeSystemContract(); // 0x4f951510 @@ -26,8 +24,6 @@ error DerivedKeyNotEqualToCompressedValue(bytes32 expected, bytes32 provided); error DictionaryDividedByEightNotGreaterThanEncodedDividedByTwo(); // 0x1c25715b error EmptyBytes32(); -// 0x92bf3cf8 -error EmptyVirtualBlocks(); // 0xc06d5cb2 error EncodedAndRealBytecodeChunkNotEqual(uint64 expected, uint64 provided); // 0x2bfbfc11 @@ -36,8 +32,6 @@ error EncodedLengthNotFourTimesSmallerThanOriginal(); error FailedToChargeGas(); // 0x1f70c58f error FailedToPayOperator(); -// 0x9d5da395 -error FirstL2BlockInitializationError(); // 0x9e4a3c8a error HashIsNonZero(bytes32); // 0x86302004 @@ -48,23 +42,19 @@ error IndexOutOfBounds(); error IndexSizeError(); // 0x03eb8b54 error InsufficientFunds(uint256 required, uint256 actual); -// 0x1c26714c -error InsufficientGas(); // 0xae962d4e error InvalidCall(); -// 0x6a84bc39 +// 0x8cbd7f8b error InvalidCodeHash(CodeHashReason); // 0xb4fa3fb3 error InvalidInput(); // 0x60b85677 error InvalidNonceOrderingChange(); -// 0x90f049c9 +// 0xc6b7f67d error InvalidSig(SigField, uint256); // 0xf4a271b5 error Keccak256InvalidReturnData(); -// 0xd2906dd9 -error L2BlockMustBeGreaterThanZero(); -// 0x43e266b0 +// 0xcea34703 error MalformedBytecode(BytecodeError); // 0xe90aded4 error NonceAlreadyUsed(address account, uint256 nonce); @@ -84,7 +74,7 @@ error NonIncreasingTimestamp(); error NotAllowedToDeployInKernelSpace(); // 0x35278d12 error Overflow(); -// 0x7f7b0cf7 +// 0xe5ec477a error ReconstructionMismatch(PubdataField, bytes32 expected, bytes32 actual); // 0x3adb5f1d error ShaInvalidReturnData(); @@ -104,14 +94,107 @@ error UnsupportedOperation(); error UnsupportedPaymasterFlow(); // 0x17a84415 error UnsupportedTxType(uint256); -// 0x5708aead -error UpgradeMustBeFirstTxn(); // 0x626ade30 error ValueMismatch(uint256 expected, uint256 actual); -// 0x460b9939 -error ValuesNotEqual(uint256 expected, uint256 actual); // 0x6818f3f9 error ZeroNonceError(); +// 0x4f2b5b33 +error SloadContractBytecodeUnknown(); +// 0x43197434 +error PreviousBytecodeUnknown(); + +// 0x7a47c9a2 +error InvalidChainId(); + +// 0xc84a0422 +error UpgradeTransactionMustBeFirst(); + +// 0x543f4c07 +error L2BlockNumberZero(); + +// 0x702a599f +error PreviousL2BlockHashIsIncorrect(bytes32 correctPrevBlockHash, bytes32 expectedPrevL2BlockHash); + +// 0x2692f507 +error CannotInitializeFirstVirtualBlock(); + +// 0x5e9ad9b0 +error L2BlockAndBatchTimestampMismatch(uint128 l2BlockTimestamp, uint128 currentBatchTimestamp); + +// 0x159a6f2e +error InconsistentNewBatchTimestamp(uint128 newBatchTimestamp, uint128 lastL2BlockTimestamp); + +// 0xdcdfb0da +error NoVirtualBlocks(); + +// 0x141d6142 +error CannotReuseL2BlockNumberFromPreviousBatch(); + +// 0xf34da52d +error IncorrectSameL2BlockTimestamp(uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp); + +// 0x5822b85d +error IncorrectSameL2BlockPrevBlockHash(bytes32 expectedPrevL2BlockHash, bytes32 latestL2blockHash); + +// 0x6d391091 +error IncorrectVirtualBlockInsideMiniblock(); + +// 0xdf841e81 +error IncorrectL2BlockHash(bytes32 expectedPrevL2BlockHash, bytes32 pendingL2BlockHash); + +// 0x35dbda93 +error NonMonotonicL2BlockTimestamp(uint128 l2BlockTimestamp, uint128 currentL2BlockTimestamp); + +// 0x6ad429e8 +error CurrentBatchNumberMustBeGreaterThanZero(); + +// 0x09c63320 +error TimestampsShouldBeIncremental(uint128 newTimestamp, uint128 previousBatchTimestamp); + +// 0x33cb1485 +error ProvidedBatchNumberIsNotCorrect(uint128 previousBatchNumber, uint128 _expectedNewNumber); + +// 0xaa957ece +error CodeOracleCallFailed(); + +// 0x26772295 +error ReturnedBytecodeDoesNotMatchExpectedHash(bytes32 returnedBytecode, bytes32 expectedBytecodeHash); + +// 0x7f08f26b +error SecondCallShouldHaveCostLessGas(uint256 secondCallCost, uint256 firstCallCost); + +// 0xaa016ed2 +error ThirdCallShouldHaveSameGasCostAsSecondCall(uint256 thirdCallCost, uint256 secondCallCost); + +// 0xee455381 +error CallToKeccakShouldHaveSucceeded(); + +// 0x9c9d5e18 +error KeccakReturnDataSizeShouldBe32Bytes(uint256 returnDataSize); + +// 0x0c69f92e +error KeccakResultIsNotCorrect(bytes32 result); + +// 0x262f4984 +error KeccakShouldStartWorkingAgain(); + +// 0x034e49a6 +error KeccakMismatchBetweenNumberOfInputsAndOutputs(uint256 testInputsLength, uint256 expectedOutputsLength); + +// 0x92f5b709 +error KeccakHashWasNotCalculatedCorrectly(bytes32 result, bytes32 expectedOutputs); + +// 0xbf961a28 +error TransactionFailed(); + +// 0xdd629f86 +error NotEnoughGas(); + +// 0xf0b4e88f +error TooMuchGas(); + +// 0x8c13f15d +error InvalidNewL2BlockNumber(uint256 l2BlockNumber); enum CodeHashReason { NotContractOnConstructor, diff --git a/system-contracts/contracts/interfaces/IComplexUpgrader.sol b/system-contracts/contracts/interfaces/IComplexUpgrader.sol index 3b1468417..d97720c6d 100644 --- a/system-contracts/contracts/interfaces/IComplexUpgrader.sol +++ b/system-contracts/contracts/interfaces/IComplexUpgrader.sol @@ -2,11 +2,19 @@ // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.20; +import {ForceDeployment} from "./IContractDeployer.sol"; + /** * @author Matter Labs * @custom:security-contact security@matterlabs.dev * @notice The interface for the ComplexUpgrader contract. */ interface IComplexUpgrader { + function forceDeployAndUpgrade( + ForceDeployment[] calldata _forceDeployments, + address _delegateTo, + bytes calldata _calldata + ) external payable; + function upgrade(address _delegateTo, bytes calldata _calldata) external payable; } diff --git a/system-contracts/contracts/interfaces/ICreate2Factory.sol b/system-contracts/contracts/interfaces/ICreate2Factory.sol new file mode 100644 index 000000000..e9a0faf15 --- /dev/null +++ b/system-contracts/contracts/interfaces/ICreate2Factory.sol @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: MIT +// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. +pragma solidity ^0.8.20; + +import {IContractDeployer} from "./IContractDeployer.sol"; + +/// @custom:security-contact security@matterlabs.dev +/// @author Matter Labs +/// @notice The contract that can be used for deterministic contract deployment. +interface ICreate2Factory { + /// @notice Function that calls the `create2` method of the `ContractDeployer` contract. + /// @dev This function accepts the same parameters as the `create2` function of the ContractDeployer system contract, + /// so that we could efficiently relay the calldata. + function create2( + bytes32, // _salt + bytes32, // _bytecodeHash + bytes calldata // _input + ) external payable returns (address); + + /// @notice Function that calls the `create2Account` method of the `ContractDeployer` contract. + /// @dev This function accepts the same parameters as the `create2Account` function of the ContractDeployer system contract, + /// so that we could efficiently relay the calldata. + function create2Account( + bytes32, // _salt + bytes32, // _bytecodeHash + bytes calldata, // _input + IContractDeployer.AccountAbstractionVersion // _aaVersion + ) external payable returns (address); +} diff --git a/system-contracts/contracts/interfaces/IL2GenesisUpgrade.sol b/system-contracts/contracts/interfaces/IL2GenesisUpgrade.sol index 8752202a5..14f05304e 100644 --- a/system-contracts/contracts/interfaces/IL2GenesisUpgrade.sol +++ b/system-contracts/contracts/interfaces/IL2GenesisUpgrade.sol @@ -2,12 +2,21 @@ // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.20; +// solhint-disable-next-line gas-struct-packing struct ZKChainSpecificForceDeploymentsData { bytes32 baseTokenAssetId; address l2LegacySharedBridge; - address l2Weth; + address predeployedL2WethAddress; + address baseTokenL1Address; + /// @dev Some info about the base token, it is + /// needed to deploy weth token in case it is not present + string baseTokenName; + string baseTokenSymbol; } +/// @notice THe structure that describes force deployments that are the same for each chain. +/// @dev Note, that for simplicity, the same struct is used both for upgrading to the +/// Gateway version and for the Genesis. Some fields may not be used in either of those. // solhint-disable-next-line gas-struct-packing struct FixedForceDeploymentsData { uint256 l1ChainId; @@ -22,8 +31,6 @@ struct FixedForceDeploymentsData { bytes32 messageRootBytecodeHash; address l2SharedBridgeLegacyImpl; address l2BridgedStandardERC20Impl; - address l2BridgeProxyOwnerAddress; - address l2BridgedStandardERC20ProxyOwnerAddress; } interface IL2GenesisUpgrade { diff --git a/system-contracts/contracts/interfaces/IL2SharedBridgeLegacy.sol b/system-contracts/contracts/interfaces/IL2SharedBridgeLegacy.sol index 05d86757e..77c6d9ec9 100644 --- a/system-contracts/contracts/interfaces/IL2SharedBridgeLegacy.sol +++ b/system-contracts/contracts/interfaces/IL2SharedBridgeLegacy.sol @@ -14,7 +14,7 @@ interface IL2SharedBridgeLegacy { uint256 amount ); - function l2TokenBeacon() external returns (UpgradeableBeacon); + function l2TokenBeacon() external view returns (UpgradeableBeacon); function withdraw(address _l1Receiver, address _l2Token, uint256 _amount) external; diff --git a/system-contracts/contracts/interfaces/IL2WrappedBaseToken.sol b/system-contracts/contracts/interfaces/IL2WrappedBaseToken.sol new file mode 100644 index 000000000..0bfc9352e --- /dev/null +++ b/system-contracts/contracts/interfaces/IL2WrappedBaseToken.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MIT +// We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. +pragma solidity ^0.8.20; + +interface IL2WrappedBaseToken { + /// @notice Initializes a contract token for later use. Expected to be used in the proxy. + /// @notice This function is used to integrate the previously deployed WETH token with the bridge. + /// @dev Sets up `name`/`symbol`/`decimals` getters. + /// @param name_ The name of the token. + /// @param symbol_ The symbol of the token. + /// @param _l2Bridge Address of the L2 bridge + /// @param _l1Address Address of the L1 token that can be deposited to mint this L2 WETH. + /// Note: The decimals are hardcoded to 18, the same as on Ether. + function initializeV3( + string calldata name_, + string calldata symbol_, + address _l2Bridge, + address _l1Address, + bytes32 _baseTokenAssetId + ) external; +} diff --git a/system-contracts/contracts/interfaces/IMessageRoot.sol b/system-contracts/contracts/interfaces/IMessageRoot.sol index 854508eb1..3966caa15 100644 --- a/system-contracts/contracts/interfaces/IMessageRoot.sol +++ b/system-contracts/contracts/interfaces/IMessageRoot.sol @@ -2,6 +2,13 @@ // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.20; +/** + * @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 security@matterlabs.dev + */ interface IMessageRoot { + /// @notice The aggregated root of the batches from different chains. + /// @return aggregatedRoot of the batches from different chains. function getAggregatedRoot() external view returns (bytes32 aggregatedRoot); } diff --git a/system-contracts/contracts/libraries/SystemContractHelper.sol b/system-contracts/contracts/libraries/SystemContractHelper.sol index d3d5e7536..7205ac86d 100644 --- a/system-contracts/contracts/libraries/SystemContractHelper.sol +++ b/system-contracts/contracts/libraries/SystemContractHelper.sol @@ -2,10 +2,12 @@ // We use a floating point pragma here so it can be used within other projects that interact with the ZKsync ecosystem without using our exact pragma version. pragma solidity ^0.8.20; -import {MAX_SYSTEM_CONTRACT_ADDRESS} from "../Constants.sol"; +import {MAX_SYSTEM_CONTRACT_ADDRESS, DEPLOYER_SYSTEM_CONTRACT, FORCE_DEPLOYER, KNOWN_CODE_STORAGE_CONTRACT, SLOAD_CONTRACT_ADDRESS} from "../Constants.sol"; +import {ForceDeployment, IContractDeployer} from "../interfaces/IContractDeployer.sol"; +import {SloadContract} from "../SloadContract.sol"; import {CalldataForwardingMode, SystemContractsCaller, MIMIC_CALL_CALL_ADDRESS, CALLFLAGS_CALL_ADDRESS, CODE_ADDRESS_CALL_ADDRESS, EVENT_WRITE_ADDRESS, EVENT_INITIALIZE_ADDRESS, GET_EXTRA_ABI_DATA_ADDRESS, LOAD_CALLDATA_INTO_ACTIVE_PTR_CALL_ADDRESS, META_CODE_SHARD_ID_OFFSET, META_CALLER_SHARD_ID_OFFSET, META_SHARD_ID_OFFSET, META_AUX_HEAP_SIZE_OFFSET, META_HEAP_SIZE_OFFSET, META_PUBDATA_PUBLISHED_OFFSET, META_CALL_ADDRESS, PTR_CALLDATA_CALL_ADDRESS, PTR_ADD_INTO_ACTIVE_CALL_ADDRESS, PTR_SHRINK_INTO_ACTIVE_CALL_ADDRESS, PTR_PACK_INTO_ACTIVE_CALL_ADDRESS, PRECOMPILE_CALL_ADDRESS, SET_CONTEXT_VALUE_CALL_ADDRESS, TO_L1_CALL_ADDRESS} from "./SystemContractsCaller.sol"; -import {IndexOutOfBounds, FailedToChargeGas} from "../SystemContractErrors.sol"; +import {IndexOutOfBounds, FailedToChargeGas, SloadContractBytecodeUnknown, PreviousBytecodeUnknown} from "../SystemContractErrors.sol"; uint256 constant UINT32_MASK = type(uint32).max; uint256 constant UINT64_MASK = type(uint64).max; @@ -402,6 +404,67 @@ library SystemContractHelper { } } + /// @notice Force deploys some bytecode hash to an address + /// without invoking the constructor. + /// @param _addr The address to force-deploy the bytecodehash to. + /// @param _bytecodeHash The bytecode hash to force-deploy. + function forceDeployNoConstructor(address _addr, bytes32 _bytecodeHash) internal { + ForceDeployment[] memory deployments = new ForceDeployment[](1); + deployments[0] = ForceDeployment({ + bytecodeHash: _bytecodeHash, + newAddress: _addr, + callConstructor: false, + value: 0, + input: hex"" + }); + mimicCallWithPropagatedRevert( + address(DEPLOYER_SYSTEM_CONTRACT), + FORCE_DEPLOYER, + abi.encodeCall(IContractDeployer.forceDeployOnAddresses, deployments) + ); + } + + /// @notice Reads a certain storage slot from a contract. + /// @param _addr The address to read the slot from. + /// @param _key The key to read. + /// @return result The value stored at slot `_key` under the address `_addr`. + /// @dev zkEVM similarly to EVM only has an opcode to read + /// from the current contract's storage. However, sometimes system contracts + /// may require to read private storage slots of a contract. In order to provide + /// generic functionality to read arbitrary storage slots from other contracts, the following + /// scheme is used: + /// 1. Force-deploy `SloadContract` to the address. + /// 2. Read the required slot. + /// 3. Force-deploy the previous bytecode back. + function forcedSload(address _addr, bytes32 _key) internal returns (bytes32 result) { + bytes32 sloadContractBytecodeHash; + address sloadContractAddress = SLOAD_CONTRACT_ADDRESS; + assembly { + sloadContractBytecodeHash := extcodehash(sloadContractAddress) + } + + // Just in case, that the `sloadContractBytecodeHash` is known + if (KNOWN_CODE_STORAGE_CONTRACT.getMarker(sloadContractBytecodeHash) == 0) { + revert SloadContractBytecodeUnknown(); + } + + bytes32 previoushHash; + assembly { + previoushHash := extcodehash(_addr) + } + + // Just in case, double checking that the previous bytecode is known. + // It may be needed since `previoushHash` could be non-zero and unknown if it is + // equal to keccak(""). It is the case for used default accounts. + if (KNOWN_CODE_STORAGE_CONTRACT.getMarker(previoushHash) == 0) { + revert PreviousBytecodeUnknown(); + } + + forceDeployNoConstructor(_addr, sloadContractBytecodeHash); + result = SloadContract(_addr).sload(_key); + forceDeployNoConstructor(_addr, previoushHash); + } + /// @notice Performs a `mimicCall` to an address, while ensuring that the call /// was successful /// @param _to The address to call. diff --git a/system-contracts/contracts/test-contracts/CodeOracleTest.sol b/system-contracts/contracts/test-contracts/CodeOracleTest.sol index 31de9d366..f93a5d54a 100644 --- a/system-contracts/contracts/test-contracts/CodeOracleTest.sol +++ b/system-contracts/contracts/test-contracts/CodeOracleTest.sol @@ -2,6 +2,8 @@ pragma solidity ^0.8.20; +import {CodeOracleCallFailed, ReturnedBytecodeDoesNotMatchExpectedHash, SecondCallShouldHaveCostLessGas, ThirdCallShouldHaveSameGasCostAsSecondCall} from "contracts/SystemContractErrors.sol"; + address constant REAL_CODE_ORACLE_ADDR = 0x0000000000000000000000000000000000008011; contract CodeOracleTest { @@ -19,13 +21,14 @@ contract CodeOracleTest { gasCost = gasBefore - gasleft(); // Check the result - require(success, "CodeOracle call failed"); + if (!success) { + revert CodeOracleCallFailed(); + } // Check the returned bytecode - require( - keccak256(returnedBytecode) == _expectedBytecodeHash, - "Returned bytecode does not match the expected hash" - ); + if (keccak256(returnedBytecode) != _expectedBytecodeHash) { + revert ReturnedBytecodeDoesNotMatchExpectedHash(keccak256(returnedBytecode), _expectedBytecodeHash); + } } function codeOracleTest(bytes32 _versionedHash, bytes32 _expectedBytecodeHash) external view { @@ -35,7 +38,11 @@ contract CodeOracleTest { uint256 secondCallCost = this.callCodeOracle(_versionedHash, _expectedBytecodeHash); uint256 thirdCallCost = this.callCodeOracle(_versionedHash, _expectedBytecodeHash); - require(secondCallCost < firstCallCost, "The second call should have cost less gas"); - require(thirdCallCost == secondCallCost, "The third call should have the same gas cost as the second call"); + if (secondCallCost >= firstCallCost) { + revert SecondCallShouldHaveCostLessGas(secondCallCost, firstCallCost); + } + if (thirdCallCost != secondCallCost) { + revert ThirdCallShouldHaveSameGasCostAsSecondCall(thirdCallCost, secondCallCost); + } } } diff --git a/system-contracts/contracts/test-contracts/KeccakTest.sol b/system-contracts/contracts/test-contracts/KeccakTest.sol index 79581afc4..61cbcfea0 100644 --- a/system-contracts/contracts/test-contracts/KeccakTest.sol +++ b/system-contracts/contracts/test-contracts/KeccakTest.sol @@ -5,6 +5,7 @@ pragma abicoder v2; import {LOAD_LATEST_RETURNDATA_INTO_ACTIVE_PTR_CALL_ADDRESS, PTR_PACK_INTO_ACTIVE_CALL_ADDRESS, SystemContractsCaller, CalldataForwardingMode, RAW_FAR_CALL_BY_REF_CALL_ADDRESS} from "../libraries/SystemContractsCaller.sol"; import {EfficientCall, KECCAK256_SYSTEM_CONTRACT} from "../libraries/EfficientCall.sol"; +import {CallToKeccakShouldHaveSucceeded, KeccakReturnDataSizeShouldBe32Bytes, KeccakResultIsNotCorrect, KeccakShouldStartWorkingAgain, KeccakMismatchBetweenNumberOfInputsAndOutputs, KeccakHashWasNotCalculatedCorrectly} from "contracts/SystemContractErrors.sol"; // In this test it is important to actually change the real Keccak256's contract's bytecode, // which requires changes in the real AccountCodeStorage contract @@ -62,13 +63,17 @@ contract KeccakTest { _loadReturnDataIntoActivePtr(); _loadFarCallABIIntoActivePtr(1000000); bool success = rawCallByRef(KECCAK256_SYSTEM_CONTRACT); - require(success, "The call to keccak should have succeeded"); + if (!success) { + revert CallToKeccakShouldHaveSucceeded(); + } uint256 returndataSize = 0; assembly { returndataSize := returndatasize() } - require(returndataSize == 32, "The return data size should be 32 bytes"); + if (returndataSize != 32) { + revert KeccakReturnDataSizeShouldBe32Bytes(returndataSize); + } bytes32 result; assembly { @@ -76,7 +81,9 @@ contract KeccakTest { result := mload(0) } - require(result == EMPTY_STRING_KECCAK, "The result is not correct"); + if (result != EMPTY_STRING_KECCAK) { + revert KeccakResultIsNotCorrect(result); + } } function keccakUpgradeTest( @@ -110,7 +117,9 @@ contract KeccakTest { // Now it should work again hash = this.callKeccak(msg.data[0:0]); - require(hash == EMPTY_STRING_KECCAK, "Keccak should start working again"); + if (hash != EMPTY_STRING_KECCAK) { + revert KeccakShouldStartWorkingAgain(); + } } function keccakPerformUpgrade(bytes calldata upgradeCalldata) external { @@ -134,7 +143,9 @@ contract KeccakTest { bytes[] calldata testInputs, bytes32[] calldata expectedOutputs ) external { - require(testInputs.length == expectedOutputs.length, "mismatch between number of inputs and outputs"); + if (testInputs.length != expectedOutputs.length) { + revert KeccakMismatchBetweenNumberOfInputsAndOutputs(testInputs.length, expectedOutputs.length); + } // Firstly, we upgrade keccak256 bytecode to the correct version. EfficientCall.mimicCall({ @@ -154,7 +165,9 @@ contract KeccakTest { } for (uint256 i = 0; i < result.length; i++) { - require(result[i] == expectedOutputs[i], "hash was not calculated correctly"); + if (result[i] != expectedOutputs[i]) { + revert KeccakHashWasNotCalculatedCorrectly(result[i], expectedOutputs[i]); + } } // Upgrading it back to the original version: diff --git a/system-contracts/contracts/test-contracts/TransferTest.sol b/system-contracts/contracts/test-contracts/TransferTest.sol index ca76a9932..d554183be 100644 --- a/system-contracts/contracts/test-contracts/TransferTest.sol +++ b/system-contracts/contracts/test-contracts/TransferTest.sol @@ -2,6 +2,8 @@ pragma solidity ^0.8.20; +import {TransactionFailed, NotEnoughGas, TooMuchGas} from "contracts/SystemContractErrors.sol"; + contract TransferTest { function transfer(address payable to, uint256 amount, bool warmUpRecipient) public payable { if (warmUpRecipient) { @@ -20,7 +22,9 @@ contract TransferTest { bool success = to.send(amount); - require(success, "Transaction failed"); + if (!success) { + revert TransactionFailed(); + } } receive() external payable {} @@ -30,8 +34,12 @@ contract TransferTestRecipient { event Received(address indexed sender, uint256 amount); receive() external payable { - require(gasleft() >= 2100, "Not enough gas"); - require(gasleft() <= 2300, "Too much gas"); + if (gasleft() < 2100) { + revert NotEnoughGas(); + } + if (gasleft() > 2300) { + revert TooMuchGas(); + } emit Received(msg.sender, msg.value); } } diff --git a/system-contracts/package.json b/system-contracts/package.json index b1010c7ab..2c9c29850 100644 --- a/system-contracts/package.json +++ b/system-contracts/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@matterlabs/hardhat-zksync-chai-matchers": "^0.2.0", - "@matterlabs/hardhat-zksync-node": "^0.0.1-beta.7", + "@matterlabs/hardhat-zksync-node": "^1.2.0", "@nomicfoundation/hardhat-chai-matchers": "^1.0.3", "@nomiclabs/hardhat-ethers": "^2.0.0", "@typechain/ethers-v5": "^2.0.0", @@ -70,7 +70,7 @@ "verify-on-explorer": "hardhat run scripts/verify-on-explorer.ts", "test": "yarn build:test-system-contracts && hardhat test --network zkSyncTestNode", "test-no-build": "hardhat test --network zkSyncTestNode", - "test-node": "hardhat node-zksync --tag v0.0.1-vm1.5.0", + "test-node": "hardhat node-zksync --tag 0.1.0-alpha.29", "test:bootloader": "cd bootloader/test_infra && cargo run" } } diff --git a/system-contracts/scripts/constants.ts b/system-contracts/scripts/constants.ts index 171c2b9f3..0827b2df1 100644 --- a/system-contracts/scripts/constants.ts +++ b/system-contracts/scripts/constants.ts @@ -206,12 +206,28 @@ export const SYSTEM_CONTRACTS: ISystemContracts = { codeName: "L2NativeTokenVault", lang: Language.Solidity, }, - L2MessageRouter: { + L2MessageRoot: { // This is explicitly a non-system-contract address. // We do not use the same address as create2 factories on EVM, since // this is a zkEVM create2 factory. address: "0x0000000000000000000000000000000000010005", - codeName: "L2MessageRouter", + codeName: "MessageRoot", + lang: Language.Solidity, + }, + SloadContract: { + // This is explicitly a non-system-contract address. + // We do not use the same address as create2 factories on EVM, since + // this is a zkEVM create2 factory. + address: "0x0000000000000000000000000000000000010006", + codeName: "SloadContract", + lang: Language.Solidity, + }, + L2WrappedBaseTokenImplementation: { + // This is explicitly a non-system-contract address. + // We do not use the same address as create2 factories on EVM, since + // this is a zkEVM create2 factory. + address: "0x0000000000000000000000000000000000010007", + codeName: "L2WrappedBaseToken", lang: Language.Solidity, }, } as const; diff --git a/system-contracts/test/CodeOracle.spec.ts b/system-contracts/test/CodeOracle.spec.ts index d9b0c3781..e8838ff0b 100644 --- a/system-contracts/test/CodeOracle.spec.ts +++ b/system-contracts/test/CodeOracle.spec.ts @@ -60,7 +60,10 @@ describe("CodeOracle tests", function () { const versionedHash = hashBytecode(unknownLargeBytecode); const keccakHash = ethers.utils.keccak256(unknownLargeBytecode); - await expect(codeOracleTest.codeOracleTest(versionedHash, keccakHash)).to.be.rejectedWith("CodeOracle call failed"); + await expect(codeOracleTest.codeOracleTest(versionedHash, keccakHash)).to.be.revertedWithCustomError( + codeOracleTest, + "CodeOracleCallFailed" + ); }); after(async () => { diff --git a/system-contracts/test/DefaultAccount.spec.ts b/system-contracts/test/DefaultAccount.spec.ts index 9f3d380d3..6770746a4 100644 --- a/system-contracts/test/DefaultAccount.spec.ts +++ b/system-contracts/test/DefaultAccount.spec.ts @@ -38,7 +38,9 @@ describe("DefaultAccount tests", function () { mockERC20 = (await deployContract("MockContract")) as MockContract; paymasterFlowIface = new ethers.utils.Interface((await loadArtifact("IPaymasterFlow")).abi); - ERC20Iface = new ethers.utils.Interface((await loadArtifact("IERC20")).abi); + ERC20Iface = new ethers.utils.Interface( + (await loadArtifact("@openzeppelin/contracts-v4/token/ERC20/IERC20.sol:IERC20")).abi + ); bootloaderAccount = await ethers.getImpersonatedSigner(TEST_BOOTLOADER_FORMAL_ADDRESS); }); diff --git a/system-contracts/test/L1Messenger.spec.ts b/system-contracts/test/L1Messenger.spec.ts index 225b197d6..342385be0 100644 --- a/system-contracts/test/L1Messenger.spec.ts +++ b/system-contracts/test/L1Messenger.spec.ts @@ -287,7 +287,7 @@ describe("L1Messenger tests", () => { l1Messenger .connect(knownCodeStorageAccount) .requestBytecodeL1Publication(ethers.utils.hexlify(utils.hashBytecode(bytecode)), { - gasLimit: 230000000, + gasLimit: 2300000000, }) ) .to.emit(l1Messenger, "BytecodeL1PublicationRequested") diff --git a/system-contracts/test/L2GenesisUpgrade.spec.ts b/system-contracts/test/L2GenesisUpgrade.spec.ts index a7914f705..f2db34fb2 100644 --- a/system-contracts/test/L2GenesisUpgrade.spec.ts +++ b/system-contracts/test/L2GenesisUpgrade.spec.ts @@ -12,7 +12,7 @@ import { ADDRESS_ONE, } from "./shared/constants"; import { deployContractOnAddress, loadArtifact } from "./shared/utils"; -import { setResult } from "./shared/mocks"; +import { prepareEnvironment, setResult } from "./shared/mocks"; describe("L2GenesisUpgrade tests", function () { let l2GenesisUpgrade: L2GenesisUpgrade; @@ -35,17 +35,24 @@ describe("L2GenesisUpgrade tests", function () { let fixedForceDeploymentsData: string; const additionalForceDeploymentsData = ethers.utils.defaultAbiCoder.encode( - ["tuple(bytes32 baseTokenAssetId, address l2LegacySharedBridge, address l2Weth)"], + [ + "tuple(bytes32 baseTokenAssetId, address l2LegacySharedBridge, address predeployedL2WethAddress, address baseTokenL1Address, string baseTokenName, string baseTokenSymbol)", + ], [ { baseTokenAssetId: "0x0100056f53fd9e940906d998a80ed53392e5c50a8eb198baf9f78fd84ce7ec70", - l2LegacySharedBridge: ADDRESS_ONE, - l2Weth: ADDRESS_ONE, + l2LegacySharedBridge: ethers.constants.AddressZero, + predeployedL2WethAddress: ADDRESS_ONE, + baseTokenL1Address: ADDRESS_ONE, + baseTokenName: "Ether", + baseTokenSymbol: "ETH", }, ] ); before(async () => { + await prepareEnvironment(); + const wallet = await ethers.getImpersonatedSigner(TEST_FORCE_DEPLOYER_ADDRESS); await deployContractOnAddress(TEST_COMPLEX_UPGRADER_CONTRACT_ADDRESS, "ComplexUpgrader"); await deployContractOnAddress(TEST_L2_GENESIS_UPGRADE_CONTRACT_ADDRESS, "L2GenesisUpgrade"); @@ -90,7 +97,7 @@ describe("L2GenesisUpgrade tests", function () { fixedForceDeploymentsData = ethers.utils.defaultAbiCoder.encode( [ - "tuple(uint256 l1ChainId, uint256 eraChainId, address l1AssetRouter, bytes32 l2TokenProxyBytecodeHash, address aliasedL1Governance, uint256 maxNumberOfZKChains, bytes32 bridgehubBytecodeHash, bytes32 l2AssetRouterBytecodeHash, bytes32 l2NtvBytecodeHash, bytes32 messageRootBytecodeHash, address l2SharedBridgeLegacyImpl, address l2BridgedStandardERC20Impl, address l2BridgeProxyOwnerAddress, address l2BridgedStandardERC20ProxyOwnerAddress)", + "tuple(uint256 l1ChainId, uint256 eraChainId, address l1AssetRouter, bytes32 l2TokenProxyBytecodeHash, address aliasedL1Governance, uint256 maxNumberOfZKChains, bytes32 bridgehubBytecodeHash, bytes32 l2AssetRouterBytecodeHash, bytes32 l2NtvBytecodeHash, bytes32 messageRootBytecodeHash, address l2SharedBridgeLegacyImpl, address l2BridgedStandardERC20Impl)", ], [ { @@ -107,8 +114,6 @@ describe("L2GenesisUpgrade tests", function () { // For genesis upgrade these values will always be zero l2SharedBridgeLegacyImpl: ethers.constants.AddressZero, l2BridgedStandardERC20Impl: ethers.constants.AddressZero, - l2BridgeProxyOwnerAddress: ethers.constants.AddressZero, - l2BridgedStandardERC20ProxyOwnerAddress: ethers.constants.AddressZero, }, ] ); diff --git a/system-contracts/test/SystemContext.spec.ts b/system-contracts/test/SystemContext.spec.ts index 2117c59da..1848defe5 100644 --- a/system-contracts/test/SystemContext.spec.ts +++ b/system-contracts/test/SystemContext.spec.ts @@ -108,7 +108,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setNewBatch(batchHash, batchData.batchTimestamp, batchData.batchNumber.add(1), 1) - ).to.be.rejectedWith("Timestamps should be incremental"); + ).to.be.revertedWithCustomError(systemContext, "TimestampsShouldBeIncremental"); }); it("should revert wrong block number", async () => { @@ -118,7 +118,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setNewBatch(batchHash, batchData.batchTimestamp.add(1), batchData.batchNumber, 1) - ).to.be.rejectedWith("The provided batch number is not correct"); + ).to.be.revertedWithCustomError(systemContext, "ProvidedBatchNumberIsNotCorrect"); }); it("should set new batch", async () => { @@ -173,9 +173,7 @@ describe("SystemContext tests", () => { const expectedBlockHash = ethers.utils.keccak256(ethers.utils.solidityPack(["uint32"], [blockData.blockNumber])); await expect( systemContext.connect(bootloaderAccount).setL2Block(blockData.blockNumber.add(1), 0, expectedBlockHash, true, 1) - ).to.be.rejectedWith( - "The timestamp of the L2 block must be greater than or equal to the timestamp of the current batch" - ); + ).to.be.revertedWithCustomError(systemContext, "L2BlockAndBatchTimestampMismatch"); }); it("should revert There must be a virtual block created at the start of the batch", async () => { @@ -185,7 +183,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(1), blockData.blockTimestamp.add(42), expectedBlockHash, true, 0) - ).to.be.rejectedWith("There must be a virtual block created at the start of the batch"); + ).to.be.revertedWithCustomError(systemContext, "NoVirtualBlocks"); }); it("should revert Upgrade transaction must be first", async () => { @@ -195,7 +193,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(1), blockData.blockTimestamp.add(42), expectedBlockHash, false, 1) - ).to.be.rejectedWith("Upgrade transaction must be first"); + ).to.be.revertedWithCustomError(systemContext, "UpgradeTransactionMustBeFirst"); }); it("should revert L2 block number is never expected to be zero", async () => { @@ -205,7 +203,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(0, blockData.blockTimestamp.add(42), expectedBlockHash, true, 1) - ).to.be.rejectedWith("L2 block number is never expected to be zero"); + ).to.be.revertedWithCustomError(systemContext, "L2BlockNumberZero"); }); it("should revert The previous L2 block hash is incorrect", async () => { @@ -215,7 +213,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(1), blockData.blockTimestamp.add(42), wrongBlockHash, true, 1) - ).to.be.rejectedWith("The previous L2 block hash is incorrect"); + ).to.be.revertedWithCustomError(systemContext, "PreviousL2BlockHashIsIncorrect"); }); it("should set L2 block, check blockNumber & blockTimestamp change, also check getBlockHashEVM", async () => { @@ -248,7 +246,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber, blockData.blockTimestamp.add(42), expectedBlockHash, true, 1) - ).to.be.rejectedWith("Can not reuse L2 block number from the previous batch"); + ).to.be.revertedWithCustomError(systemContext, "CannotReuseL2BlockNumberFromPreviousBatch"); }); it("should revert The timestamp of the same L2 block must be same", async () => { @@ -258,7 +256,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber, blockData.blockTimestamp.add(42), expectedBlockHash, false, 1) - ).to.be.rejectedWith("The timestamp of the same L2 block must be same"); + ).to.be.revertedWithCustomError(systemContext, "IncorrectSameL2BlockTimestamp"); }); it("should revert The previous hash of the same L2 block must be same", async () => { @@ -270,7 +268,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber, blockData.blockTimestamp, expectedBlockHash, false, 1) - ).to.be.rejectedWith("The previous hash of the same L2 block must be same"); + ).to.be.revertedWithCustomError(systemContext, "IncorrectSameL2BlockPrevBlockHash"); }); it("should revert Can not create virtual blocks in the middle of the miniblock", async () => { @@ -282,7 +280,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber, blockData.blockTimestamp, expectedBlockHash, false, 1) - ).to.be.rejectedWith("Can not create virtual blocks in the middle of the miniblock"); + ).to.be.revertedWithCustomError(systemContext, "IncorrectVirtualBlockInsideMiniblock"); }); it("should set block again, no data changed", async () => { @@ -307,7 +305,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(1), blockData.blockTimestamp.add(42), invalidBlockHash, false, 0) - ).to.be.rejectedWith("The current L2 block hash is incorrect"); + ).to.be.revertedWithCustomError(systemContext, "IncorrectL2BlockHash"); }); it("should revert The timestamp of the new L2 block must be greater than the timestamp of the previous L2 block", async () => { @@ -326,9 +324,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(1), 0, expectedBlockHash, false, 0) - ).to.be.rejectedWith( - "The timestamp of the new L2 block must be greater than the timestamp of the previous L2 block" - ); + ).to.be.revertedWithCustomError(systemContext, "NonMonotonicL2BlockTimestamp"); }); it("should set block again and check blockNumber & blockTimestamp also check getBlockHashEVM", async () => { @@ -363,7 +359,7 @@ describe("SystemContext tests", () => { systemContext .connect(bootloaderAccount) .setL2Block(blockData.blockNumber.add(111), blockData.blockTimestamp.add(42), expectedBlockHash, false, 0) - ).to.be.rejectedWith("Invalid new L2 block number"); + ).to.be.revertedWithCustomError(systemContext, "InvalidNewL2BlockNumber"); }); it("should update currentL2BlockTxsRollingHash", async () => { @@ -384,8 +380,9 @@ describe("SystemContext tests", () => { const batchData = await systemContext.getBatchNumberAndTimestamp(); const baseFee = await systemContext.baseFee(); await systemContext.connect(bootloaderAccount).unsafeOverrideBatch(batchData.batchTimestamp, 0, baseFee); - await expect(systemContext.connect(bootloaderAccount).publishTimestampDataToL1()).to.be.rejectedWith( - "The current batch number must be greater than 0" + await expect(systemContext.connect(bootloaderAccount).publishTimestampDataToL1()).to.be.revertedWithCustomError( + systemContext, + "CurrentBatchNumberMustBeGreaterThanZero" ); await systemContext .connect(bootloaderAccount) diff --git a/yarn.lock b/yarn.lock index 2677c503c..96046f0a2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -722,6 +722,23 @@ chalk "4.1.2" fs-extra "^11.1.1" +"@matterlabs/hardhat-zksync-node@^1.2.0": + version "1.2.0" + resolved "https://registry.yarnpkg.com/@matterlabs/hardhat-zksync-node/-/hardhat-zksync-node-1.2.0.tgz#800b24d33ca3a35c92afdc75d1ab05a6a957b15f" + integrity sha512-cTL8FrsolQEJMn2K25Nj/78rydRs/YiQyUu3Q1Rn5axrtVWXWATUP4z7hE5qH2lWk3VZcC9GYFrewP5c1Q+A9Q== + dependencies: + "@matterlabs/hardhat-zksync-solc" "^1.2.5" + axios "^1.7.2" + chai "^4.3.4" + chalk "^4.1.2" + debug "^4.3.5" + fs-extra "^11.2.0" + proxyquire "^2.1.3" + sinon "^18.0.0" + sinon-chai "^3.7.0" + source-map-support "^0.5.21" + undici "^6.18.2" + "@matterlabs/hardhat-zksync-solc@0.4.2": version "0.4.2" resolved "https://registry.yarnpkg.com/@matterlabs/hardhat-zksync-solc/-/hardhat-zksync-solc-0.4.2.tgz#64121082e88c5ab22eb4e9594d120e504f6af499" @@ -772,6 +789,23 @@ chalk "4.1.2" dockerode "^3.3.4" +"@matterlabs/hardhat-zksync-solc@^1.2.5": + version "1.2.5" + resolved "https://registry.yarnpkg.com/@matterlabs/hardhat-zksync-solc/-/hardhat-zksync-solc-1.2.5.tgz#fbeeabc3fea0dd232fa3c8cb31bd93c103eba11a" + integrity sha512-iZyznWl1Hoe/Z46hnUe1s2drBZBjJOS/eN+Ql2lIBX9B6NevBl9DYzkKzH5HEIMCLGnX9sWpRAJqUQJWy9UB6w== + dependencies: + "@nomiclabs/hardhat-docker" "^2.0.2" + chai "^4.3.4" + chalk "^4.1.2" + debug "^4.3.5" + dockerode "^4.0.2" + fs-extra "^11.2.0" + proper-lockfile "^4.1.2" + semver "^7.6.2" + sinon "^18.0.0" + sinon-chai "^3.7.0" + undici "^6.18.2" + "@matterlabs/hardhat-zksync-verify@0.6.1": version "0.6.1" resolved "https://registry.yarnpkg.com/@matterlabs/hardhat-zksync-verify/-/hardhat-zksync-verify-0.6.1.tgz#3fd83f4177ac0b138656ed93d4756ec27f1d329d" @@ -1181,7 +1215,7 @@ "@nomicfoundation/solidity-analyzer-win32-ia32-msvc" "0.1.1" "@nomicfoundation/solidity-analyzer-win32-x64-msvc" "0.1.1" -"@nomiclabs/hardhat-docker@^2.0.0": +"@nomiclabs/hardhat-docker@^2.0.0", "@nomiclabs/hardhat-docker@^2.0.2": version "2.0.2" resolved "https://registry.yarnpkg.com/@nomiclabs/hardhat-docker/-/hardhat-docker-2.0.2.tgz#ae964be17951275a55859ff7358e9e7c77448846" integrity sha512-XgGEpRT3wlA1VslyB57zyAHV+oll8KnV1TjwnxxC1tpAL04/lbdwpdO5KxInVN8irMSepqFpsiSkqlcnvbE7Ng== @@ -1415,20 +1449,27 @@ dependencies: type-detect "4.0.8" -"@sinonjs/commons@^3.0.0": +"@sinonjs/commons@^3.0.0", "@sinonjs/commons@^3.0.1": version "3.0.1" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-3.0.1.tgz#1029357e44ca901a615585f6d27738dbc89084cd" integrity sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ== dependencies: type-detect "4.0.8" -"@sinonjs/fake-timers@^11.2.2": +"@sinonjs/fake-timers@11.2.2", "@sinonjs/fake-timers@^11.2.2": version "11.2.2" resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-11.2.2.tgz#50063cc3574f4a27bd8453180a04171c85cc9699" integrity sha512-G2piCSxQ7oWOxwGSAyFHfPIsyeJGXYtc6mFbnFA+kRXkiEnTl8c/8jul2S329iFBnDI9HGoeWWAZvuvOkZccgw== dependencies: "@sinonjs/commons" "^3.0.0" +"@sinonjs/fake-timers@^13.0.1": + version "13.0.5" + resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-13.0.5.tgz#36b9dbc21ad5546486ea9173d6bea063eb1717d5" + integrity sha512-36/hTbH2uaWuGVERyC6da9YwGWnzUZXuPro/F2LfsdOsLnCojz/iSH8MxUt/FD2S5XBSVPhmArFUXcpCQ2Hkiw== + dependencies: + "@sinonjs/commons" "^3.0.1" + "@sinonjs/samsam@^8.0.0": version "8.0.0" resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-8.0.0.tgz#0d488c91efb3fa1442e26abea81759dfc8b5ac60" @@ -1443,6 +1484,11 @@ resolved "https://registry.yarnpkg.com/@sinonjs/text-encoding/-/text-encoding-0.7.2.tgz#5981a8db18b56ba38ef0efb7d995b12aa7b51918" integrity sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ== +"@sinonjs/text-encoding@^0.7.3": + version "0.7.3" + resolved "https://registry.yarnpkg.com/@sinonjs/text-encoding/-/text-encoding-0.7.3.tgz#282046f03e886e352b2d5f5da5eb755e01457f3f" + integrity sha512-DE427ROAphMQzU4ENbliGYrBSYPXF+TtLg9S8vzeA+OF4ZKzoDdzfL8sxuMUGS/lgRhM6j1URSk9ghf7Xo1tyA== + "@solidity-parser/parser@^0.14.0": version "0.14.5" resolved "https://registry.yarnpkg.com/@solidity-parser/parser/-/parser-0.14.5.tgz#87bc3cc7b068e08195c219c91cd8ddff5ef1a804" @@ -2229,6 +2275,15 @@ axios@^1.6.2: form-data "^4.0.0" proxy-from-env "^1.1.0" +axios@^1.7.2: + version "1.7.7" + resolved "https://registry.yarnpkg.com/axios/-/axios-1.7.7.tgz#2f554296f9892a72ac8d8e4c5b79c14a91d0a47f" + integrity sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q== + dependencies: + follow-redirects "^1.15.6" + form-data "^4.0.0" + proxy-from-env "^1.1.0" + babel-runtime@^6.26.0: version "6.26.0" resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe" @@ -2551,6 +2606,19 @@ chai@^4.3.10, chai@^4.3.6, chai@^4.3.7: pathval "^1.1.1" type-detect "^4.0.8" +chai@^4.3.4: + version "4.5.0" + resolved "https://registry.yarnpkg.com/chai/-/chai-4.5.0.tgz#707e49923afdd9b13a8b0b47d33d732d13812fd8" + integrity sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw== + dependencies: + assertion-error "^1.1.0" + check-error "^1.0.3" + deep-eql "^4.1.3" + get-func-name "^2.0.2" + loupe "^2.3.6" + pathval "^1.1.1" + type-detect "^4.1.0" + chalk@4.1.2, chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.2: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" @@ -2963,6 +3031,13 @@ debug@^3.1.0, debug@^3.2.6, debug@^3.2.7: dependencies: ms "^2.1.1" +debug@^4.3.5: + version "4.3.7" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.7.tgz#87945b4151a011d76d95a198d7111c865c360a52" + integrity sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ== + dependencies: + ms "^2.1.3" + decamelize@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-4.0.0.tgz#aa472d7bf660eb15f3494efd531cab7f2a709837" @@ -3043,7 +3118,7 @@ diff@^4.0.1: resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== -diff@^5.1.0: +diff@^5.1.0, diff@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.2.0.tgz#26ded047cd1179b78b9537d5ef725503ce1ae531" integrity sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A== @@ -3875,6 +3950,14 @@ file-entry-cache@^6.0.1: dependencies: flat-cache "^3.0.4" +fill-keys@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/fill-keys/-/fill-keys-1.0.2.tgz#9a8fa36f4e8ad634e3bf6b4f3c8882551452eb20" + integrity sha512-tcgI872xXjwFF4xgQmLxi76GnwJG3g/3isB1l4/G5Z4zrbddGpBjqZCO9oEAcB5wX0Hj/5iQB3toxfO7in1hHA== + dependencies: + is-object "~1.0.1" + merge-descriptors "~1.0.0" + fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" @@ -4006,7 +4089,7 @@ fs-extra@^0.30.0: path-is-absolute "^1.0.0" rimraf "^2.2.8" -fs-extra@^11.1.1: +fs-extra@^11.1.1, fs-extra@^11.2.0: version "11.2.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-11.2.0.tgz#e70e17dfad64232287d01929399e0ea7c86b0e5b" integrity sha512-PmDi3uwK5nFuXh7XDTlVnS17xJS7vW36is2+w3xcv8SVxiB4NyATf4ctkVY5bkSjX0Y4nbvZCq1/EjtEyr9ktw== @@ -4910,6 +4993,11 @@ is-number@^7.0.0: resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== +is-object@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-object/-/is-object-1.0.2.tgz#a56552e1c665c9e950b4a025461da87e72f86fcf" + integrity sha512-2rRIahhZr2UWb45fIOuvZGpFtz0TyOZLf32KxBbSoUCeZR495zCKlWUKKUByk3geS2eAs7ZAABt0Y/Rx0GiQGA== + is-path-inside@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" @@ -5553,6 +5641,11 @@ memorystream@^0.3.1: resolved "https://registry.yarnpkg.com/memorystream/-/memorystream-0.3.1.tgz#86d7090b30ce455d63fbae12dda51a47ddcaf9b2" integrity sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw== +merge-descriptors@~1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.3.tgz#d80319a65f3c7935351e5cfdac8f9318504dbed5" + integrity sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ== + merge2@^1.2.3, merge2@^1.3.0, merge2@^1.4.1: version "1.4.1" resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" @@ -5766,6 +5859,11 @@ mocha@^9.0.2: yargs-parser "20.2.4" yargs-unparser "2.0.0" +module-not-found-error@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/module-not-found-error/-/module-not-found-error-1.0.1.tgz#cf8b4ff4f29640674d6cdd02b0e3bc523c2bbdc0" + integrity sha512-pEk4ECWQXV6z2zjhRZUongnLJNUeGQJ3w6OQ5ctGwD+i5o93qjRQUk2Rt6VdNeu3sEP0AB4LcfvdebpxBRVr4g== + ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" @@ -5776,7 +5874,7 @@ ms@2.1.2: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -ms@2.1.3, ms@^2.1.1: +ms@2.1.3, ms@^2.1.1, ms@^2.1.3: version "2.1.3" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== @@ -5817,6 +5915,17 @@ nise@^5.1.5: just-extend "^6.2.0" path-to-regexp "^6.2.1" +nise@^6.0.0: + version "6.1.1" + resolved "https://registry.yarnpkg.com/nise/-/nise-6.1.1.tgz#78ea93cc49be122e44cb7c8fdf597b0e8778b64a" + integrity sha512-aMSAzLVY7LyeM60gvBS423nBmIPP+Wy7St7hsb+8/fc1HmeoHJfLO8CKse4u3BtOZvQLJghYPI2i/1WZrEj5/g== + dependencies: + "@sinonjs/commons" "^3.0.1" + "@sinonjs/fake-timers" "^13.0.1" + "@sinonjs/text-encoding" "^0.7.3" + just-extend "^6.2.0" + path-to-regexp "^8.1.0" + node-addon-api@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.2.tgz#432cfa82962ce494b132e9d72a15b29f71ff5d32" @@ -6104,6 +6213,11 @@ path-to-regexp@^6.2.1: resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-6.2.2.tgz#324377a83e5049cbecadc5554d6a63a9a4866b36" integrity sha512-GQX3SSMokngb36+whdpRXE+3f9V8UzyAorlYvOGx87ufGHehNTn5lCxrKtLyZ4Yl/wEKnNnr98ZzOwwDZV5ogw== +path-to-regexp@^8.1.0: + version "8.2.0" + resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-8.2.0.tgz#73990cc29e57a3ff2a0d914095156df5db79e8b4" + integrity sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ== + path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" @@ -6255,6 +6369,15 @@ proxy-from-env@^1.1.0: resolved "https://registry.yarnpkg.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz#e102f16ca355424865755d2c9e8ea4f24d58c3e2" integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg== +proxyquire@^2.1.3: + version "2.1.3" + resolved "https://registry.yarnpkg.com/proxyquire/-/proxyquire-2.1.3.tgz#2049a7eefa10a9a953346a18e54aab2b4268df39" + integrity sha512-BQWfCqYM+QINd+yawJz23tbBM40VIGXOdDw3X344KcclI/gtBbdWF6SlQ4nK/bYhF9d27KYug9WzljHC6B9Ysg== + dependencies: + fill-keys "^1.0.2" + module-not-found-error "^1.0.1" + resolve "^1.11.1" + prr@~1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476" @@ -6514,7 +6637,7 @@ resolve@1.17.0: dependencies: path-parse "^1.0.6" -resolve@^1.1.6, resolve@^1.22.4, resolve@^1.8.1: +resolve@^1.1.6, resolve@^1.11.1, resolve@^1.22.4, resolve@^1.8.1: version "1.22.8" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.8.tgz#b6c87a9f2aa06dfab52e3d70ac8cde321fa5a48d" integrity sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw== @@ -6698,6 +6821,11 @@ semver@^7.3.7: resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.1.tgz#60bfe090bf907a25aa8119a72b9f90ef7ca281b2" integrity sha512-f/vbBsu+fOiYt+lmwZV0rVwJScl46HppnOA1ZvIuBWKOTlllpyJ3bfVax76/OrhCH38dyxoDIA8K7uB963IYgA== +semver@^7.6.2: + version "7.6.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" + integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== + serialize-javascript@6.0.0: version "6.0.0" resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" @@ -6811,6 +6939,18 @@ sinon@^17.0.1: nise "^5.1.5" supports-color "^7.2.0" +sinon@^18.0.0: + version "18.0.1" + resolved "https://registry.yarnpkg.com/sinon/-/sinon-18.0.1.tgz#464334cdfea2cddc5eda9a4ea7e2e3f0c7a91c5e" + integrity sha512-a2N2TDY1uGviajJ6r4D1CyRAkzE9NNVlYOV1wX5xQDuAk0ONgzgRl0EjCQuRCPxOwp13ghsMwt9Gdldujs39qw== + dependencies: + "@sinonjs/commons" "^3.0.1" + "@sinonjs/fake-timers" "11.2.2" + "@sinonjs/samsam" "^8.0.0" + diff "^5.2.0" + nise "^6.0.0" + supports-color "^7" + slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" @@ -6967,7 +7107,7 @@ solidity-coverage@^0.8.5: shelljs "^0.8.3" web3-utils "^1.3.6" -source-map-support@^0.5.13: +source-map-support@^0.5.13, source-map-support@^0.5.21: version "0.5.21" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== @@ -7161,7 +7301,7 @@ supports-color@^5.3.0: dependencies: has-flag "^3.0.0" -supports-color@^7.1.0, supports-color@^7.2.0: +supports-color@^7, supports-color@^7.1.0, supports-color@^7.2.0: version "7.2.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== @@ -7487,6 +7627,11 @@ type-detect@4.0.8, type-detect@^4.0.0, type-detect@^4.0.8: resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== +type-detect@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.1.0.tgz#deb2453e8f08dcae7ae98c626b13dddb0155906c" + integrity sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw== + type-fest@^0.20.2: version "0.20.2" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" @@ -7637,6 +7782,11 @@ undici@^5.14.0: dependencies: "@fastify/busboy" "^2.0.0" +undici@^6.18.2: + version "6.20.1" + resolved "https://registry.yarnpkg.com/undici/-/undici-6.20.1.tgz#fbb87b1e2b69d963ff2d5410a40ffb4c9e81b621" + integrity sha512-AjQF1QsmqfJys+LXfGTNum+qw4S88CojRInG/6t31W/1fk6G59s92bnAvGz5Cmur+kQv2SURXEvvudLmbrE8QA== + universalify@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"