Abstract Testnet

Contract Diff Checker

Contract Name:
AGWAccount

Contract Source Code:

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {IAccount, ACCOUNT_VALIDATION_SUCCESS_MAGIC} from '@matterlabs/zksync-contracts/l2/system-contracts/interfaces/IAccount.sol';
import {Transaction, TransactionHelper} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/TransactionHelper.sol';
import {EfficientCall} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/EfficientCall.sol';
import {BOOTLOADER_FORMAL_ADDRESS, NONCE_HOLDER_SYSTEM_CONTRACT, DEPLOYER_SYSTEM_CONTRACT, INonceHolder} from '@matterlabs/zksync-contracts/l2/system-contracts/Constants.sol';
import {SystemContractsCaller} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/SystemContractsCaller.sol';
import {SystemContractHelper} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/SystemContractHelper.sol';
import {Utils} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/Utils.sol';
import {Initializable} from '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';

import {HookManager} from './managers/HookManager.sol';
import {ModuleManager} from './managers/ModuleManager.sol';
import {UpgradeManager} from './managers/UpgradeManager.sol';

import {TokenCallbackHandler, IERC165} from './helpers/TokenCallbackHandler.sol';

import {Errors} from './libraries/Errors.sol';
import {SignatureDecoder} from './libraries/SignatureDecoder.sol';

import {ERC1271Handler} from './handlers/ERC1271Handler.sol';
import {Call} from './batch/BatchCaller.sol';

import {IAGWAccount} from './interfaces/IAGWAccount.sol';
import {OperationType} from './interfaces/IValidator.sol';
import {AccountFactory} from './AccountFactory.sol';
import {BatchCaller} from './batch/BatchCaller.sol';

/**
 * @title Main account contract for the Abstract Global Wallet infrastructure
 * @dev Forked from Clave for Abstract
 * @dev The Abstract fork uses a K1 signer and validator initially
 * @author https://getclave.io
 * @author https://abs.xyz
 */
contract AGWAccount is
    Initializable,
    UpgradeManager,
    HookManager,
    ModuleManager,
    ERC1271Handler,
    TokenCallbackHandler,
    BatchCaller,
    IAGWAccount
{
    // Helper library for the Transaction struct
    using TransactionHelper for Transaction;

    uint256 public constant VERSION = 1;

    address public immutable KNOWN_TRUSTED_EOA_VALIDATOR;

    /**
     * @notice Constructor for the account implementation
     */
    constructor(address knownTrustedEoaValidator) {
        KNOWN_TRUSTED_EOA_VALIDATOR = knownTrustedEoaValidator;
        _disableInitializers();
    }

    /**
     * @notice Initializer function for the account contract
     * @param initialK1Owner bytes address - The initial k1 owner of the account
     * @param initialK1Validator address    - The initial k1 validator of the account
     * @param modules bytes[] calldata      - The list of modules to enable for the account
     * @param initCall Call calldata         - The initial call to be executed after the account is created
     */
    function initialize(
        address initialK1Owner,
        address initialK1Validator,
        bytes[] calldata modules,
        Call calldata initCall
    ) public payable initializer {
        __ERC1271Handler_init();
        // check that this account is being deployed by the initial signer or the factory authorized deployer
        AccountFactory factory = AccountFactory(msg.sender);
        // require a specific salt for the acccount based on the initial k1 owner
        address expectedAddress = factory.getAddressForSalt(keccak256(abi.encodePacked(initialK1Owner)));
        if (address(this) != expectedAddress) {
            revert Errors.INVALID_SALT();
        }

        // add the initial k1 owner as an owner
        _k1AddOwner(initialK1Owner);

        address thisDeployer = factory.accountToDeployer(address(this));
        if (!factory.authorizedDeployers(thisDeployer)) {
            if (initialK1Owner != thisDeployer) {
                // disregard any modules and initial call as the deployer is untrusted
                _k1AddValidator(KNOWN_TRUSTED_EOA_VALIDATOR);
                return;
            }
        }

        _k1AddValidator(initialK1Validator);

        for (uint256 i = 0; i < modules.length; ) {
            _addModule(modules[i]);
            unchecked {
                i++;
            }
        }

        if (initCall.target != address(0)) {
            uint128 value = Utils.safeCastToU128(initCall.value);
            _executeCall(initCall.target, value, initCall.callData, initCall.allowFailure);
        }
    }

    // Receive function to allow ETH to be sent to the account
    // with no additional calldata
    receive() external payable {}
    
    // Fallback function to allow ETH to be sent to the account
    // with arbitrary calldata to mirror the behavior of an EOA
    fallback() external payable {
        // Simulate the behavior of the EOA if it is called via `delegatecall`.
        address codeAddress = SystemContractHelper.getCodeAddress();
        if (codeAddress != address(this)) {
            // If the function was delegate called, behave like an EOA.
            assembly {
                return(0, 0)
            }
        }

        // fallback of default account shouldn't be called by bootloader under any circumstances
        assert(msg.sender != BOOTLOADER_FORMAL_ADDRESS);

        // If the contract is called directly, behave like an EOA
    }

    /**
     * @notice Called by the bootloader to validate that an account agrees to process the transaction
     * (and potentially pay for it).
     * @dev The developer should strive to preserve as many steps as possible both for valid
     * and invalid transactions as this very method is also used during the gas fee estimation
     * (without some of the necessary data, e.g. signature).
     * @param - bytes32                        - Not used
     * @param suggestedSignedHash bytes32      - The suggested hash of the transaction that is signed by the signer
     * @param transaction Transaction calldata - The transaction itself
     * @return magic bytes4 - The magic value that should be equal to the signature of this function
     * if the user agrees to proceed with the transaction.
     */
    function validateTransaction(
        bytes32,
        bytes32 suggestedSignedHash,
        Transaction calldata transaction
    ) external payable override onlyBootloader returns (bytes4 magic) {
        _incrementNonce(transaction.nonce);

        // The fact there is enough balance for the account
        // should be checked explicitly to prevent user paying for fee for a
        // transaction that wouldn't be included on Ethereum.
        if (transaction.totalRequiredBalance() > address(this).balance) {
            revert Errors.INSUFFICIENT_FUNDS();
        }

        // While the suggested signed hash is usually provided, it is generally
        // not recommended to rely on it to be present, since in the future
        // there may be tx types with no suggested signed hash.
        bytes32 signedHash = suggestedSignedHash == bytes32(0)
            ? transaction.encodeHash()
            : suggestedSignedHash;

        magic = _validateTransaction(signedHash, transaction);
    }

    /**
     * @notice Called by the bootloader to make the account execute the transaction.
     * @dev The transaction is considered successful if this function does not revert
     * @param - bytes32                        - Not used
     * @param - bytes32                        - Not used
     * @param transaction Transaction calldata - The transaction itself
     */
    function executeTransaction(
        bytes32,
        bytes32,
        Transaction calldata transaction
    ) external payable override onlyBootloader {
        _executeTransaction(transaction);
    }

    /**
     * @notice This function allows an EOA to start a transaction for the account.
     * @dev There is no point in providing possible signed hash in the `executeTransactionFromOutside` method,
     * since it typically should not be trusted.
     * @param transaction Transaction calldata - The transaction itself
     */
    function executeTransactionFromOutside(
        Transaction calldata transaction
    ) external payable override {
        // Check if msg.sender is authorized
        if (!_k1IsOwner(msg.sender)) {
            revert Errors.UNAUTHORIZED_OUTSIDE_TRANSACTION();
        }

        // Extract hook data from transaction.signature
        bytes[] memory hookData = SignatureDecoder.decodeSignatureOnlyHookData(
            transaction.signature
        );

        // Get the hash of the transaction
        bytes32 signedHash = transaction.encodeHash();

        // Run the validation hooks
        if (!runValidationHooks(signedHash, transaction, hookData)) {
            revert Errors.VALIDATION_HOOK_FAILED();
        }

        _incrementNonce(transaction.nonce);
        _executeTransaction(transaction);
    }

    /**
     * @notice This function allows the account to pay for its own gas and used when there is no paymaster
     * @param - bytes32                        - not used
     * @param - bytes32                        - not used
     * @param transaction Transaction calldata - Transaction to pay for
     * @dev "This method must send at least `tx.gasprice * tx.gasLimit` ETH to the bootloader address."
     */
    function payForTransaction(
        bytes32,
        bytes32,
        Transaction calldata transaction
    ) external payable override onlyBootloader {
        bool success = transaction.payToTheBootloader();

        if (!success) {
            revert Errors.FEE_PAYMENT_FAILED();
        }

        emit FeePaid();
    }

    /**
     * @notice This function is called by the system if the transaction has a paymaster
        and prepares the interaction with the paymaster
     * @param - bytes32               - not used 
     * @param - bytes32               - not used 
     * @param transaction Transaction - The transaction itself
     */
    function prepareForPaymaster(
        bytes32,
        bytes32,
        Transaction calldata transaction
    ) external payable override onlyBootloader {
        transaction.processPaymasterInput();
    }

    /// @dev type(IAGWAccount).interfaceId indicates AGW accounts
    function supportsInterface(
        bytes4 interfaceId
    ) public view override(IERC165, TokenCallbackHandler) returns (bool) {
        return
            interfaceId == type(IAGWAccount).interfaceId || super.supportsInterface(interfaceId);
    }

    function _validateTransaction(
        bytes32 signedHash,
        Transaction calldata transaction
    ) internal returns (bytes4 magicValue) {
        if (transaction.signature.length == 65) {
            // This is a gas estimation
            return bytes4(0);
        }
        
        // Extract the signature, validator address and hook data from the transaction.signature
        (bytes memory signature, address validator, bytes[] memory hookData) = SignatureDecoder
            .decodeSignature(transaction.signature);

        // Run validation hooks
        bool hookSuccess = runValidationHooks(signedHash, transaction, hookData);

        // Handle validation
        bool valid = _handleValidation(validator, OperationType.Transaction, signedHash, signature);

        magicValue = (hookSuccess && valid) ? ACCOUNT_VALIDATION_SUCCESS_MAGIC : bytes4(0);
    }

    function _executeTransaction(
        Transaction calldata transaction
    ) internal runExecutionHooks(transaction) {
        address to = _safeCastToAddress(transaction.to);
        uint128 value = Utils.safeCastToU128(transaction.value);
        bytes calldata data = transaction.data;

        _executeCall(to, value, data, false);
    }

    function _executeCall(
        address to,
        uint128 value,
        bytes calldata data,
        bool allowFailure
    ) internal {
        uint32 gas = Utils.safeCastToU32(gasleft());

        if (to == address(DEPLOYER_SYSTEM_CONTRACT)) {
            // Note, that the deployer contract can only be called
            // with a "systemCall" flag.
            (bool success, bytes memory returnData) = SystemContractsCaller
                .systemCallWithReturndata(gas, to, value, data);
            if (!success && !allowFailure) {
                assembly {
                    let size := mload(returnData)
                    revert(add(returnData, 0x20), size)
                }
            }
        } else {
            bool success = EfficientCall.rawCall(gas, to, value, data, false);
            if (!success && !allowFailure) {
                EfficientCall.propagateRevert();
            }
        }
    }

    function _incrementNonce(uint256 nonce) internal {
        SystemContractsCaller.systemCallWithPropagatedRevert(
            uint32(gasleft()),
            address(NONCE_HOLDER_SYSTEM_CONTRACT),
            0,
            abi.encodeCall(INonceHolder.incrementMinNonceIfEquals, (nonce))
        );
    }

    function _safeCastToAddress(uint256 value) internal pure returns (address) {
        if (value > type(uint160).max) revert();
        return address(uint160(value));
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {DEPLOYER_SYSTEM_CONTRACT, IContractDeployer} from '@matterlabs/zksync-contracts/l2/system-contracts/Constants.sol';
import {SystemContractsCaller} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/SystemContractsCaller.sol';
import {Ownable, Ownable2Step} from '@openzeppelin/contracts/access/Ownable2Step.sol';
import {EfficientCall} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/EfficientCall.sol';
import {Errors} from './libraries/Errors.sol';
import {IAGWRegistry} from './interfaces/IAGWRegistry.sol';

/**
 * @title Factory contract to create AGW accounts
 * @dev Forked from Clave for Abstract
 * @author https://abs.xyz
 * @author https://getclave.io
 */
contract AccountFactory is Ownable2Step {
    
    /**
     * @notice Address of the account implementation
     */
    address public implementationAddress;
    /**
     * @notice Allowed selector for account initialization
     */
    bytes4 public initializerSelector;

    /**
     * @notice Account registry contract address
     */
    address public registry;

    /**
     * @notice Account creation bytecode hash
     */
    bytes32 public proxyBytecodeHash;
    
    /**
     * @notice Authorized deployers of AGW accounts
     */
    mapping (address deployer => bool authorized) public authorizedDeployers;
    
    /**
     * @notice Tracks the initial deployer of each account
     */
    mapping (address account => address deployer) public accountToDeployer;
    
    /**
     * @notice Account address deployed for a given salt the same account
     * @dev This is used to override the deterministic account address if the account is already deployed
     *      and the initial implementation has been changed
     */
    mapping (bytes32 salt => address accountAddress) public saltToAccount;

    /**
     * @notice Event emmited when a new AGW account is created
     * @param accountAddress Address of the newly created AGW account
     */
    event AGWAccountCreated(address indexed accountAddress);

    /**
     * @notice Event emmited when a new AGW account is deployed
     * @param accountAddress Address of the newly deployed AGW account
     */
    event AGWAccountDeployed(address indexed accountAddress);

    /**
     * @notice Event emmited when a deployer account is authorized
     * @param deployer Address of the deployer account
     * @param authorized Whether the deployer is authorized to deploy AGW accounts
     */
    event DeployerAuthorized(address indexed deployer, bool indexed authorized);

    /**
     * @notice Event emmited when the implementation contract is changed
     * @param newImplementation Address of the new implementation contract
     */
    event ImplementationChanged(address indexed newImplementation);

    /**
     * @notice Event emmited when the registry contract is changed
     * @param newRegistry Address of the new registry contract
     */
    event RegistryChanged(address indexed newRegistry);

    /**
     * @notice Constructor function of the factory contract
     * @param _implementation address     - Address of the implementation contract
     * @param _registry address           - Address of the registry contract
     * @param _proxyBytecodeHash address - Hash of the bytecode of the AGW proxy contract
     * @param _deployer address           - Address of the account authorized to deploy AGW accounts
     */
    constructor(
        address _implementation,
        bytes4 _initializerSelector,
        address _registry,
        bytes32 _proxyBytecodeHash,
        address _deployer,
        address _owner
    ) Ownable(_owner) {
        implementationAddress = _implementation;
        emit ImplementationChanged(_implementation);
        initializerSelector = _initializerSelector;
        registry = _registry;
        proxyBytecodeHash = _proxyBytecodeHash;
        authorizedDeployers[_deployer] = true;
        emit DeployerAuthorized(_deployer, true);
    }

    /**
     * @notice Deploys a new AGW account
     * @dev Account address depends only on salt
     * @param salt bytes32             - Salt to be used for the account creation
     * @param initializer bytes memory - Initializer data for the account
     * @return accountAddress address - Address of the newly created AGW account
     */
    function deployAccount(
        bytes32 salt,
        bytes calldata initializer
    ) external payable returns (address accountAddress) {
        if (saltToAccount[salt] != address(0)) {
            revert Errors.ALREADY_CREATED();
        }
        // Check that the initializer is not empty
        if (initializer.length < 4) {
            revert Errors.INVALID_INITIALIZER();
        }
        // Check that the initializer selector is correct
        {
            bytes4 selector = bytes4(initializer[0:4]);
            if (selector != initializerSelector) {
                revert Errors.INVALID_INITIALIZER();
            }
        }
        // Deploy the implementation contract
        (bool success, bytes memory returnData) = SystemContractsCaller.systemCallWithReturndata(
            uint32(gasleft()),
            address(DEPLOYER_SYSTEM_CONTRACT),
            uint128(0),
            abi.encodeCall(
                DEPLOYER_SYSTEM_CONTRACT.create2Account,
                (
                    salt,
                    proxyBytecodeHash,
                    abi.encode(implementationAddress),
                    IContractDeployer.AccountAbstractionVersion.Version1
                )
            )
        );

        if (!success) {
            revert Errors.DEPLOYMENT_FAILED();
        }

        // Decode the account address
        (accountAddress) = abi.decode(returnData, (address));
        // Store the deployer of the account
        accountToDeployer[accountAddress] = msg.sender;
        saltToAccount[salt] = accountAddress;
        
        // This propagates the revert if the initialization fails
        EfficientCall.call(gasleft(), accountAddress, msg.value, initializer, false);

        IAGWRegistry(registry).register(accountAddress);

        emit AGWAccountDeployed(accountAddress);
    }

    /**
     * @notice To emit an event when a AGW account is created but not yet deployed
     * @dev This event is so that we can index accounts that are created but not yet deployed
     * @param accountAddress address - Address of the AGW account that was created
     */
    function agwAccountCreated(address accountAddress) external {
        if (!authorizedDeployers[msg.sender]) {
            revert Errors.NOT_FROM_DEPLOYER();
        }
        emit AGWAccountCreated(accountAddress);
    }

    /**
     * @notice Sets authorization to deploy AGW accounts
     * @param deployer address - Address of the new account authorized to deploy AGW accounts
     * @param authorized bool - Whether the new deployer is authorized to deploy AGW accounts
     */
    function setDeployer(address deployer, bool authorized) external onlyOwner {
        authorizedDeployers[deployer] = authorized;

        emit DeployerAuthorized(deployer, authorized);
    }

    /**
     * @notice Changes the implementation contract address
     * @param newImplementation address - Address of the new implementation contract
     */
    function changeImplementation(address newImplementation, bytes4 newInitializerSelector) external onlyOwner {
        implementationAddress = newImplementation;
        initializerSelector = newInitializerSelector;

        emit ImplementationChanged(newImplementation);
    }

    /**
     * @notice Changes the registry contract address
     * @param newRegistry address - Address of the new registry contract
     */
    function changeRegistry(address newRegistry) external onlyOwner {
        registry = newRegistry;

        emit RegistryChanged(newRegistry);
    }

    /**
     * @notice Returns the address of the AGW account that would be created with the given salt
     * @dev If the account already exists, it returns the existing account address
     * @param salt bytes32 - Salt to be used for the account creation
     * @return accountAddress address - Address of the AGW account that would be created with the given salt
     */
    function getAddressForSalt(bytes32 salt) external view returns (address accountAddress) {
        // Check if the account is already deployed
        accountAddress = saltToAccount[salt];
        if (accountAddress == address(0)) {
            // If not, get the deterministic account address for the current implementation
            accountAddress = IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).getNewAddressCreate2(
                address(this),
                proxyBytecodeHash,
                salt,
                abi.encode(implementationAddress)
            );
        }
    }

    /**
     * @notice Returns the address of the AGW account that would be created with the given salt and implementation
     * @param salt bytes32 - Salt to be used for the account creation
     * @param _implementation address - Address of the implementation contract
     * @return accountAddress address - Address of the AGW account that would be created with the given salt and implementation
     */
    function getAddressForSaltAndImplementation(
        bytes32 salt,
        address _implementation
    ) external view returns (address accountAddress) {
        accountAddress = IContractDeployer(DEPLOYER_SYSTEM_CONTRACT).getNewAddressCreate2(
            address(this),
            proxyBytecodeHash,
            salt,
            abi.encode(_implementation)
        );
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {ERC165Checker} from '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol';
import {ExcessivelySafeCall} from '@nomad-xyz/excessively-safe-call/src/ExcessivelySafeCall.sol';

import {AGWStorage} from '../libraries/AGWStorage.sol';
import {Auth} from '../auth/Auth.sol';
import {AddressLinkedList} from '../libraries/LinkedList.sol';
import {Errors} from '../libraries/Errors.sol';
import {IModule} from '../interfaces/IModule.sol';
import {IInitable} from '../interfaces/IInitable.sol';
import {IAGWAccount} from '../interfaces/IAGWAccount.sol';
import {IModuleManager} from '../interfaces/IModuleManager.sol';

/**
 * @title Manager contract for modules
 * @notice Abstract contract for managing the enabled modules of the account
 * @dev Module addresses are stored in a linked list
 * @author https://getclave.io
 */
abstract contract ModuleManager is IModuleManager, Auth {
    // Helper library for address to address mappings
    using AddressLinkedList for mapping(address => address);
    // Interface helper library
    using ERC165Checker for address;
    // Low level calls helper library
    using ExcessivelySafeCall for address;

    /// @inheritdoc IModuleManager
    function addModule(bytes calldata moduleAndData) external override onlySelfOrModule {
        _addModule(moduleAndData);
    }

    /// @inheritdoc IModuleManager
    function removeModule(address module) external override onlySelfOrModule {
        _removeModule(module);
    }

    /// @inheritdoc IModuleManager
    function executeFromModule(
        address to,
        uint256 value,
        bytes memory data
    ) external override onlyModule {
        if (to == address(this)) revert Errors.RECUSIVE_MODULE_CALL();

        assembly {
            let result := call(gas(), to, value, add(data, 0x20), mload(data), 0, 0)
            if iszero(result) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
        }
    }

    /// @inheritdoc IModuleManager
    function isModule(address addr) external view override returns (bool) {
        return _isModule(addr);
    }

    /// @inheritdoc IModuleManager
    function listModules() external view override returns (address[] memory moduleList) {
        moduleList = _modulesLinkedList().list();
    }

    function _addModule(bytes calldata moduleAndData) internal {
        if (moduleAndData.length < 20) {
            revert Errors.EMPTY_MODULE_ADDRESS();
        }

        address moduleAddress = address(bytes20(moduleAndData[0:20]));
        bytes calldata initData = moduleAndData[20:];

        if (!_supportsModule(moduleAddress)) {
            revert Errors.MODULE_ERC165_FAIL();
        }

        _modulesLinkedList().add(moduleAddress);

        IModule(moduleAddress).init(initData);

        emit AddModule(moduleAddress);
    }

    function _removeModule(address module) internal {

        (bool success, ) = module.excessivelySafeCall(
            gasleft(),
            0,
            0,
            abi.encodeWithSelector(IInitable.disable.selector)
        );
        (success); // silence unused local variable warning

        _modulesLinkedList().remove(module);

        emit RemoveModule(module);
    }

    function _isModule(address addr) internal view override returns (bool) {
        return _modulesLinkedList().exists(addr);
    }

    function _modulesLinkedList()
        private
        view
        returns (mapping(address => address) storage modules)
    {
        modules = AGWStorage.layout().modules;
    }

    function _supportsModule(address module) internal view returns (bool) {
        return module.supportsInterface(type(IModule).interfaceId);
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol';

/**
 * Token callback handler.
 *   Handles supported tokens' callbacks, allowing account receiving these tokens.
 */
contract TokenCallbackHandler is IERC721Receiver, IERC1155Receiver {
    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector;
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        return IERC1155Receiver.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] calldata,
        uint256[] calldata,
        bytes calldata
    ) external pure override returns (bytes4) {
        return IERC1155Receiver.onERC1155BatchReceived.selector;
    }

    /// @dev functon visibility changed to public to allow overriding
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return
            interfaceId == type(IERC721Receiver).interfaceId ||
            interfaceId == type(IERC1155Receiver).interfaceId ||
            interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {IERC1271} from '@openzeppelin/contracts/interfaces/IERC1271.sol';

import {SignatureDecoder} from '../libraries/SignatureDecoder.sol';
import {ValidationHandler} from './ValidationHandler.sol';
import {EIP712Upgradeable} from '@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol';
import {OperationType} from '../interfaces/IValidator.sol';

/**
 * @title ERC1271Handler
 * @notice Contract which provides ERC1271 signature validation
 * @dev Forked from Clave for Abstract
 * @author https://getclave.io
 * @author https://abs.xyz
 */
abstract contract ERC1271Handler is
    IERC1271,
    EIP712Upgradeable,
    ValidationHandler
{
    struct AGWMessage {
        bytes32 signedHash;
    }

    bytes32 constant _AGW_MESSAGE_TYPEHASH = keccak256('AGWMessage(bytes32 signedHash)');

    bytes4 private constant _ERC1271_MAGIC = 0x1626ba7e;

    function __ERC1271Handler_init() internal onlyInitializing {
        __EIP712_init('AbstractGlobalWallet', '1.0.0');
    }

    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param signedHash bytes32                   - Hash of the data that is signed
     * @param signatureAndValidator bytes calldata - Validator address concatenated to signature
     * @return magicValue bytes4 - Magic value if the signature is valid, 0 otherwise
     */
    function isValidSignature(
        bytes32 signedHash,
        bytes memory signatureAndValidator
    ) public view override returns (bytes4 magicValue) {
        (bytes memory signature, address validator) = SignatureDecoder.decodeSignatureNoHookData(
            signatureAndValidator
        );

        bytes32 eip712Hash = _hashTypedDataV4(_agwMessageHash(AGWMessage(signedHash)));

        bool valid = _handleValidation(validator, OperationType.Signature, eip712Hash, signature);

        magicValue = valid ? _ERC1271_MAGIC : bytes4(0);
    }

    /**
     * @notice Returns the EIP-712 hash of the AGW message
     * @param agwMessage AGWMessage calldata - The message containing signedHash
     * @return bytes32 - EIP712 hash of the message
     */
    function getEip712Hash(AGWMessage calldata agwMessage) external view returns (bytes32) {
        return _hashTypedDataV4(_agwMessageHash(agwMessage));
    }

    /**
     * @notice Returns the typehash for the AGW message struct
     * @return bytes32 - AGW message typehash
     */
    function agwMessageTypeHash() external pure returns (bytes32) {
        return _AGW_MESSAGE_TYPEHASH;
    }

    function _agwMessageHash(AGWMessage memory agwMessage) internal pure returns (bytes32) {
        return keccak256(abi.encode(_AGW_MESSAGE_TYPEHASH, agwMessage.signedHash));
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';
import {Auth} from '../auth/Auth.sol';

import {IUpgradeManager} from '../interfaces/IUpgradeManager.sol';

/**
 * @title Upgrade Manager
 * @notice Abstract contract for managing the upgrade process of the account
 * @author https://getclave.io
 */
abstract contract UpgradeManager is IUpgradeManager, Auth {
    // keccak-256 of "eip1967.proxy.implementation" subtracted by 1
    bytes32 private constant _IMPLEMENTATION_SLOT =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /// @inheritdoc IUpgradeManager
    function upgradeTo(address newImplementation) external override onlySelf {
        address oldImplementation;
        assembly {
            oldImplementation := and(
                sload(_IMPLEMENTATION_SLOT),
                0xffffffffffffffffffffffffffffffffffffffff
            )
        }
        if (oldImplementation == newImplementation) {
            revert Errors.SAME_IMPLEMENTATION();
        }
        assembly {
            sstore(_IMPLEMENTATION_SLOT, newImplementation)
        }

        emit Upgraded(oldImplementation, newImplementation);
    }

    /// @inheritdoc IUpgradeManager
    function implementationAddress() external view override returns (address) {
        address impl;
        assembly {
            impl := and(sload(_IMPLEMENTATION_SLOT), 0xffffffffffffffffffffffffffffffffffffffff)
        }

        return impl;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';

library SignatureDecoder {
    // Decode transaction.signature into signature, validator and hook data
    function decodeSignature(
        bytes calldata txSignature
    ) internal pure returns (bytes memory signature, address validator, bytes[] memory hookData) {
        (signature, validator, hookData) = abi.decode(txSignature, (bytes, address, bytes[]));
    }

    // Decode transaction.signature into hook data
    function decodeSignatureOnlyHookData(
        bytes calldata txSignature
    ) internal pure returns (bytes[] memory hookData) {
        (hookData) = abi.decode(txSignature, (bytes[]));
    }

    // Decode signature into signature and validator
    function decodeSignatureNoHookData(
        bytes memory signatureAndValidator
    ) internal pure returns (bytes memory signature, address validator) {
        (signature, validator) = abi.decode(signatureAndValidator, (bytes, address));
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {ERC165Checker} from '@openzeppelin/contracts/utils/introspection/ERC165Checker.sol';
import {Transaction} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/TransactionHelper.sol';
import {ExcessivelySafeCall} from '@nomad-xyz/excessively-safe-call/src/ExcessivelySafeCall.sol';

import {Auth} from '../auth/Auth.sol';
import {AGWStorage} from '../libraries/AGWStorage.sol';
import {AddressLinkedList} from '../libraries/LinkedList.sol';
import {Errors} from '../libraries/Errors.sol';
import {IExecutionHook, IValidationHook} from '../interfaces/IHook.sol';
import {IInitable} from '../interfaces/IInitable.sol';
import {IHookManager} from '../interfaces/IHookManager.sol';

/**
 * @title Manager contract for hooks
 * @notice Abstract contract for managing the enabled hooks of the account
 * @dev Hook addresses are stored in a linked list
 * @author https://getclave.io
 */
abstract contract HookManager is IHookManager, Auth {
    // Helper library for address to address mappings
    using AddressLinkedList for mapping(address => address);
    // Interface helper library
    using ERC165Checker for address;
    // Low level calls helper library
    using ExcessivelySafeCall for address;

    // Slot for execution hooks to store context
    bytes32 private constant CONTEXT_KEY = keccak256('HookManager.context');

    /// @inheritdoc IHookManager
    function addHook(
        bytes calldata hookAndData,
        bool isValidation
    ) external override onlySelfOrModule {
        _addHook(hookAndData, isValidation);
    }

    /// @inheritdoc IHookManager
    function removeHook(address hook, bool isValidation) external override onlySelfOrModule {
        _removeHook(hook, isValidation);
    }

    /// @inheritdoc IHookManager
    function setHookData(bytes32 key, bytes calldata data) external override onlyHook {
        if (key == CONTEXT_KEY) {
            revert Errors.INVALID_KEY();
        }

        _hookDataStore()[msg.sender][key] = data;
    }

    /// @inheritdoc IHookManager
    function getHookData(address hook, bytes32 key) external view override returns (bytes memory) {
        return _hookDataStore()[hook][key];
    }

    /// @inheritdoc IHookManager
    function isHook(address addr) external view override returns (bool) {
        return _isHook(addr);
    }

    /// @inheritdoc IHookManager
    function listHooks(
        bool isValidation
    ) external view override returns (address[] memory hookList) {
        if (isValidation) {
            hookList = _validationHooksLinkedList().list();
        } else {
            hookList = _executionHooksLinkedList().list();
        }
    }

    // Runs the validation hooks that are enabled by the account and returns true if none reverts
    function runValidationHooks(
        bytes32 signedHash,
        Transaction calldata transaction,
        bytes[] memory hookData
    ) internal returns (bool) {
        mapping(address => address) storage validationHooks = _validationHooksLinkedList();

        address cursor = validationHooks[AddressLinkedList.SENTINEL_ADDRESS];
        uint256 idx = 0;
        // Iterate through hooks
        while (cursor > AddressLinkedList.SENTINEL_ADDRESS) {
            // hookData array is out of bounds for the number of hooks
            if (idx >= hookData.length) {
                return false;
            }

            // Call it with corresponding hookData
            bool success = _call(
                cursor,
                abi.encodeWithSelector(
                    IValidationHook.validationHook.selector,
                    signedHash,
                    transaction,
                    hookData[idx++]
                )
            );

            if (!success) {
                return false;
            }

            cursor = validationHooks[cursor];
        }

        // Ensure that hookData is not tampered with
        if (hookData.length != idx) return false;

        return true;
    }

    // Runs the execution hooks that are enabled by the account before and after _executeTransaction
    modifier runExecutionHooks(Transaction calldata transaction) {
        mapping(address => address) storage executionHooks = _executionHooksLinkedList();

        address cursor = executionHooks[AddressLinkedList.SENTINEL_ADDRESS];
        // Iterate through hooks
        while (cursor > AddressLinkedList.SENTINEL_ADDRESS) {
            // Call the preExecutionHook function with transaction struct
            bytes memory context = IExecutionHook(cursor).preExecutionHook(transaction);
            // Store returned data as context
            _setContext(cursor, context);

            cursor = executionHooks[cursor];
        }

        _;

        cursor = executionHooks[AddressLinkedList.SENTINEL_ADDRESS];
        // Iterate through hooks
        while (cursor > AddressLinkedList.SENTINEL_ADDRESS) {
            bytes memory context = _getContext(cursor);
            if (context.length > 0) {
                // Call the postExecutionHook function with stored context
                IExecutionHook(cursor).postExecutionHook(context);
                // Delete context
                _deleteContext(cursor);
            }

            cursor = executionHooks[cursor];
        }
    }

    function _addHook(bytes calldata hookAndData, bool isValidation) internal {
        if (hookAndData.length < 20) {
            revert Errors.EMPTY_HOOK_ADDRESS();
        }

        address hookAddress = address(bytes20(hookAndData[0:20]));

        if (!_supportsHook(hookAddress, isValidation)) {
            revert Errors.HOOK_ERC165_FAIL();
        }

        bytes calldata initData = hookAndData[20:];

        if (isValidation) {
            _validationHooksLinkedList().add(hookAddress);
        } else {
            _executionHooksLinkedList().add(hookAddress);
        }

        IInitable(hookAddress).init(initData);

        emit AddHook(hookAddress);
    }

    function _removeHook(address hook, bool isValidation) internal {
        if (isValidation) {
            _validationHooksLinkedList().remove(hook);
        } else {
            _executionHooksLinkedList().remove(hook);
        }
        
        // if the hook removal occured during execution of hooks, the hook 
        // context will not be cleaned up during post execution so we need
        // to delete it manually
        _deleteContext(hook);

        (bool success, ) = hook.excessivelySafeCall(
            gasleft(),
            0,
            0,
            abi.encodeWithSelector(IInitable.disable.selector)
        );
        (success); // silence unused local variable warning

        emit RemoveHook(hook);
    }

    function _isHook(address addr) internal view override returns (bool) {
        return
            _validationHooksLinkedList().exists(addr) || _executionHooksLinkedList().exists(addr);
    }

    function _setContext(address hook, bytes memory context) private {
        _hookDataStore()[hook][CONTEXT_KEY] = context;
    }

    function _deleteContext(address hook) private {
        delete _hookDataStore()[hook][CONTEXT_KEY];
    }

    function _getContext(address hook) private view returns (bytes memory context) {
        context = _hookDataStore()[hook][CONTEXT_KEY];
    }

    function _call(address target, bytes memory data) private returns (bool success) {
        assembly ('memory-safe') {
            success := call(gas(), target, 0, add(data, 0x20), mload(data), 0, 0)
        }
    }

    function _validationHooksLinkedList()
        private
        view
        returns (mapping(address => address) storage validationHooks)
    {
        validationHooks = AGWStorage.layout().validationHooks;
    }

    function _executionHooksLinkedList()
        private
        view
        returns (mapping(address => address) storage executionHooks)
    {
        executionHooks = AGWStorage.layout().executionHooks;
    }

    function _hookDataStore()
        private
        view
        returns (mapping(address => mapping(bytes32 => bytes)) storage hookDataStore)
    {
        hookDataStore = AGWStorage.layout().hookDataStore;
    }

    function _supportsHook(address hook, bool isValidation) internal view returns (bool) {
        return
            isValidation
                ? hook.supportsInterface(type(IValidationHook).interfaceId)
                : hook.supportsInterface(type(IExecutionHook).interfaceId);
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

library Errors {
    /*//////////////////////////////////////////////////////////////
                               AGW
    //////////////////////////////////////////////////////////////*/

    error INSUFFICIENT_FUNDS(); // 0xe7931438
    error FEE_PAYMENT_FAILED(); // 0x3d40a3a3
    error UNAUTHORIZED_OUTSIDE_TRANSACTION(); // 0xfc82da4e
    error VALIDATION_HOOK_FAILED(); // 0x52c9d27a

    /*//////////////////////////////////////////////////////////////
                               LINKED LIST
    //////////////////////////////////////////////////////////////*/

    error INVALID_PREV(); // 0x5a4c0eb3
    // Bytes
    error INVALID_BYTES(); // 0xb6dfaaff
    error BYTES_ALREADY_EXISTS(); // 0xdf6cac6b
    error BYTES_NOT_EXISTS(); // 0x689908a6
    // Address
    error INVALID_ADDRESS(); // 0x5963709b
    error ADDRESS_ALREADY_EXISTS(); // 0xf2d4d191
    error ADDRESS_NOT_EXISTS(); // 0xad6ab975

    /*//////////////////////////////////////////////////////////////
                              OWNER MANAGER
    //////////////////////////////////////////////////////////////*/

    error EMPTY_OWNERS(); // 0xc957eb7e
    error INVALID_PUBKEY_LENGTH(); // 0x04c4d8f7

    /*//////////////////////////////////////////////////////////////
                             VALIDATOR MANAGER
    //////////////////////////////////////////////////////////////*/

    error EMPTY_VALIDATORS(); // 0xd7c64d89
    error VALIDATOR_ERC165_FAIL(); // 0x5d5273ad

    /*//////////////////////////////////////////////////////////////
                              UPGRADE MANAGER
    //////////////////////////////////////////////////////////////*/

    error SAME_IMPLEMENTATION(); // 0x5e741005

    /*//////////////////////////////////////////////////////////////
                              HOOK MANAGER
    //////////////////////////////////////////////////////////////*/

    error EMPTY_HOOK_ADDRESS(); // 0x413348ae
    error HOOK_ERC165_FAIL(); // 0x9f93f87d
    error INVALID_KEY(); // 0xce7045bd

    /*//////////////////////////////////////////////////////////////
                             MODULE MANAGER
    //////////////////////////////////////////////////////////////*/

    error EMPTY_MODULE_ADDRESS(); // 0x912fe2f2
    error RECUSIVE_MODULE_CALL(); // 0x2cf7b9c8
    error MODULE_ERC165_FAIL(); // 0xc1ad2a50

    /*//////////////////////////////////////////////////////////////
                              AUTH
    //////////////////////////////////////////////////////////////*/

    error NOT_FROM_BOOTLOADER(); // 0x93887e3b
    error NOT_FROM_MODULE(); // 0x574a805d
    error NOT_FROM_HOOK(); // 0xd675a4f1
    error NOT_FROM_SELF(); // 0xa70c28d1
    error NOT_FROM_SELF_OR_MODULE(); // 0x22a1259f

    /*//////////////////////////////////////////////////////////////
                            R1 VALIDATOR
    //////////////////////////////////////////////////////////////*/

    error INVALID_SIGNATURE(); // 0xa3402a38

    /*//////////////////////////////////////////////////////////////
                          SOCIAL RECOVERY
    //////////////////////////////////////////////////////////////*/

    error INVALID_RECOVERY_CONFIG(); // 0xf774f439
    error INVALID_RECOVERY_NONCE(); // 0x098c9f8e
    error INVALID_GUARDIAN(); // 0x11a2a82b
    error INVALID_GUARDIAN_SIGNATURE(); // 0xcc117c1c
    error ZERO_ADDRESS_GUARDIAN(); // 0x6de9b401
    error GUARDIANS_MUST_BE_SORTED(); // 0xc52b41f7
    error RECOVERY_TIMELOCK(); // 0x1506ac5a
    error RECOVERY_NOT_STARTED(); // 0xa6a4a3aa
    error RECOVERY_NOT_INITED(); // 0xd0f6fdbf
    error RECOVERY_IN_PROGRESS(); // 0x8daa42a9
    error INSUFFICIENT_GUARDIANS(); // 0x7629075d
    error ALREADY_INITED(); // 0xdb0c77c8

    /*//////////////////////////////////////////////////////////////
                            FACTORY
    //////////////////////////////////////////////////////////////*/

    error DEPLOYMENT_FAILED(); // 0x0f02d218
    error INITIALIZATION_FAILED(); // 0x5b101091
    error INVALID_INITIALIZER(); // 0x350366d7
    error INVALID_SALT(); // 0x8b3152e6
    error ALREADY_CREATED(); // 0x26ebf2e8

    /*//////////////////////////////////////////////////////////////
                            PAYMASTER
    //////////////////////////////////////////////////////////////*/

    error UNSUPPORTED_FLOW(); // 0xd721e389
    error UNAUTHORIZED_WITHDRAW(); // 0x7809a0b4
    error INVALID_TOKEN(); // 0xd0995cf2
    error SHORT_PAYMASTER_INPUT(); // 0x48d170f6
    error UNSUPPORTED_TOKEN(); // 0xce706f70
    error LESS_ALLOWANCE_FOR_PAYMASTER(); // 0x11f7d13f
    error FAILED_FEE_TRANSFER(); // 0xf316e09d
    error INVALID_MARKUP(); // 0x4af7ffe3
    error USER_LIMIT_REACHED(); // 0x07235346
    error INVALID_USER_LIMIT(); // 0x2640fa41
    error NOT_AGW_ACCOUNT(); // 0x1ae1d6fd
    error EXCEEDS_MAX_SPONSORED_ETH(); // 0x3f379f40

    /*//////////////////////////////////////////////////////////////
                             REGISTRY
    //////////////////////////////////////////////////////////////*/

    error NOT_FROM_FACTORY(); // 0x238438ed
    error NOT_FROM_DEPLOYER(); // 0x83f090e3

    /*//////////////////////////////////////////////////////////////
                            BatchCaller
    //////////////////////////////////////////////////////////////*/

    error ONLY_DELEGATECALL(); // 0x43d22ee9
    error CALL_FAILED(); // 0x84aed38d

    /*//////////////////////////////////////////////////////////////
                            INITABLE
    //////////////////////////////////////////////////////////////*/

    error MODULE_NOT_ADDED_CORRECTLY(); // 0xb66e8ec4
    error MODULE_NOT_REMOVED_CORRECTLY(); // 0x680c8744

    error MsgValueMismatch(uint256 actualValue, uint256 expectedValue);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';

enum OperationType {
    Signature,
    Transaction
}

/**
 * @title secp256r1 ec keys' signature validator interface
 * @author https://getclave.io
 */
interface IR1Validator is IERC165 {
    /**
     * @notice Allows to validate secp256r1 ec signatures
     * @param signedHash bytes32          - hash of the data that is signed by the key
     * @param signature bytes             - signature
     * @param pubKey bytes32[2]           - public key coordinates array for the x and y values
     * @return valid bool                 - validation result
     */
    function validateSignature(
        OperationType operationType,
        bytes32 signedHash,
        bytes calldata signature,
        bytes32[2] calldata pubKey
    ) external view returns (bool valid);
}

/**
 * @title secp256k1 ec keys' signature validator interface
 * @author https://getclave.io
 */
interface IK1Validator is IERC165 {
    /**
     * @notice Allows to validate secp256k1 ec signatures
     * @param signedHash bytes32          - hash of the transaction signed by the key
     * @param signature bytes             - signature
     * @return signer address             - recovered signer address
     */
    function validateSignature(
        OperationType operationType,
        bytes32 signedHash,
        bytes calldata signature
    ) external view returns (address signer);
}

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

import {SystemContractsCaller} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/SystemContractsCaller.sol';
import {EfficientCall} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/EfficientCall.sol';
import { DEPLOYER_SYSTEM_CONTRACT } from "@matterlabs/zksync-contracts/l2/system-contracts/Constants.sol";
import {Errors} from '../libraries/Errors.sol';
import {SelfAuth} from '../auth/SelfAuth.sol';
// Each call data for batches
struct Call {
    address target; // Target contract address
    bool allowFailure; // Whether to revert if the call fails
    uint256 value; // Amount of ETH to send with call
    bytes callData; // Calldata to send
}

/// @title BatchCaller
/// @notice Make multiple calls in a single transaction
abstract contract BatchCaller is SelfAuth {
  /// @notice Make multiple calls, ensure success if required.
  /// @dev The total Ether sent across all calls must be equal to `msg.value` to maintain the invariant
  /// that `msg.value` + `tx.fee` is the maximum amount of Ether that can be spent on the transaction.
  /// @param _calls Array of Call structs, each representing an individual external call to be made.
  function batchCall(Call[] calldata _calls) external payable onlySelf {
    uint256 totalValue;
    uint256 len = _calls.length;
    for (uint256 i = 0; i < len; ++i) {
      totalValue += _calls[i].value;
      bool success;
      if (_calls[i].target == address(DEPLOYER_SYSTEM_CONTRACT)) {
        // Note, that the deployer contract can only be called with a "systemCall" flag.
        success = SystemContractsCaller.systemCall(
          uint32(gasleft()),
          _calls[i].target,
          _calls[i].value,
          _calls[i].callData
        );
      } else {
        success = EfficientCall.rawCall(gasleft(), _calls[i].target, _calls[i].value, _calls[i].callData, false);
      }

      if (!_calls[i].allowFailure && !success) {
        revert Errors.CALL_FAILED();
      }
    }

    if (totalValue != msg.value) {
      revert Errors.MsgValueMismatch(msg.value, totalValue);
    }
  }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {IAccount} from '@matterlabs/zksync-contracts/l2/system-contracts/interfaces/IAccount.sol';

import {IERC1271} from '@openzeppelin/contracts/interfaces/IERC1271.sol';
import {IERC777Recipient} from '@openzeppelin/contracts/interfaces/IERC777Recipient.sol';
import {IERC721Receiver} from '@openzeppelin/contracts/interfaces/IERC721Receiver.sol';
import {IERC1155Receiver} from '@openzeppelin/contracts/interfaces/IERC1155Receiver.sol';

import {IHookManager} from './IHookManager.sol';
import {IModuleManager} from './IModuleManager.sol';
import {IOwnerManager} from './IOwnerManager.sol';
import {IUpgradeManager} from './IUpgradeManager.sol';
import {IValidatorManager} from './IValidatorManager.sol';

/**
 * @title IAGWAccount
 * @notice Interface for the AGW contract
 * @dev Implementations of this interface are contracts that can be used as an AGW account
 * @dev Forked from Clave for Abstract
 * @author https://getclave.io
 * @author https://abs.xyz
 */
interface IAGWAccount is
    IERC1271,
    IERC721Receiver,
    IERC1155Receiver,
    IHookManager,
    IModuleManager,
    IOwnerManager,
    IValidatorManager,
    IUpgradeManager,
    IAccount
{
    event FeePaid();
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./interfaces/IAccountCodeStorage.sol";
import "./interfaces/INonceHolder.sol";
import "./interfaces/IContractDeployer.sol";
import "./interfaces/IKnownCodesStorage.sol";
import "./interfaces/IImmutableSimulator.sol";
import "./interfaces/IEthToken.sol";
import "./interfaces/IL1Messenger.sol";
import "./interfaces/ISystemContext.sol";
import "./interfaces/IBytecodeCompressor.sol";
import "./BootloaderUtilities.sol";

/// @dev All the system contracts introduced by zkSync have their addresses
/// started from 2^15 in order to avoid collision with Ethereum precompiles.
uint160 constant SYSTEM_CONTRACTS_OFFSET = 0x8000; // 2^15

/// @dev All the system contracts must be located in the kernel space,
/// i.e. their addresses must be below 2^16.
uint160 constant MAX_SYSTEM_CONTRACT_ADDRESS = 0xffff; // 2^16 - 1

address constant ECRECOVER_SYSTEM_CONTRACT = address(0x01);
address constant SHA256_SYSTEM_CONTRACT = address(0x02);

/// @dev The current maximum deployed precompile address.
/// Note: currently only two precompiles are deployed:
/// 0x01 - ecrecover
/// 0x02 - sha256
/// Important! So the constant should be updated if more precompiles are deployed.
uint256 constant CURRENT_MAX_PRECOMPILE_ADDRESS = uint256(uint160(SHA256_SYSTEM_CONTRACT));

address payable constant BOOTLOADER_FORMAL_ADDRESS = payable(address(SYSTEM_CONTRACTS_OFFSET + 0x01));
IAccountCodeStorage constant ACCOUNT_CODE_STORAGE_SYSTEM_CONTRACT = IAccountCodeStorage(
    address(SYSTEM_CONTRACTS_OFFSET + 0x02)
);
INonceHolder constant NONCE_HOLDER_SYSTEM_CONTRACT = INonceHolder(address(SYSTEM_CONTRACTS_OFFSET + 0x03));
IKnownCodesStorage constant KNOWN_CODE_STORAGE_CONTRACT = IKnownCodesStorage(address(SYSTEM_CONTRACTS_OFFSET + 0x04));
IImmutableSimulator constant IMMUTABLE_SIMULATOR_SYSTEM_CONTRACT = IImmutableSimulator(
    address(SYSTEM_CONTRACTS_OFFSET + 0x05)
);
IContractDeployer constant DEPLOYER_SYSTEM_CONTRACT = IContractDeployer(address(SYSTEM_CONTRACTS_OFFSET + 0x06));

// A contract that is allowed to deploy any codehash
// on any address. To be used only during an upgrade.
address constant FORCE_DEPLOYER = address(SYSTEM_CONTRACTS_OFFSET + 0x07);
IL1Messenger constant L1_MESSENGER_CONTRACT = IL1Messenger(address(SYSTEM_CONTRACTS_OFFSET + 0x08));
address constant MSG_VALUE_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x09);

IEthToken constant ETH_TOKEN_SYSTEM_CONTRACT = IEthToken(address(SYSTEM_CONTRACTS_OFFSET + 0x0a));

address constant KECCAK256_SYSTEM_CONTRACT = address(SYSTEM_CONTRACTS_OFFSET + 0x10);

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

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

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

IBytecodeCompressor constant BYTECODE_COMPRESSOR_CONTRACT = IBytecodeCompressor(
    address(SYSTEM_CONTRACTS_OFFSET + 0x0e)
);

/// @dev If the bitwise AND of the extraAbi[2] param when calling the MSG_VALUE_SIMULATOR
/// is non-zero, the call will be assumed to be a system one.
uint256 constant MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT = 1;

/// @dev The maximal msg.value that context can have
uint256 constant MAX_MSG_VALUE = 2 ** 128 - 1;

/// @dev Prefix used during derivation of account addresses using CREATE2
/// @dev keccak256("zksyncCreate2")
bytes32 constant CREATE2_PREFIX = 0x2020dba91b30cc0006188af794c2fb30dd8520db7e2c088b7fc7c103c00ca494;
/// @dev Prefix used during derivation of account addresses using CREATE
/// @dev keccak256("zksyncCreate")
bytes32 constant CREATE_PREFIX = 0x63bae3a9951d38e8a3fbb7b70909afc1200610fc5bc55ade242f815974674f23;

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../libraries/TransactionHelper.sol";

bytes4 constant ACCOUNT_VALIDATION_SUCCESS_MAGIC = IAccount.validateTransaction.selector;

interface IAccount {
    /// @notice Called by the bootloader to validate that an account agrees to process the transaction
    /// (and potentially pay for it).
    /// @param _txHash The hash of the transaction to be used in the explorer
    /// @param _suggestedSignedHash The hash of the transaction is signed by EOAs
    /// @param _transaction The transaction itself
    /// @return magic The magic value that should be equal to the signature of this function
    /// if the user agrees to proceed with the transaction.
    /// @dev The developer should strive to preserve as many steps as possible both for valid
    /// and invalid transactions as this very method is also used during the gas fee estimation
    /// (without some of the necessary data, e.g. signature).
    function validateTransaction(
        bytes32 _txHash,
        bytes32 _suggestedSignedHash,
        Transaction calldata _transaction
    ) external payable returns (bytes4 magic);

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

    // There is no point in providing possible signed hash in the `executeTransactionFromOutside` method,
    // since it typically should not be trusted.
    function executeTransactionFromOutside(Transaction calldata _transaction) external payable;

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

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

// SPDX-License-Identifier: MIT OR Apache-2.0

pragma solidity ^0.8.0;

import "./SystemContractHelper.sol";
import "./Utils.sol";
import {SHA256_SYSTEM_CONTRACT, KECCAK256_SYSTEM_CONTRACT} from "../Constants.sol";

/**
 * @author Matter Labs
 * @notice This library is used to perform ultra-efficient calls using zkEVM-specific features.
 * @dev EVM calls always accept a memory slice as input and return a memory slice as output.
 * Therefore, even if the user has a ready-made calldata slice, they still need to copy it to memory
 * before calling. This is especially inefficient for large inputs (proxies, multi-calls, etc.).
 * In turn, zkEVM operates over a fat pointer, which is a set of (memory page, offset, start, length) in the memory/calldata/returndata.
 * This allows forwarding the calldata slice as is, without copying it to memory.
 * @dev Fat pointer is not just an integer, it is an extended data type supported on the VM level.
 * zkEVM creates the wellformed fat pointers for all the calldata/returndata regions, later
 * the contract may manipulate the already created fat pointers to forward a slice of the data, but not
 * to create new fat pointers!
 * @dev The allowed operation on fat pointers are:
 * 1. `ptr.add` - Transforms `ptr.offset` into `ptr.offset + u32(_value)`. If overflow happens then it panics.
 * 2. `ptr.sub` - Transforms `ptr.offset` into `ptr.offset - u32(_value)`. If underflow happens then it panics.
 * 3. `ptr.pack` - Do the concatenation between the lowest 128 bits of the pointer itself and the highest 128 bits of `_value`. It is typically used to prepare the ABI for external calls.
 * 4. `ptr.shrink` - Transforms `ptr.length` into `ptr.length - u32(_shrink)`. If underflow happens then it panics.
 * @dev The call opcodes accept the fat pointer and change it to its canonical form before passing it to the child call
 * 1. `ptr.start` is transformed into `ptr.offset + ptr.start`
 * 2. `ptr.length` is transformed into `ptr.length - ptr.offset`
 * 3. `ptr.offset` is transformed into `0`
 */
library EfficientCall {
    /// @notice Call the `keccak256` without copying calldata to memory.
    /// @param _data The preimage data.
    /// @return The `keccak256` hash.
    function keccak(bytes calldata _data) internal view returns (bytes32) {
        bytes memory returnData = staticCall(gasleft(), KECCAK256_SYSTEM_CONTRACT, _data);
        require(returnData.length == 32, "keccak256 returned invalid data");
        return bytes32(returnData);
    }

    /// @notice Call the `sha256` precompile without copying calldata to memory.
    /// @param _data The preimage data.
    /// @return The `sha256` hash.
    function sha(bytes calldata _data) internal view returns (bytes32) {
        bytes memory returnData = staticCall(gasleft(), SHA256_SYSTEM_CONTRACT, _data);
        require(returnData.length == 32, "sha returned invalid data");
        return bytes32(returnData);
    }

    /// @notice Perform a `call` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _value The `msg.value` to send.
    /// @param _data The calldata to use for the call.
    /// @param _isSystem Whether the call should contain the `isSystem` flag.
    /// @return returnData The copied to memory return data.
    function call(
        uint256 _gas,
        address _address,
        uint256 _value,
        bytes calldata _data,
        bool _isSystem
    ) internal returns (bytes memory returnData) {
        bool success = rawCall(_gas, _address, _value, _data, _isSystem);
        returnData = _verifyCallResult(success);
    }

    /// @notice Perform a `staticCall` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @return returnData The copied to memory return data.
    function staticCall(
        uint256 _gas,
        address _address,
        bytes calldata _data
    ) internal view returns (bytes memory returnData) {
        bool success = rawStaticCall(_gas, _address, _data);
        returnData = _verifyCallResult(success);
    }

    /// @notice Perform a `delegateCall` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @return returnData The copied to memory return data.
    function delegateCall(
        uint256 _gas,
        address _address,
        bytes calldata _data
    ) internal returns (bytes memory returnData) {
        bool success = rawDelegateCall(_gas, _address, _data);
        returnData = _verifyCallResult(success);
    }

    /// @notice Perform a `mimicCall` (a call with custom msg.sender) without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @param _whoToMimic The `msg.sender` for the next call.
    /// @param _isConstructor Whether the call should contain the `isConstructor` flag.
    /// @param _isSystem Whether the call should contain the `isSystem` flag.
    /// @return returnData The copied to memory return data.
    function mimicCall(
        uint256 _gas,
        address _address,
        bytes calldata _data,
        address _whoToMimic,
        bool _isConstructor,
        bool _isSystem
    ) internal returns (bytes memory returnData) {
        bool success = rawMimicCall(_gas, _address, _data, _whoToMimic, _isConstructor, _isSystem);
        returnData = _verifyCallResult(success);
    }

    /// @notice Perform a `call` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _value The `msg.value` to send.
    /// @param _data The calldata to use for the call.
    /// @param _isSystem Whether the call should contain the `isSystem` flag.
    /// @return success whether the call was successful.
    function rawCall(
        uint256 _gas,
        address _address,
        uint256 _value,
        bytes calldata _data,
        bool _isSystem
    ) internal returns (bool success) {
        if (_value == 0) {
            _loadFarCallABIIntoActivePtr(_gas, _data, false, _isSystem);

            address callAddr = RAW_FAR_CALL_BY_REF_CALL_ADDRESS;
            assembly {
                success := call(_address, callAddr, 0, 0, 0xFFFF, 0, 0)
            }
        } else {
            _loadFarCallABIIntoActivePtr(_gas, _data, false, true);

            // If there is provided `msg.value` call the `MsgValueSimulator` to forward ether.
            address msgValueSimulator = MSG_VALUE_SYSTEM_CONTRACT;
            address callAddr = SYSTEM_CALL_BY_REF_CALL_ADDRESS;
            // We need to supply the mask to the MsgValueSimulator to denote
            // that the call should be a system one.
            uint256 forwardMask = _isSystem ? MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT : 0;

            assembly {
                success := call(msgValueSimulator, callAddr, _value, _address, 0xFFFF, forwardMask, 0)
            }
        }
    }

    /// @notice Perform a `staticCall` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @return success whether the call was successful.
    function rawStaticCall(uint256 _gas, address _address, bytes calldata _data) internal view returns (bool success) {
        _loadFarCallABIIntoActivePtr(_gas, _data, false, false);

        address callAddr = RAW_FAR_CALL_BY_REF_CALL_ADDRESS;
        assembly {
            success := staticcall(_address, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Perform a `delegatecall` without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @return success whether the call was successful.
    function rawDelegateCall(uint256 _gas, address _address, bytes calldata _data) internal returns (bool success) {
        _loadFarCallABIIntoActivePtr(_gas, _data, false, false);

        address callAddr = RAW_FAR_CALL_BY_REF_CALL_ADDRESS;
        assembly {
            success := delegatecall(_address, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Perform a `mimicCall` (call with custom msg.sender) without copying calldata to memory.
    /// @param _gas The gas to use for the call.
    /// @param _address The address to call.
    /// @param _data The calldata to use for the call.
    /// @param _whoToMimic The `msg.sender` for the next call.
    /// @param _isConstructor Whether the call should contain the `isConstructor` flag.
    /// @param _isSystem Whether the call should contain the `isSystem` flag.
    /// @return success whether the call was successful.
    /// @dev If called not in kernel mode, it will result in a revert (enforced by the VM)
    function rawMimicCall(
        uint256 _gas,
        address _address,
        bytes calldata _data,
        address _whoToMimic,
        bool _isConstructor,
        bool _isSystem
    ) internal returns (bool success) {
        _loadFarCallABIIntoActivePtr(_gas, _data, _isConstructor, _isSystem);

        address callAddr = MIMIC_CALL_BY_REF_CALL_ADDRESS;
        uint256 cleanupMask = ADDRESS_MASK;
        assembly {
            // Clearing values before usage in assembly, since Solidity
            // doesn't do it by default
            _whoToMimic := and(_whoToMimic, cleanupMask)

            success := call(_address, callAddr, 0, 0, _whoToMimic, 0, 0)
        }
    }

    /// @dev Verify that a low-level call was successful, and revert if it wasn't, by bubbling the revert reason.
    /// @param _success Whether the call was successful.
    /// @return returnData The copied to memory return data.
    function _verifyCallResult(bool _success) private pure returns (bytes memory returnData) {
        if (_success) {
            uint256 size;
            assembly {
                size := returndatasize()
            }

            returnData = new bytes(size);
            assembly {
                returndatacopy(add(returnData, 0x20), 0, size)
            }
        } else {
            propagateRevert();
        }
    }

    /// @dev Propagate the revert reason from the current call to the caller.
    function propagateRevert() internal pure {
        assembly {
            let size := returndatasize()
            returndatacopy(0, 0, size)
            revert(0, size)
        }
    }

    /// @dev Load the far call ABI into active ptr, that will be used for the next call by reference.
    /// @param _gas The gas to be passed to the call.
    /// @param _data The calldata to be passed to the call.
    /// @param _isConstructor Whether the call is a constructor call.
    /// @param _isSystem Whether the call is a system call.
    function _loadFarCallABIIntoActivePtr(
        uint256 _gas,
        bytes calldata _data,
        bool _isConstructor,
        bool _isSystem
    ) private view {
        SystemContractHelper.loadCalldataIntoActivePtr();

        // Currently, zkEVM considers the pointer valid if(ptr.offset < ptr.length || (ptr.length == 0 && ptr.offset == 0)), otherwise panics.
        // So, if the data is empty we need to make the `ptr.length = ptr.offset = 0`, otherwise follow standard logic.
        if (_data.length == 0) {
            // Safe to cast, offset is never bigger than `type(uint32).max`
            SystemContractHelper.ptrShrinkIntoActive(uint32(msg.data.length));
        } else {
            uint256 dataOffset;
            assembly {
                dataOffset := _data.offset
            }

            // Safe to cast, offset is never bigger than `type(uint32).max`
            SystemContractHelper.ptrAddIntoActive(uint32(dataOffset));
            // Safe to cast, `data.length` is never bigger than `type(uint32).max`
            uint32 shrinkTo = uint32(msg.data.length - (_data.length + dataOffset));
            SystemContractHelper.ptrShrinkIntoActive(shrinkTo);
        }

        uint32 gas = Utils.safeCastToU32(_gas);
        uint256 farCallAbi = SystemContractsCaller.getFarCallABIWithEmptyFatPointer(
            gas,
            // Only rollup is supported for now
            0,
            CalldataForwardingMode.ForwardFatPointer,
            _isConstructor,
            _isSystem
        );
        SystemContractHelper.ptrPackIntoActivePtr(farCallAbi);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8;

import {MSG_VALUE_SYSTEM_CONTRACT, MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT} from "../Constants.sol";
import "./Utils.sol";

// Addresses used for the compiler to be replaced with the
// zkSync-specific opcodes during the compilation.
// IMPORTANT: these are just compile-time constants and are used
// only if used in-place by Yul optimizer.
address constant TO_L1_CALL_ADDRESS = address((1 << 16) - 1);
address constant CODE_ADDRESS_CALL_ADDRESS = address((1 << 16) - 2);
address constant PRECOMPILE_CALL_ADDRESS = address((1 << 16) - 3);
address constant META_CALL_ADDRESS = address((1 << 16) - 4);
address constant MIMIC_CALL_CALL_ADDRESS = address((1 << 16) - 5);
address constant SYSTEM_MIMIC_CALL_CALL_ADDRESS = address((1 << 16) - 6);
address constant MIMIC_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 7);
address constant SYSTEM_MIMIC_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 8);
address constant RAW_FAR_CALL_CALL_ADDRESS = address((1 << 16) - 9);
address constant RAW_FAR_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 10);
address constant SYSTEM_CALL_CALL_ADDRESS = address((1 << 16) - 11);
address constant SYSTEM_CALL_BY_REF_CALL_ADDRESS = address((1 << 16) - 12);
address constant SET_CONTEXT_VALUE_CALL_ADDRESS = address((1 << 16) - 13);
address constant SET_PUBDATA_PRICE_CALL_ADDRESS = address((1 << 16) - 14);
address constant INCREMENT_TX_COUNTER_CALL_ADDRESS = address((1 << 16) - 15);
address constant PTR_CALLDATA_CALL_ADDRESS = address((1 << 16) - 16);
address constant CALLFLAGS_CALL_ADDRESS = address((1 << 16) - 17);
address constant PTR_RETURNDATA_CALL_ADDRESS = address((1 << 16) - 18);
address constant EVENT_INITIALIZE_ADDRESS = address((1 << 16) - 19);
address constant EVENT_WRITE_ADDRESS = address((1 << 16) - 20);
address constant LOAD_CALLDATA_INTO_ACTIVE_PTR_CALL_ADDRESS = address((1 << 16) - 21);
address constant LOAD_LATEST_RETURNDATA_INTO_ACTIVE_PTR_CALL_ADDRESS = address((1 << 16) - 22);
address constant PTR_ADD_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 23);
address constant PTR_SHRINK_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 24);
address constant PTR_PACK_INTO_ACTIVE_CALL_ADDRESS = address((1 << 16) - 25);
address constant MULTIPLICATION_HIGH_ADDRESS = address((1 << 16) - 26);
address constant GET_EXTRA_ABI_DATA_ADDRESS = address((1 << 16) - 27);

// All the offsets are in bits
uint256 constant META_GAS_PER_PUBDATA_BYTE_OFFSET = 0 * 8;
uint256 constant META_HEAP_SIZE_OFFSET = 8 * 8;
uint256 constant META_AUX_HEAP_SIZE_OFFSET = 12 * 8;
uint256 constant META_SHARD_ID_OFFSET = 28 * 8;
uint256 constant META_CALLER_SHARD_ID_OFFSET = 29 * 8;
uint256 constant META_CODE_SHARD_ID_OFFSET = 30 * 8;

/// @notice The way to forward the calldata:
/// - Use the current heap (i.e. the same as on EVM).
/// - Use the auxiliary heap.
/// - Forward via a pointer
/// @dev Note, that currently, users do not have access to the auxiliary
/// heap and so the only type of forwarding that will be used by the users
/// are UseHeap and ForwardFatPointer for forwarding a slice of the current calldata
/// to the next call.
enum CalldataForwardingMode {
    UseHeap,
    ForwardFatPointer,
    UseAuxHeap
}

/**
 * @author Matter Labs
 * @notice A library that allows calling contracts with the `isSystem` flag.
 * @dev It is needed to call ContractDeployer and NonceHolder.
 */
library SystemContractsCaller {
    /// @notice Makes a call with the `isSystem` flag.
    /// @param gasLimit The gas limit for the call.
    /// @param to The address to call.
    /// @param value The value to pass with the transaction.
    /// @param data The calldata.
    /// @return success Whether the transaction has been successful.
    /// @dev Note, that the `isSystem` flag can only be set when calling system contracts.
    function systemCall(uint32 gasLimit, address to, uint256 value, bytes memory data) internal returns (bool success) {
        address callAddr = SYSTEM_CALL_CALL_ADDRESS;

        uint32 dataStart;
        assembly {
            dataStart := add(data, 0x20)
        }
        uint32 dataLength = uint32(Utils.safeCastToU32(data.length));

        uint256 farCallAbi = SystemContractsCaller.getFarCallABI(
            0,
            0,
            dataStart,
            dataLength,
            gasLimit,
            // Only rollup is supported for now
            0,
            CalldataForwardingMode.UseHeap,
            false,
            true
        );

        if (value == 0) {
            // Doing the system call directly
            assembly {
                success := call(to, callAddr, 0, 0, farCallAbi, 0, 0)
            }
        } else {
            address msgValueSimulator = MSG_VALUE_SYSTEM_CONTRACT;
            // We need to supply the mask to the MsgValueSimulator to denote
            // that the call should be a system one.
            uint256 forwardMask = MSG_VALUE_SIMULATOR_IS_SYSTEM_BIT;

            assembly {
                success := call(msgValueSimulator, callAddr, value, to, farCallAbi, forwardMask, 0)
            }
        }
    }

    /// @notice Makes a call with the `isSystem` flag.
    /// @param gasLimit The gas limit for the call.
    /// @param to The address to call.
    /// @param value The value to pass with the transaction.
    /// @param data The calldata.
    /// @return success Whether the transaction has been successful.
    /// @return returnData The returndata of the transaction (revert reason in case the transaction has failed).
    /// @dev Note, that the `isSystem` flag can only be set when calling system contracts.
    function systemCallWithReturndata(
        uint32 gasLimit,
        address to,
        uint128 value,
        bytes memory data
    ) internal returns (bool success, bytes memory returnData) {
        success = systemCall(gasLimit, to, value, data);

        uint256 size;
        assembly {
            size := returndatasize()
        }

        returnData = new bytes(size);
        assembly {
            returndatacopy(add(returnData, 0x20), 0, size)
        }
    }

    /// @notice Makes a call with the `isSystem` flag.
    /// @param gasLimit The gas limit for the call.
    /// @param to The address to call.
    /// @param value The value to pass with the transaction.
    /// @param data The calldata.
    /// @return returnData The returndata of the transaction. In case the transaction reverts, the error
    /// bubbles up to the parent frame.
    /// @dev Note, that the `isSystem` flag can only be set when calling system contracts.
    function systemCallWithPropagatedRevert(
        uint32 gasLimit,
        address to,
        uint128 value,
        bytes memory data
    ) internal returns (bytes memory returnData) {
        bool success;
        (success, returnData) = systemCallWithReturndata(gasLimit, to, value, data);

        if (!success) {
            assembly {
                let size := mload(returnData)
                revert(add(returnData, 0x20), size)
            }
        }
    }

    /// @notice Calculates the packed representation of the FarCallABI.
    /// @param dataOffset Calldata offset in memory. Provide 0 unless using custom pointer.
    /// @param memoryPage Memory page to use. Provide 0 unless using custom pointer.
    /// @param dataStart The start of the calldata slice. Provide the offset in memory
    /// if not using custom pointer.
    /// @param dataLength The calldata length. Provide the length of the calldata in bytes
    /// unless using custom pointer.
    /// @param gasPassed The gas to pass with the call.
    /// @param shardId Of the account to call. Currently only 0 is supported.
    /// @param forwardingMode The forwarding mode to use:
    /// - provide CalldataForwardingMode.UseHeap when using your current memory
    /// - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer.
    /// @param isConstructorCall Whether the call will be a call to the constructor
    /// (ignored when the caller is not a system contract).
    /// @param isSystemCall Whether the call will have the `isSystem` flag.
    /// @return farCallAbi The far call ABI.
    /// @dev The `FarCallABI` has the following structure:
    /// pub struct FarCallABI {
    ///     pub memory_quasi_fat_pointer: FatPointer,
    ///     pub gas_passed: u32,
    ///     pub shard_id: u8,
    ///     pub forwarding_mode: FarCallForwardPageType,
    ///     pub constructor_call: bool,
    ///     pub to_system: bool,
    /// }
    ///
    /// The FatPointer struct:
    ///
    /// pub struct FatPointer {
    ///     pub offset: u32, // offset relative to `start`
    ///     pub memory_page: u32, // memory page where slice is located
    ///     pub start: u32, // absolute start of the slice
    ///     pub length: u32, // length of the slice
    /// }
    ///
    /// @dev Note, that the actual layout is the following:
    ///
    /// [0..32) bits -- the calldata offset
    /// [32..64) bits -- the memory page to use. Can be left blank in most of the cases.
    /// [64..96) bits -- the absolute start of the slice
    /// [96..128) bits -- the length of the slice.
    /// [128..192) bits -- empty bits.
    /// [192..224) bits -- gasPassed.
    /// [224..232) bits -- forwarding_mode
    /// [232..240) bits -- shard id.
    /// [240..248) bits -- constructor call flag
    /// [248..256] bits -- system call flag
    function getFarCallABI(
        uint32 dataOffset,
        uint32 memoryPage,
        uint32 dataStart,
        uint32 dataLength,
        uint32 gasPassed,
        uint8 shardId,
        CalldataForwardingMode forwardingMode,
        bool isConstructorCall,
        bool isSystemCall
    ) internal pure returns (uint256 farCallAbi) {
        // Fill in the call parameter fields
        farCallAbi = getFarCallABIWithEmptyFatPointer(
            gasPassed,
            shardId,
            forwardingMode,
            isConstructorCall,
            isSystemCall
        );
        // Fill in the fat pointer fields
        farCallAbi |= dataOffset;
        farCallAbi |= (uint256(memoryPage) << 32);
        farCallAbi |= (uint256(dataStart) << 64);
        farCallAbi |= (uint256(dataLength) << 96);
    }

    /// @notice Calculates the packed representation of the FarCallABI with zero fat pointer fields.
    /// @param gasPassed The gas to pass with the call.
    /// @param shardId Of the account to call. Currently only 0 is supported.
    /// @param forwardingMode The forwarding mode to use:
    /// - provide CalldataForwardingMode.UseHeap when using your current memory
    /// - provide CalldataForwardingMode.ForwardFatPointer when using custom pointer.
    /// @param isConstructorCall Whether the call will be a call to the constructor
    /// (ignored when the caller is not a system contract).
    /// @param isSystemCall Whether the call will have the `isSystem` flag.
    /// @return farCallAbiWithEmptyFatPtr The far call ABI with zero fat pointer fields.
    function getFarCallABIWithEmptyFatPointer(
        uint32 gasPassed,
        uint8 shardId,
        CalldataForwardingMode forwardingMode,
        bool isConstructorCall,
        bool isSystemCall
    ) internal pure returns (uint256 farCallAbiWithEmptyFatPtr) {
        farCallAbiWithEmptyFatPtr |= (uint256(gasPassed) << 192);
        farCallAbiWithEmptyFatPtr |= (uint256(forwardingMode) << 224);
        farCallAbiWithEmptyFatPtr |= (uint256(shardId) << 232);
        if (isConstructorCall) {
            farCallAbiWithEmptyFatPtr |= (1 << 240);
        }
        if (isSystemCall) {
            farCallAbiWithEmptyFatPtr |= (1 << 248);
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

import "./EfficientCall.sol";

/**
 * @author Matter Labs
 * @dev Common utilities used in zkSync system contracts
 */
library Utils {
    /// @dev Bit mask of bytecode hash "isConstructor" marker
    bytes32 constant IS_CONSTRUCTOR_BYTECODE_HASH_BIT_MASK =
        0x00ff000000000000000000000000000000000000000000000000000000000000;

    /// @dev Bit mask to set the "isConstructor" marker in the bytecode hash
    bytes32 constant SET_IS_CONSTRUCTOR_MARKER_BIT_MASK =
        0x0001000000000000000000000000000000000000000000000000000000000000;

    function safeCastToU128(uint256 _x) internal pure returns (uint128) {
        require(_x <= type(uint128).max, "Overflow");

        return uint128(_x);
    }

    function safeCastToU32(uint256 _x) internal pure returns (uint32) {
        require(_x <= type(uint32).max, "Overflow");

        return uint32(_x);
    }

    function safeCastToU24(uint256 _x) internal pure returns (uint24) {
        require(_x <= type(uint24).max, "Overflow");

        return uint24(_x);
    }

    /// @return codeLength The bytecode length in bytes
    function bytecodeLenInBytes(bytes32 _bytecodeHash) internal pure returns (uint256 codeLength) {
        codeLength = bytecodeLenInWords(_bytecodeHash) << 5; // _bytecodeHash * 32
    }

    /// @return codeLengthInWords The bytecode length in machine words
    function bytecodeLenInWords(bytes32 _bytecodeHash) internal pure returns (uint256 codeLengthInWords) {
        unchecked {
            codeLengthInWords = uint256(uint8(_bytecodeHash[2])) * 256 + uint256(uint8(_bytecodeHash[3]));
        }
    }

    /// @notice Denotes whether bytecode hash corresponds to a contract that already constructed
    function isContractConstructed(bytes32 _bytecodeHash) internal pure returns (bool) {
        return _bytecodeHash[1] == 0x00;
    }

    /// @notice Denotes whether bytecode hash corresponds to a contract that is on constructor or has already been constructed
    function isContractConstructing(bytes32 _bytecodeHash) internal pure returns (bool) {
        return _bytecodeHash[1] == 0x01;
    }

    /// @notice Sets "isConstructor" flag to TRUE for the bytecode hash
    /// @param _bytecodeHash The bytecode hash for which it is needed to set the constructing flag
    /// @return The bytecode hash with "isConstructor" flag set to TRUE
    function constructingBytecodeHash(bytes32 _bytecodeHash) internal pure returns (bytes32) {
        // Clear the "isConstructor" marker and set it to 0x01.
        return constructedBytecodeHash(_bytecodeHash) | SET_IS_CONSTRUCTOR_MARKER_BIT_MASK;
    }

    /// @notice Sets "isConstructor" flag to FALSE for the bytecode hash
    /// @param _bytecodeHash The bytecode hash for which it is needed to set the constructing flag
    /// @return The bytecode hash with "isConstructor" flag set to FALSE
    function constructedBytecodeHash(bytes32 _bytecodeHash) internal pure returns (bytes32) {
        return _bytecodeHash & ~IS_CONSTRUCTOR_BYTECODE_HASH_BIT_MASK;
    }

    /// @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 hashL2Bytecode(bytes calldata _bytecode) internal view returns (bytes32 hashedBytecode) {
        // Note that the length of the bytecode must be provided in 32-byte words.
        require(_bytecode.length % 32 == 0, "po");

        uint256 bytecodeLenInWords = _bytecode.length / 32;
        require(bytecodeLenInWords < 2 ** 16, "pp"); // bytecode length must be less than 2^16 words
        require(bytecodeLenInWords % 2 == 1, "pr"); // bytecode length in words must be odd
        hashedBytecode =
            EfficientCall.sha(_bytecode) &
            0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
        // Setting the version of the hash
        hashedBytecode = (hashedBytecode | bytes32(uint256(1 << 248)));
        // Setting the length
        hashedBytecode = hashedBytecode | bytes32(bytecodeLenInWords << 224);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../openzeppelin/token/ERC20/IERC20.sol";
import "../openzeppelin/token/ERC20/utils/SafeERC20.sol";

import "../interfaces/IPaymasterFlow.sol";
import "../interfaces/IContractDeployer.sol";
import {ETH_TOKEN_SYSTEM_CONTRACT, BOOTLOADER_FORMAL_ADDRESS} from "../Constants.sol";
import "./RLPEncoder.sol";
import "./EfficientCall.sol";

/// @dev The type id of zkSync's EIP-712-signed transaction.
uint8 constant EIP_712_TX_TYPE = 0x71;

/// @dev The type id of legacy transactions.
uint8 constant LEGACY_TX_TYPE = 0x0;
/// @dev The type id of legacy transactions.
uint8 constant EIP_2930_TX_TYPE = 0x01;
/// @dev The type id of EIP1559 transactions.
uint8 constant EIP_1559_TX_TYPE = 0x02;

/// @notice Structure used to represent zkSync transaction.
struct Transaction {
    // The type of the transaction.
    uint256 txType;
    // The caller.
    uint256 from;
    // The callee.
    uint256 to;
    // The gasLimit to pass with the transaction.
    // It has the same meaning as Ethereum's gasLimit.
    uint256 gasLimit;
    // The maximum amount of gas the user is willing to pay for a byte of pubdata.
    uint256 gasPerPubdataByteLimit;
    // The maximum fee per gas that the user is willing to pay.
    // It is akin to EIP1559's maxFeePerGas.
    uint256 maxFeePerGas;
    // The maximum priority fee per gas that the user is willing to pay.
    // It is akin to EIP1559's maxPriorityFeePerGas.
    uint256 maxPriorityFeePerGas;
    // The transaction's paymaster. If there is no paymaster, it is equal to 0.
    uint256 paymaster;
    // The nonce of the transaction.
    uint256 nonce;
    // The value to pass with the transaction.
    uint256 value;
    // In the future, we might want to add some
    // new fields to the struct. The `txData` struct
    // is to be passed to account and any changes to its structure
    // would mean a breaking change to these accounts. In order to prevent this,
    // we should keep some fields as "reserved".
    // It is also recommended that their length is fixed, since
    // it would allow easier proof integration (in case we will need
    // some special circuit for preprocessing transactions).
    uint256[4] reserved;
    // The transaction's calldata.
    bytes data;
    // The signature of the transaction.
    bytes signature;
    // The properly formatted hashes of bytecodes that must be published on L1
    // with the inclusion of this transaction. Note, that a bytecode has been published
    // before, the user won't pay fees for its republishing.
    bytes32[] factoryDeps;
    // The input to the paymaster.
    bytes paymasterInput;
    // Reserved dynamic type for the future use-case. Using it should be avoided,
    // But it is still here, just in case we want to enable some additional functionality.
    bytes reservedDynamic;
}

/**
 * @author Matter Labs
 * @notice Library is used to help custom accounts to work with common methods for the Transaction type.
 */
library TransactionHelper {
    using SafeERC20 for IERC20;

    /// @notice The EIP-712 typehash for the contract's domain
    bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId)");

    bytes32 constant EIP712_TRANSACTION_TYPE_HASH =
        keccak256(
            "Transaction(uint256 txType,uint256 from,uint256 to,uint256 gasLimit,uint256 gasPerPubdataByteLimit,uint256 maxFeePerGas,uint256 maxPriorityFeePerGas,uint256 paymaster,uint256 nonce,uint256 value,bytes data,bytes32[] factoryDeps,bytes paymasterInput)"
        );

    /// @notice Whether the token is Ethereum.
    /// @param _addr The address of the token
    /// @return `true` or `false` based on whether the token is Ether.
    /// @dev This method assumes that address is Ether either if the address is 0 (for convenience)
    /// or if the address is the address of the L2EthToken system contract.
    function isEthToken(uint256 _addr) internal pure returns (bool) {
        return _addr == uint256(uint160(address(ETH_TOKEN_SYSTEM_CONTRACT))) || _addr == 0;
    }

    /// @notice Calculate the suggested signed hash of the transaction,
    /// i.e. the hash that is signed by EOAs and is recommended to be signed by other accounts.
    function encodeHash(Transaction calldata _transaction) internal view returns (bytes32 resultHash) {
        if (_transaction.txType == LEGACY_TX_TYPE) {
            resultHash = _encodeHashLegacyTransaction(_transaction);
        } else if (_transaction.txType == EIP_712_TX_TYPE) {
            resultHash = _encodeHashEIP712Transaction(_transaction);
        } else if (_transaction.txType == EIP_1559_TX_TYPE) {
            resultHash = _encodeHashEIP1559Transaction(_transaction);
        } else if (_transaction.txType == EIP_2930_TX_TYPE) {
            resultHash = _encodeHashEIP2930Transaction(_transaction);
        } else {
            // Currently no other transaction types are supported.
            // Any new transaction types will be processed in a similar manner.
            revert("Encoding unsupported tx");
        }
    }

    /// @notice Encode hash of the zkSync native transaction type.
    /// @return keccak256 hash of the EIP-712 encoded representation of transaction
    function _encodeHashEIP712Transaction(Transaction calldata _transaction) private view returns (bytes32) {
        bytes32 structHash = keccak256(
            abi.encode(
                EIP712_TRANSACTION_TYPE_HASH,
                _transaction.txType,
                _transaction.from,
                _transaction.to,
                _transaction.gasLimit,
                _transaction.gasPerPubdataByteLimit,
                _transaction.maxFeePerGas,
                _transaction.maxPriorityFeePerGas,
                _transaction.paymaster,
                _transaction.nonce,
                _transaction.value,
                EfficientCall.keccak(_transaction.data),
                keccak256(abi.encodePacked(_transaction.factoryDeps)),
                EfficientCall.keccak(_transaction.paymasterInput)
            )
        );

        bytes32 domainSeparator = keccak256(
            abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256("zkSync"), keccak256("2"), block.chainid)
        );

        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }

    /// @notice Encode hash of the legacy transaction type.
    /// @return keccak256 of the serialized RLP encoded representation of transaction
    function _encodeHashLegacyTransaction(Transaction calldata _transaction) private view returns (bytes32) {
        // Hash of legacy transactions are encoded as one of the:
        // - RLP(nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0)
        // - RLP(nonce, gasPrice, gasLimit, to, value, data)
        //
        // In this RLP encoding, only the first one above list appears, so we encode each element
        // inside list and then concatenate the length of all elements with them.

        bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
        // Encode `gasPrice` and `gasLimit` together to prevent "stack too deep error".
        bytes memory encodedGasParam;
        {
            bytes memory encodedGasPrice = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            encodedGasParam = bytes.concat(encodedGasPrice, encodedGasLimit);
        }

        bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
        bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        // Encode `chainId` according to EIP-155, but only if the `chainId` is specified in the transaction.
        bytes memory encodedChainId;
        if (_transaction.reserved[0] != 0) {
            encodedChainId = bytes.concat(RLPEncoder.encodeUint256(block.chainid), hex"80_80");
        }

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedNonce.length +
                encodedGasParam.length +
                encodedTo.length +
                encodedValue.length +
                encodedDataLength.length +
                _transaction.data.length +
                encodedChainId.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    encodedListLength,
                    encodedNonce,
                    encodedGasParam,
                    encodedTo,
                    encodedValue,
                    encodedDataLength,
                    _transaction.data,
                    encodedChainId
                )
            );
    }

    /// @notice Encode hash of the EIP2930 transaction type.
    /// @return keccak256 of the serialized RLP encoded representation of transaction
    function _encodeHashEIP2930Transaction(Transaction calldata _transaction) private view returns (bytes32) {
        // Hash of EIP2930 transactions is encoded the following way:
        // H(0x01 || RLP(chain_id, nonce, gas_price, gas_limit, destination, amount, data, access_list))
        //
        // Note, that on zkSync access lists are not supported and should always be empty.

        // Encode all fixed-length params to avoid "stack too deep error"
        bytes memory encodedFixedLengthParams;
        {
            bytes memory encodedChainId = RLPEncoder.encodeUint256(block.chainid);
            bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
            bytes memory encodedGasPrice = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
            bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
            encodedFixedLengthParams = bytes.concat(
                encodedChainId,
                encodedNonce,
                encodedGasPrice,
                encodedGasLimit,
                encodedTo,
                encodedValue
            );
        }

        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        // On zkSync, access lists are always zero length (at least for now).
        bytes memory encodedAccessListLength = RLPEncoder.encodeListLen(0);

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedFixedLengthParams.length +
                encodedDataLength.length +
                _transaction.data.length +
                encodedAccessListLength.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    "\x01",
                    encodedListLength,
                    encodedFixedLengthParams,
                    encodedDataLength,
                    _transaction.data,
                    encodedAccessListLength
                )
            );
    }

    /// @notice Encode hash of the EIP1559 transaction type.
    /// @return keccak256 of the serialized RLP encoded representation of transaction
    function _encodeHashEIP1559Transaction(Transaction calldata _transaction) private view returns (bytes32) {
        // Hash of EIP1559 transactions is encoded the following way:
        // H(0x02 || RLP(chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas, gas_limit, destination, amount, data, access_list))
        //
        // Note, that on zkSync access lists are not supported and should always be empty.

        // Encode all fixed-length params to avoid "stack too deep error"
        bytes memory encodedFixedLengthParams;
        {
            bytes memory encodedChainId = RLPEncoder.encodeUint256(block.chainid);
            bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
            bytes memory encodedMaxPriorityFeePerGas = RLPEncoder.encodeUint256(_transaction.maxPriorityFeePerGas);
            bytes memory encodedMaxFeePerGas = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
            bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
            encodedFixedLengthParams = bytes.concat(
                encodedChainId,
                encodedNonce,
                encodedMaxPriorityFeePerGas,
                encodedMaxFeePerGas,
                encodedGasLimit,
                encodedTo,
                encodedValue
            );
        }

        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        // On zkSync, access lists are always zero length (at least for now).
        bytes memory encodedAccessListLength = RLPEncoder.encodeListLen(0);

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedFixedLengthParams.length +
                encodedDataLength.length +
                _transaction.data.length +
                encodedAccessListLength.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    "\x02",
                    encodedListLength,
                    encodedFixedLengthParams,
                    encodedDataLength,
                    _transaction.data,
                    encodedAccessListLength
                )
            );
    }

    /// @notice Processes the common paymaster flows, e.g. setting proper allowance
    /// for tokens, etc. For more information on the expected behavior, check out
    /// the "Paymaster flows" section in the documentation.
    function processPaymasterInput(Transaction calldata _transaction) internal {
        require(_transaction.paymasterInput.length >= 4, "The standard paymaster input must be at least 4 bytes long");

        bytes4 paymasterInputSelector = bytes4(_transaction.paymasterInput[0:4]);
        if (paymasterInputSelector == IPaymasterFlow.approvalBased.selector) {
            require(
                _transaction.paymasterInput.length >= 68,
                "The approvalBased paymaster input must be at least 68 bytes long"
            );

            // While the actual data consists of address, uint256 and bytes data,
            // the data is needed only for the paymaster, so we ignore it here for the sake of optimization
            (address token, uint256 minAllowance) = abi.decode(_transaction.paymasterInput[4:68], (address, uint256));
            address paymaster = address(uint160(_transaction.paymaster));

            uint256 currentAllowance = IERC20(token).allowance(address(this), paymaster);
            if (currentAllowance < minAllowance) {
                // Some tokens, e.g. USDT require that the allowance is firsty set to zero
                // and only then updated to the new value.

                IERC20(token).safeApprove(paymaster, 0);
                IERC20(token).safeApprove(paymaster, minAllowance);
            }
        } else if (paymasterInputSelector == IPaymasterFlow.general.selector) {
            // Do nothing. general(bytes) paymaster flow means that the paymaster must interpret these bytes on his own.
        } else {
            revert("Unsupported paymaster flow");
        }
    }

    /// @notice Pays the required fee for the transaction to the bootloader.
    /// @dev Currently it pays the maximum amount "_transaction.maxFeePerGas * _transaction.gasLimit",
    /// it will change in the future.
    function payToTheBootloader(Transaction calldata _transaction) internal returns (bool success) {
        address bootloaderAddr = BOOTLOADER_FORMAL_ADDRESS;
        uint256 amount = _transaction.maxFeePerGas * _transaction.gasLimit;

        assembly {
            success := call(gas(), bootloaderAddr, amount, 0, 0, 0, 0)
        }
    }

    // Returns the balance required to process the transaction.
    function totalRequiredBalance(Transaction calldata _transaction) internal pure returns (uint256 requiredBalance) {
        if (address(uint160(_transaction.paymaster)) != address(0)) {
            // Paymaster pays for the fee
            requiredBalance = _transaction.value;
        } else {
            // The user should have enough balance for both the fee and the value of the transaction
            requiredBalance = _transaction.maxFeePerGas * _transaction.gasLimit + _transaction.value;
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8;

import {MAX_SYSTEM_CONTRACT_ADDRESS, MSG_VALUE_SYSTEM_CONTRACT} from "../Constants.sol";

import "./SystemContractsCaller.sol";
import "./Utils.sol";

uint256 constant UINT32_MASK = 0xffffffff;
uint256 constant UINT128_MASK = 0xffffffffffffffffffffffffffffffff;
/// @dev The mask that is used to convert any uint256 to a proper address.
/// It needs to be padded with `00` to be treated as uint256 by Solidity
uint256 constant ADDRESS_MASK = 0x00ffffffffffffffffffffffffffffffffffffffff;

struct ZkSyncMeta {
    uint32 gasPerPubdataByte;
    uint32 heapSize;
    uint32 auxHeapSize;
    uint8 shardId;
    uint8 callerShardId;
    uint8 codeShardId;
}

enum Global {
    CalldataPtr,
    CallFlags,
    ExtraABIData1,
    ExtraABIData2,
    ReturndataPtr
}

/**
 * @author Matter Labs
 * @notice Library used for accessing zkEVM-specific opcodes, needed for the development
 * of system contracts.
 * @dev While this library will be eventually available to public, some of the provided
 * methods won't work for non-system contracts. We will not recommend this library
 * for external use.
 */
library SystemContractHelper {
    /// @notice Send an L2Log to L1.
    /// @param _isService The `isService` flag.
    /// @param _key The `key` part of the L2Log.
    /// @param _value The `value` part of the L2Log.
    /// @dev The meaning of all these parameters is context-dependent, but they
    /// have no intrinsic meaning per se.
    function toL1(bool _isService, bytes32 _key, bytes32 _value) internal {
        address callAddr = TO_L1_CALL_ADDRESS;
        assembly {
            // Ensuring that the type is bool
            _isService := and(_isService, 1)
            // This `success` is always 0, but the method always succeeds
            // (except for the cases when there is not enough gas)
            let success := call(_isService, callAddr, _key, _value, 0xFFFF, 0, 0)
        }
    }

    /// @notice Get address of the currently executed code.
    /// @dev This allows differentiating between `call` and `delegatecall`.
    /// During the former `this` and `codeAddress` are the same, while
    /// during the latter they are not.
    function getCodeAddress() internal view returns (address addr) {
        address callAddr = CODE_ADDRESS_CALL_ADDRESS;
        assembly {
            addr := staticcall(0, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Provide a compiler hint, by placing calldata fat pointer into virtual `ACTIVE_PTR`,
    /// that can be manipulated by `ptr.add`/`ptr.sub`/`ptr.pack`/`ptr.shrink` later.
    /// @dev This allows making a call by forwarding calldata pointer to the child call.
    /// It is a much more efficient way to forward calldata, than standard EVM bytes copying.
    function loadCalldataIntoActivePtr() internal view {
        address callAddr = LOAD_CALLDATA_INTO_ACTIVE_PTR_CALL_ADDRESS;
        assembly {
            pop(staticcall(0, callAddr, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice Compiler simulation of the `ptr.pack` opcode for the virtual `ACTIVE_PTR` pointer.
    /// @dev Do the concatenation between lowest part of `ACTIVE_PTR` and highest part of `_farCallAbi`
    /// forming packed fat pointer for a far call or ret ABI when necessary.
    /// Note: Panics if the lowest 128 bits of `_farCallAbi` are not zeroes.
    function ptrPackIntoActivePtr(uint256 _farCallAbi) internal view {
        address callAddr = PTR_PACK_INTO_ACTIVE_CALL_ADDRESS;
        assembly {
            pop(staticcall(_farCallAbi, callAddr, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice Compiler simulation of the `ptr.add` opcode for the virtual `ACTIVE_PTR` pointer.
    /// @dev Transforms `ACTIVE_PTR.offset` into `ACTIVE_PTR.offset + u32(_value)`. If overflow happens then it panics.
    function ptrAddIntoActive(uint32 _value) internal view {
        address callAddr = PTR_ADD_INTO_ACTIVE_CALL_ADDRESS;
        uint256 cleanupMask = UINT32_MASK;
        assembly {
            // Clearing input params as they are not cleaned by Solidity by default
            _value := and(_value, cleanupMask)
            pop(staticcall(_value, callAddr, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice Compiler simulation of the `ptr.shrink` opcode for the virtual `ACTIVE_PTR` pointer.
    /// @dev Transforms `ACTIVE_PTR.length` into `ACTIVE_PTR.length - u32(_shrink)`. If underflow happens then it panics.
    function ptrShrinkIntoActive(uint32 _shrink) internal view {
        address callAddr = PTR_SHRINK_INTO_ACTIVE_CALL_ADDRESS;
        uint256 cleanupMask = UINT32_MASK;
        assembly {
            // Clearing input params as they are not cleaned by Solidity by default
            _shrink := and(_shrink, cleanupMask)
            pop(staticcall(_shrink, callAddr, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice packs precompile parameters into one word
    /// @param _inputMemoryOffset The memory offset in 32-byte words for the input data for calling the precompile.
    /// @param _inputMemoryLength The length of the input data in words.
    /// @param _outputMemoryOffset The memory offset in 32-byte words for the output data.
    /// @param _outputMemoryLength The length of the output data in words.
    /// @param _perPrecompileInterpreted The constant, the meaning of which is defined separately for
    /// each precompile. For information, please read the documentation of the precompilecall log in
    /// the VM.
    function packPrecompileParams(
        uint32 _inputMemoryOffset,
        uint32 _inputMemoryLength,
        uint32 _outputMemoryOffset,
        uint32 _outputMemoryLength,
        uint64 _perPrecompileInterpreted
    ) internal pure returns (uint256 rawParams) {
        rawParams = _inputMemoryOffset;
        rawParams |= uint256(_inputMemoryLength) << 32;
        rawParams |= uint256(_outputMemoryOffset) << 64;
        rawParams |= uint256(_outputMemoryLength) << 96;
        rawParams |= uint256(_perPrecompileInterpreted) << 192;
    }

    /// @notice Call precompile with given parameters.
    /// @param _rawParams The packed precompile params. They can be retrieved by
    /// the `packPrecompileParams` method.
    /// @param _gasToBurn The number of gas to burn during this call.
    /// @return success Whether the call was successful.
    /// @dev The list of currently available precompiles sha256, keccak256, ecrecover.
    /// NOTE: The precompile type depends on `this` which calls precompile, which means that only
    /// system contracts corresponding to the list of precompiles above can do `precompileCall`.
    /// @dev If used not in the `sha256`, `keccak256` or `ecrecover` contracts, it will just burn the gas provided.
    function precompileCall(uint256 _rawParams, uint32 _gasToBurn) internal view returns (bool success) {
        address callAddr = PRECOMPILE_CALL_ADDRESS;

        // After `precompileCall` gas will be burned down to 0 if there are not enough of them,
        // thats why it should be checked before the call.
        require(gasleft() >= _gasToBurn);
        uint256 cleanupMask = UINT32_MASK;
        assembly {
            // Clearing input params as they are not cleaned by Solidity by default
            _gasToBurn := and(_gasToBurn, cleanupMask)
            success := staticcall(_rawParams, callAddr, _gasToBurn, 0xFFFF, 0, 0)
        }
    }

    /// @notice Set `msg.value` to next far call.
    /// @param _value The msg.value that will be used for the *next* call.
    /// @dev If called not in kernel mode, it will result in a revert (enforced by the VM)
    function setValueForNextFarCall(uint128 _value) internal returns (bool success) {
        uint256 cleanupMask = UINT128_MASK;
        address callAddr = SET_CONTEXT_VALUE_CALL_ADDRESS;
        assembly {
            // Clearing input params as they are not cleaned by Solidity by default
            _value := and(_value, cleanupMask)
            success := call(0, callAddr, _value, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Initialize a new event.
    /// @param initializer The event initializing value.
    /// @param value1 The first topic or data chunk.
    function eventInitialize(uint256 initializer, uint256 value1) internal {
        address callAddr = EVENT_INITIALIZE_ADDRESS;
        assembly {
            pop(call(initializer, callAddr, value1, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice Continue writing the previously initialized event.
    /// @param value1 The first topic or data chunk.
    /// @param value2 The second topic or data chunk.
    function eventWrite(uint256 value1, uint256 value2) internal {
        address callAddr = EVENT_WRITE_ADDRESS;
        assembly {
            pop(call(value1, callAddr, value2, 0, 0xFFFF, 0, 0))
        }
    }

    /// @notice Get the packed representation of the `ZkSyncMeta` from the current context.
    /// @return meta The packed representation of the ZkSyncMeta.
    /// @dev The fields in ZkSyncMeta are NOT tightly packed, i.e. there is a special rule on how
    /// they are packed. For more information, please read the documentation on ZkSyncMeta.
    function getZkSyncMetaBytes() internal view returns (uint256 meta) {
        address callAddr = META_CALL_ADDRESS;
        assembly {
            meta := staticcall(0, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Returns the bits [offset..offset+size-1] of the meta.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @param offset The offset of the bits.
    /// @param size The size of the extracted number in bits.
    /// @return result The extracted number.
    function extractNumberFromMeta(uint256 meta, uint256 offset, uint256 size) internal pure returns (uint256 result) {
        // Firstly, we delete all the bits after the field
        uint256 shifted = (meta << (256 - size - offset));
        // Then we shift everything back
        result = (shifted >> (256 - size));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the number of gas
    /// that a single byte sent to L1 as pubdata costs.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return gasPerPubdataByte The current price in gas per pubdata byte.
    function getGasPerPubdataByteFromMeta(uint256 meta) internal pure returns (uint32 gasPerPubdataByte) {
        gasPerPubdataByte = uint32(extractNumberFromMeta(meta, META_GAS_PER_PUBDATA_BYTE_OFFSET, 32));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the number of the current size
    /// of the heap in bytes.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return heapSize The size of the memory in bytes byte.
    /// @dev The following expression: getHeapSizeFromMeta(getZkSyncMetaBytes()) is
    /// equivalent to the MSIZE in Solidity.
    function getHeapSizeFromMeta(uint256 meta) internal pure returns (uint32 heapSize) {
        heapSize = uint32(extractNumberFromMeta(meta, META_HEAP_SIZE_OFFSET, 32));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the number of the current size
    /// of the auxilary heap in bytes.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return auxHeapSize The size of the auxilary memory in bytes byte.
    /// @dev You can read more on auxilary memory in the VM1.2 documentation.
    function getAuxHeapSizeFromMeta(uint256 meta) internal pure returns (uint32 auxHeapSize) {
        auxHeapSize = uint32(extractNumberFromMeta(meta, META_AUX_HEAP_SIZE_OFFSET, 32));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the shardId of `this`.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return shardId The shardId of `this`.
    /// @dev Currently only shard 0 (zkRollup) is supported.
    function getShardIdFromMeta(uint256 meta) internal pure returns (uint8 shardId) {
        shardId = uint8(extractNumberFromMeta(meta, META_SHARD_ID_OFFSET, 8));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the shardId of
    /// the msg.sender.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return callerShardId The shardId of the msg.sender.
    /// @dev Currently only shard 0 (zkRollup) is supported.
    function getCallerShardIdFromMeta(uint256 meta) internal pure returns (uint8 callerShardId) {
        callerShardId = uint8(extractNumberFromMeta(meta, META_CALLER_SHARD_ID_OFFSET, 8));
    }

    /// @notice Given the packed representation of `ZkSyncMeta`, retrieves the shardId of
    /// the currently executed code.
    /// @param meta Packed representation of the ZkSyncMeta.
    /// @return codeShardId The shardId of the currently executed code.
    /// @dev Currently only shard 0 (zkRollup) is supported.
    function getCodeShardIdFromMeta(uint256 meta) internal pure returns (uint8 codeShardId) {
        codeShardId = uint8(extractNumberFromMeta(meta, META_CODE_SHARD_ID_OFFSET, 8));
    }

    /// @notice Retrieves the ZkSyncMeta structure.
    /// @return meta The ZkSyncMeta execution context parameters.
    function getZkSyncMeta() internal view returns (ZkSyncMeta memory meta) {
        uint256 metaPacked = getZkSyncMetaBytes();
        meta.gasPerPubdataByte = getGasPerPubdataByteFromMeta(metaPacked);
        meta.shardId = getShardIdFromMeta(metaPacked);
        meta.callerShardId = getCallerShardIdFromMeta(metaPacked);
        meta.codeShardId = getCodeShardIdFromMeta(metaPacked);
    }

    /// @notice Returns the call flags for the current call.
    /// @return callFlags The bitmask of the callflags.
    /// @dev Call flags is the value of the first register
    /// at the start of the call.
    /// @dev The zero bit of the callFlags indicates whether the call is
    /// a constructor call. The first bit of the callFlags indicates whether
    /// the call is a system one.
    function getCallFlags() internal view returns (uint256 callFlags) {
        address callAddr = CALLFLAGS_CALL_ADDRESS;
        assembly {
            callFlags := staticcall(0, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Returns the current calldata pointer.
    /// @return ptr The current calldata pointer.
    /// @dev NOTE: This file is just an integer and it can not be used
    /// to forward the calldata to the next calls in any way.
    function getCalldataPtr() internal view returns (uint256 ptr) {
        address callAddr = PTR_CALLDATA_CALL_ADDRESS;
        assembly {
            ptr := staticcall(0, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Returns the N-th extraAbiParam for the current call.
    /// @return extraAbiData The value of the N-th extraAbiParam for this call.
    /// @dev It is equal to the value of the (N+2)-th register
    /// at the start of the call.
    function getExtraAbiData(uint256 index) internal view returns (uint256 extraAbiData) {
        require(index < 10, "There are only 10 accessible registers");

        address callAddr = GET_EXTRA_ABI_DATA_ADDRESS;
        assembly {
            extraAbiData := staticcall(index, callAddr, 0, 0xFFFF, 0, 0)
        }
    }

    /// @notice Retuns whether the current call is a system call.
    /// @return `true` or `false` based on whether the current call is a system call.
    function isSystemCall() internal view returns (bool) {
        uint256 callFlags = getCallFlags();
        // When the system call is passed, the 2-bit it set to 1
        return (callFlags & 2) != 0;
    }

    /// @notice Returns whether the address is a system contract.
    /// @param _address The address to test
    /// @return `true` or `false` based on whether the `_address` is a system contract.
    function isSystemContract(address _address) internal pure returns (bool) {
        return uint160(_address) <= uint160(MAX_SYSTEM_CONTRACT_ADDRESS);
    }
}

/// @dev Solidity does not allow exporting modifiers via libraries, so
/// the only way to do reuse modifiers is to have a base contract
abstract contract ISystemContract {
    /// @notice Modifier that makes sure that the method
    /// can only be called via a system call.
    modifier onlySystemCall() {
        require(
            SystemContractHelper.isSystemCall() || SystemContractHelper.isSystemContract(msg.sender),
            "This method require system call flag"
        );
        _;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

interface IAGWRegistry {
    function register(address account) external;

    function isAGW(address account) external view returns (bool);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {IInitable} from '../interfaces/IInitable.sol';
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';

interface IModule is IInitable, IERC165 {}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

library AGWStorage {
    //keccak256('agw.contracts.AGWStorage') - 1
    bytes32 private constant AGW_STORAGE_SLOT =
        0x67641650ff26a63f6b1fb8b1cb96de5bac5c28fcfcca35c9518ea6966d32d42d;

    struct Layout {
        // ┌───────────────────┐
        // │   Ownership Data  │
        mapping(bytes => bytes) r1Owners;
        mapping(address => address) k1Owners;
        uint256[50] __gap_0;
        // └───────────────────┘

        // ┌───────────────────┐
        // │     Fallback      │
        address defaultFallbackContract; // for next version
        uint256[50] __gap_1;
        // └───────────────────┘

        // ┌───────────────────┐
        // │     Validation    │
        mapping(address => address) r1Validators;
        mapping(address => address) k1Validators;
        mapping(address => address) moduleValidators;
        uint256[49] __gap_2;
        // └───────────────────┘

        // ┌───────────────────┐
        // │       Module      │
        mapping(address => address) modules;
        uint256[50] __gap_3;
        // └───────────────────┘

        // ┌───────────────────┐
        // │       Hooks       │
        mapping(address => address) validationHooks;
        mapping(address => address) executionHooks;
        mapping(address => mapping(bytes32 => bytes)) hookDataStore;
        uint256[50] __gap_4;
        // └───────────────────┘
    }

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = AGW_STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

interface IInitable {
    event Inited(address indexed account);
    event Disabled(address indexed account);

    function init(bytes calldata initData) external;

    function disable() external;

    function isInited(address account) external view returns (bool);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';

/**
 * @title Bytes linked list library
 * @notice Helper library for bytes linkedlist operations
 * @author https://getclave.io
 */
library BytesLinkedList {
    bytes internal constant SENTINEL_BYTES = hex'00';
    uint8 internal constant SENTINEL_LENGTH = 1;

    modifier validBytes(bytes calldata value) {
        if (value.length <= SENTINEL_LENGTH) {
            revert Errors.INVALID_BYTES();
        }
        _;
    }

    function add(
        mapping(bytes => bytes) storage self,
        bytes calldata value
    ) internal validBytes(value) {
        if (self[value].length != 0) {
            revert Errors.BYTES_ALREADY_EXISTS();
        }

        bytes memory prev = self[SENTINEL_BYTES];
        if (prev.length < SENTINEL_LENGTH) {
            self[SENTINEL_BYTES] = value;
            self[value] = SENTINEL_BYTES;
        } else {
            self[SENTINEL_BYTES] = value;
            self[value] = prev;
        }
    }

    function replace(
        mapping(bytes => bytes) storage self,
        bytes calldata oldValue,
        bytes calldata newValue
    ) internal {
        if (!exists(self, oldValue)) {
            revert Errors.BYTES_NOT_EXISTS();
        }
        if (exists(self, newValue)) {
            revert Errors.BYTES_ALREADY_EXISTS();
        }

        bytes memory cursor = SENTINEL_BYTES;
        while (true) {
            bytes memory _value = self[cursor];
            if (equals(_value, oldValue)) {
                bytes memory next = self[_value];
                self[newValue] = next;
                self[cursor] = newValue;
                delete self[_value];
                return;
            }
            cursor = _value;
        }
    }

    function replaceUsingPrev(
        mapping(bytes => bytes) storage self,
        bytes calldata prevValue,
        bytes calldata oldValue,
        bytes calldata newValue
    ) internal {
        if (!exists(self, oldValue)) {
            revert Errors.BYTES_NOT_EXISTS();
        }
        if (exists(self, newValue)) {
            revert Errors.BYTES_ALREADY_EXISTS();
        }
        if (!equals(self[prevValue], oldValue)) {
            revert Errors.INVALID_PREV();
        }

        self[newValue] = self[oldValue];
        self[prevValue] = newValue;
        delete self[oldValue];
    }

    function remove(mapping(bytes => bytes) storage self, bytes calldata value) internal {
        if (!exists(self, value)) {
            revert Errors.BYTES_NOT_EXISTS();
        }

        bytes memory cursor = SENTINEL_BYTES;
        while (true) {
            bytes memory _value = self[cursor];
            if (equals(_value, value)) {
                bytes memory next = self[_value];
                self[cursor] = next;
                delete self[_value];
                return;
            }
            cursor = _value;
        }
    }

    function removeUsingPrev(
        mapping(bytes => bytes) storage self,
        bytes calldata prevValue,
        bytes calldata value
    ) internal {
        if (!exists(self, value)) {
            revert Errors.BYTES_NOT_EXISTS();
        }
        if (!equals(self[prevValue], value)) {
            revert Errors.INVALID_PREV();
        }

        self[prevValue] = self[value];
        delete self[value];
    }

    function clear(mapping(bytes => bytes) storage self) internal {
        bytes memory cursor = SENTINEL_BYTES;
        do {
            bytes memory nextCursor = self[cursor];
            delete self[cursor];
            cursor = nextCursor;
        } while (cursor.length > SENTINEL_LENGTH);
    }

    function exists(
        mapping(bytes => bytes) storage self,
        bytes calldata value
    ) internal view validBytes(value) returns (bool) {
        return self[value].length != 0;
    }

    function size(mapping(bytes => bytes) storage self) internal view returns (uint256) {
        uint256 result = 0;
        bytes memory cursor = self[SENTINEL_BYTES];
        while (cursor.length > SENTINEL_LENGTH) {
            cursor = self[cursor];
            unchecked {
                result++;
            }
        }
        return result;
    }

    function isEmpty(mapping(bytes => bytes) storage self) internal view returns (bool) {
        return self[SENTINEL_BYTES].length <= SENTINEL_LENGTH;
    }

    function list(mapping(bytes => bytes) storage self) internal view returns (bytes[] memory) {
        uint256 _size = size(self);
        bytes[] memory result = new bytes[](_size);
        uint256 i = 0;
        bytes memory cursor = self[SENTINEL_BYTES];
        while (cursor.length > SENTINEL_LENGTH) {
            result[i] = cursor;
            cursor = self[cursor];
            unchecked {
                i++;
            }
        }

        return result;
    }

    function equals(bytes memory a, bytes memory b) private pure returns (bool result) {
        assembly {
            result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
        }
    }
}

/**
 * @title Address linked list library
 * @notice Helper library for address linkedlist operations
 */
library AddressLinkedList {
    address internal constant SENTINEL_ADDRESS = address(1);

    modifier validAddress(address value) {
        if (value <= SENTINEL_ADDRESS) {
            revert Errors.INVALID_ADDRESS();
        }
        _;
    }

    function add(
        mapping(address => address) storage self,
        address value
    ) internal validAddress(value) {
        if (self[value] != address(0)) {
            revert Errors.ADDRESS_ALREADY_EXISTS();
        }

        address prev = self[SENTINEL_ADDRESS];
        if (prev == address(0)) {
            self[SENTINEL_ADDRESS] = value;
            self[value] = SENTINEL_ADDRESS;
        } else {
            self[SENTINEL_ADDRESS] = value;
            self[value] = prev;
        }
    }

    function replace(
        mapping(address => address) storage self,
        address oldValue,
        address newValue
    ) internal {
        if (!exists(self, oldValue)) {
            revert Errors.ADDRESS_NOT_EXISTS();
        }
        if (exists(self, newValue)) {
            revert Errors.ADDRESS_ALREADY_EXISTS();
        }

        address cursor = SENTINEL_ADDRESS;
        while (true) {
            address _value = self[cursor];
            if (_value == oldValue) {
                address next = self[_value];
                self[newValue] = next;
                self[cursor] = newValue;
                delete self[_value];
                return;
            }
            cursor = _value;
        }
    }

    function replaceUsingPrev(
        mapping(address => address) storage self,
        address prevValue,
        address oldValue,
        address newValue
    ) internal {
        if (!exists(self, oldValue)) {
            revert Errors.ADDRESS_NOT_EXISTS();
        }
        if (exists(self, newValue)) {
            revert Errors.ADDRESS_ALREADY_EXISTS();
        }
        if (self[prevValue] != oldValue) {
            revert Errors.INVALID_PREV();
        }

        self[newValue] = self[oldValue];
        self[prevValue] = newValue;
        delete self[oldValue];
    }

    function remove(mapping(address => address) storage self, address value) internal {
        if (!exists(self, value)) {
            revert Errors.ADDRESS_NOT_EXISTS();
        }

        address cursor = SENTINEL_ADDRESS;
        while (true) {
            address _value = self[cursor];
            if (_value == value) {
                address next = self[_value];
                self[cursor] = next;
                delete self[_value];
                return;
            }
            cursor = _value;
        }
    }

    function removeUsingPrev(
        mapping(address => address) storage self,
        address prevValue,
        address value
    ) internal {
        if (!exists(self, value)) {
            revert Errors.ADDRESS_NOT_EXISTS();
        }
        if (self[prevValue] != value) {
            revert Errors.INVALID_PREV();
        }

        self[prevValue] = self[value];
        delete self[value];
    }

    function clear(mapping(address => address) storage self) internal {
        address cursor = SENTINEL_ADDRESS;
        do {
            address nextCursor = self[cursor];
            delete self[cursor];
            cursor = nextCursor;
        } while (cursor > SENTINEL_ADDRESS);
    }

    function exists(
        mapping(address => address) storage self,
        address value
    ) internal view validAddress(value) returns (bool) {
        return self[value] != address(0);
    }

    function size(mapping(address => address) storage self) internal view returns (uint256) {
        uint256 result = 0;
        address cursor = self[SENTINEL_ADDRESS];
        while (cursor > SENTINEL_ADDRESS) {
            cursor = self[cursor];
            unchecked {
                result++;
            }
        }
        return result;
    }

    function isEmpty(mapping(address => address) storage self) internal view returns (bool) {
        return self[SENTINEL_ADDRESS] <= SENTINEL_ADDRESS;
    }

    function list(
        mapping(address => address) storage self
    ) internal view returns (address[] memory) {
        uint256 _size = size(self);
        address[] memory result = new address[](_size);
        uint256 i = 0;
        address cursor = self[SENTINEL_ADDRESS];
        while (cursor > SENTINEL_ADDRESS) {
            result[i] = cursor;
            cursor = self[cursor];
            unchecked {
                i++;
            }
        }

        return result;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {BootloaderAuth} from './BootloaderAuth.sol';
import {ModuleAuth} from './ModuleAuth.sol';
import {SelfAuth} from './SelfAuth.sol';
import {HookAuth} from './HookAuth.sol';
import {Errors} from '../libraries/Errors.sol';

/**
 * @title Auth
 * @notice Abstract contract that organizes authentification logic for the contract
 * @author https://getclave.io
 */
abstract contract Auth is BootloaderAuth, SelfAuth, ModuleAuth, HookAuth {
    modifier onlySelfOrModule() {
        if (msg.sender != address(this) && !_isModule(msg.sender)) {
            revert Errors.NOT_FROM_SELF_OR_MODULE();
        }
        _;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

/**
 * @title Interface of the manager contract for modules
 * @author https://getclave.io
 */
interface IModuleManager {
    /**
     * @notice Event emitted when a module is added
     * @param module address - Address of the added module
     */
    event AddModule(address indexed module);

    /**
     * @notice Event emitted when a module is removed
     * @param module address - Address of the removed module
     */
    event RemoveModule(address indexed module);

    /**
     * @notice Add a module to the list of modules and call it's init function
     * @dev Can only be called by self or a module
     * @param moduleAndData bytes calldata - Address of the module and data to initialize it with
     */
    function addModule(bytes calldata moduleAndData) external;

    /**
     * @notice Remove a module from the list of modules and call it's disable function
     * @dev Can only be called by self or a module
     * @param module address - Address of the module to remove
     */
    function removeModule(address module) external;

    /**
     * @notice Allow modules to execute arbitrary calls on behalf of the account
     * @dev Can only be called by a module
     * @param to address - Address to call
     * @param value uint256 - Eth to send with call
     * @param data bytes memory - Data to make the call with
     */
    function executeFromModule(address to, uint256 value, bytes memory data) external;

    /**
     * @notice Check if an address is in the list of modules
     * @param addr address - Address to check
     * @return bool - True if the address is a module, false otherwise
     */
    function isModule(address addr) external view returns (bool);

    /**
     * @notice Get the list of modules
     * @return moduleList address[] memory - List of modules
     */
    function listModules() external view returns (address[] memory moduleList);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {SignatureDecoder} from '../libraries/SignatureDecoder.sol';
import {BytesLinkedList, AddressLinkedList} from '../libraries/LinkedList.sol';
import {OwnerManager} from '../managers/OwnerManager.sol';
import {ValidatorManager} from '../managers/ValidatorManager.sol';

import {IK1Validator, IR1Validator} from '../interfaces/IValidator.sol';
import {IModuleValidator} from '../interfaces/IModuleValidator.sol';
import {OperationType} from '../interfaces/IValidator.sol';

/**
 * @title ValidationHandler
 * @notice Contract which calls validators for signature validation
 * @author https://getclave.io
 */
abstract contract ValidationHandler is OwnerManager, ValidatorManager {
    function _handleValidation(
        address validator,
        OperationType operationType,
        bytes32 signedHash,
        bytes memory signature
    ) internal view returns (bool) {
        if (validator <= AddressLinkedList.SENTINEL_ADDRESS) {
            // address less than or equal to sentinel address can't be used in linked list
            // implementation so this scenario is never valid
            return false;
        } else if (_r1IsValidator(validator)) {
            mapping(bytes => bytes) storage owners = OwnerManager._r1OwnersLinkedList();
            bytes memory cursor = owners[BytesLinkedList.SENTINEL_BYTES];
            while (cursor.length > BytesLinkedList.SENTINEL_LENGTH) {
                bytes32[2] memory pubKey = abi.decode(cursor, (bytes32[2]));

                bool _success = IR1Validator(validator).validateSignature(
                    operationType,
                    signedHash,
                    signature,
                    pubKey
                );

                if (_success) {
                    return true;
                }

                cursor = owners[cursor];
            }
        } else if (_k1IsValidator(validator)) {
            address recoveredAddress = IK1Validator(validator).validateSignature(
                operationType,
                signedHash,
                signature
            );

            if (recoveredAddress == address(0)) {
                return false;
            }

            if (OwnerManager._k1IsOwner(recoveredAddress)) {
                return true;
            }
        } else if ( _isModuleValidator(validator)) {
            return IModuleValidator(validator).handleValidation(operationType, signedHash, signature);
        }

        return false;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

/**
 * @title Interface of the upgrade manager contract
 * @author https://getclave.io
 */
interface IUpgradeManager {
    /**
     * @notice Event emitted when the contract is upgraded
     * @param oldImplementation address - Address of the old implementation contract
     * @param newImplementation address - Address of the new implementation contract
     */
    event Upgraded(address indexed oldImplementation, address indexed newImplementation);

    /**
     * @notice Upgrades the account contract to a new implementation
     * @dev Can only be called by self
     * @param newImplementation address - Address of the new implementation contract
     */
    function upgradeTo(address newImplementation) external;

    /**
     * @notice Returns the current implementation address
     * @return address - Address of the current implementation contract
     */
    function implementationAddress() external view returns (address);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Transaction} from '@matterlabs/zksync-contracts/l2/system-contracts/libraries/TransactionHelper.sol';
import {IInitable} from '../interfaces/IInitable.sol';
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';

interface IValidationHook is IInitable, IERC165 {
    function validationHook(
        bytes32 signedHash,
        Transaction calldata transaction,
        bytes calldata hookData
    ) external;
}

interface IExecutionHook is IInitable, IERC165 {
    function preExecutionHook(
        Transaction calldata transaction
    ) external returns (bytes memory context);

    function postExecutionHook(bytes memory context) external;
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

/**
 * @title Interface of the manager contract for hooks
 * @author https://getclave.io
 */
interface IHookManager {
    /**
     * @notice Event emitted when a hook is added
     * @param hook address - Address of the added hook
     */
    event AddHook(address indexed hook);

    /**
     * @notice Event emitted when a hook is removed
     * @param hook address - Address of the removed hook
     */
    event RemoveHook(address indexed hook);

    /**
     * @notice Add a hook to the list of hooks and call it's init function
     * @dev Can only be called by self or a module
     * @param hookAndData bytes calldata - Address of the hook and data to initialize it with
     * @param isValidation bool          - True if the hook is a validation hook, false otherwise
     */
    function addHook(bytes calldata hookAndData, bool isValidation) external;

    /**
     * @notice Remove a hook from the list of hooks and call it's disable function
     * @dev Can only be called by self or a module
     * @param hook address      - Address of the hook to remove
     * @param isValidation bool - True if the hook is a validation hook, false otherwise
     */
    function removeHook(address hook, bool isValidation) external;

    /**
     * @notice Allow a hook to store data in the contract
     * @dev Can only be called by a hook
     * @param key bytes32         - Slot to store data at
     * @param data bytes calldata - Data to store
     */
    function setHookData(bytes32 key, bytes calldata data) external;

    /**
     * @notice Get the data stored by a hook
     * @param hook address  - Address of the hook to retrieve data for
     * @param key bytes32   - Slot to retrieve data from
     * @return bytes memory - Data stored at the slot
     */
    function getHookData(address hook, bytes32 key) external view returns (bytes memory);

    /**
     * @notice Check if an address is in the list of hooks
     * @param addr address - Address to check
     * @return bool        - True if the address is a hook, false otherwise
     */
    function isHook(address addr) external view returns (bool);

    /**
     * @notice Get the list of validation or execution hooks
     * @param isValidation bool          - True if the list of validation hooks should be returned, false otherwise
     * @return hookList address[] memory - List of validation or exeuction hooks
     */
    function listHooks(bool isValidation) external view returns (address[] memory hookList);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';

/**
 * @title SelfAuth
 * @notice Abstract contract that allows only calls by the self contract
 * @author https://getclave.io
 */
abstract contract SelfAuth {
    modifier onlySelf() {
        if (msg.sender != address(this)) {
            revert Errors.NOT_FROM_SELF();
        }
        _;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

/**
 * @title Interface of the manager contract for owners
 * @author https://getclave.io
 */
interface IOwnerManager {
    /**
     * @notice Event emitted when a r1 owner is added
     * @param pubKey bytes - r1 owner that has been added
     */
    event R1AddOwner(bytes pubKey);

    /**
     * @notice Event emitted when a k1 owner is added
     * @param addr address - k1 owner that has been added
     */
    event K1AddOwner(address indexed addr);

    /**
     * @notice Event emitted when a r1 owner is removed
     * @param pubKey bytes - r1 owner that has been removed
     */
    event R1RemoveOwner(bytes pubKey);

    /**
     * @notice Event emitted when a k1 owner is removed
     * @param addr address - k1 owner that has been removed
     */
    event K1RemoveOwner(address indexed addr);

    /**
     * @notice Event emitted when all owners are cleared
     */
    event ResetOwners();

    /**
     * @notice Adds a r1 owner to the list of r1 owners
     * @dev Can only be called by self or a whitelisted module
     * @dev Public Key length must be 64 bytes
     * @param pubKey bytes calldata - Public key to add to the list of r1 owners
     */
    function r1AddOwner(bytes calldata pubKey) external;

    /**
     * @notice Adds a k1 owner to the list of k1 owners
     * @dev Can only be called by self or a whitelisted module
     * @dev Address can not be the zero address
     * @param addr address - Address to add to the list of k1 owners
     */
    function k1AddOwner(address addr) external;

    /**
     * @notice Removes a r1 owner from the list of r1 owners
     * @dev Can only be called by self or a whitelisted module
     * @dev Can not remove the last r1 owner
     * @param pubKey bytes calldata - Public key to remove from the list of r1 owners
     */
    function r1RemoveOwner(bytes calldata pubKey) external;

    /**
     * @notice Removes a k1 owner from the list of k1 owners
     * @dev Can only be called by self or a whitelisted module
     * @param addr address - Address to remove from the list of k1 owners
     */
    function k1RemoveOwner(address addr) external;

    /**
     * @notice Clears both r1 owners and k1 owners and adds an r1 owner
     * @dev Can only be called by self or a whitelisted module
     * @dev Public Key length must be 64 bytes
     * @param pubKey bytes calldata - new r1 owner to add
     */
    function resetOwners(bytes calldata pubKey) external;

    /**
     * @notice Checks if a public key is in the list of r1 owners
     * @param pubKey bytes calldata - Public key to check
     * @return bool - True if the public key is in the list, false otherwise
     */
    function r1IsOwner(bytes calldata pubKey) external view returns (bool);

    /**
     * @notice Checks if an address is in the list of k1 owners
     * @param addr address - Address to check
     * @return bool - True if the address is in the list, false otherwise
     */
    function k1IsOwner(address addr) external view returns (bool);

    /**
     * @notice Returns the list of r1 owners
     * @return r1OwnerList bytes[] memory - Array of r1 owner public keys
     */
    function r1ListOwners() external view returns (bytes[] memory r1OwnerList);

    /**
     * @notice Returns the list of k1 owners
     * @return k1OwnerList address[] memory - Array of k1 owner addresses
     */
    function k1ListOwners() external view returns (address[] memory k1OwnerList);
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

/**
 * @title Manager contract for validators
 * @author https://getclave.io
 */
interface IValidatorManager {
    /**
     * @notice Event emitted when a r1 validator is added
     * @param validator address - Address of the added r1 validator
     */
    event R1AddValidator(address indexed validator);

    /**
     * @notice Event emitted when a k1 validator is added
     * @param validator address - Address of the added k1 validator
     */
    event K1AddValidator(address indexed validator);

    /**
     * @notice Event emitted when a modular validator is added
     * @param validator address - Address of the added modular validator
     */
    event AddModuleValidator(address indexed validator);

    /**
     * @notice Event emitted when a r1 validator is removed
     * @param validator address - Address of the removed r1 validator
     */
    event R1RemoveValidator(address indexed validator);

    /**
     * @notice Event emitted when a k1 validator is removed
     * @param validator address - Address of the removed k1 validator
     */
    event K1RemoveValidator(address indexed validator);

    /**
     * @notice Event emitted when a modular validator is removed
     * @param validator address - Address of the removed modular validator
     */
    event RemoveModuleValidator(address indexed validator);

    /**
     * @notice Adds a validator to the list of r1 validators
     * @dev Can only be called by self or a whitelisted module
     * @param validator address - Address of the r1 validator to add
     */
    function r1AddValidator(address validator) external;

    /**
     * @notice Adds a validator to the list of modular validators
     * @dev Can only be called by self or a whitelisted module
     * @param validator address - Address of the generic validator to add
     * @param accountValidationKey bytes - data for the validator to use to validate the account
     */
    function addModuleValidator(address validator, bytes memory accountValidationKey) external;

    /**
     * @notice Adds a validator to the list of k1 validators
     * @dev Can only be called by self or a whitelisted module
     * @param validator address - Address of the k1 validator to add
     */
    function k1AddValidator(address validator) external;

    /**
     * @notice Removes a validator from the list of r1 validators
     * @dev Can only be called by self or a whitelisted module
     * @dev Can not remove the last validator
     * @param validator address - Address of the validator to remove
     */
    function r1RemoveValidator(address validator) external;

    /**
     * @notice Removes a validator from the list of k1 validators
     * @dev Can only be called by self or a whitelisted module
     * @param validator address - Address of the validator to remove
     */
    function k1RemoveValidator(address validator) external;

    /**
     * @notice Removes a validator from the list of modular validators
     * @dev Can only be called by self or a whitelisted module
     * @param validator address - Address of the validator to remove
     */
    function removeModuleValidator(address validator) external;

    /**
     * @notice Checks if an address is in the r1 validator list
     * @param validator address -Address of the validator to check
     * @return True if the address is a validator, false otherwise
     */
    function r1IsValidator(address validator) external view returns (bool);

    /**
     * @notice Checks if an address is in the k1 validator list
     * @param validator address - Address of the validator to check
     * @return True if the address is a validator, false otherwise
     */
    function k1IsValidator(address validator) external view returns (bool);

    /**
     * @notice Checks if an address is in the modular validator list
     * @param validator address - Address of the validator to check
     * @return True if the address is a validator, false otherwise
     */
    function isModuleValidator(address validator) external view returns (bool);

    /**
     * @notice Returns the list of r1 validators
     * @return validatorList address[] memory - Array of r1 validator addresses
     */
    function r1ListValidators() external view returns (address[] memory validatorList);

    /**
     * @notice Returns the list of k1 validators
     * @return validatorList address[] memory - Array of k1 validator addresses
     */
    function k1ListValidators() external view returns (address[] memory validatorList);


    /**
     * @notice Returns the list of modular validators
     * @return validatorList address[] memory - Array of modular validator addresses
     */
    function listModuleValidators() external view returns (address[] memory validatorList);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.7.6;

library ExcessivelySafeCall {
    uint256 constant LOW_28_MASK =
        0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;

    /// @notice Use when you _really_ really _really_ don't trust the called
    /// contract. This prevents the called contract from causing reversion of
    /// the caller in as many ways as we can.
    /// @dev The main difference between this and a solidity low-level call is
    /// that we limit the number of bytes that the callee can cause to be
    /// copied to caller memory. This prevents stupid things like malicious
    /// contracts returning 10,000,000 bytes causing a local OOG when copying
    /// to memory.
    /// @param _target The address to call
    /// @param _gas The amount of gas to forward to the remote contract
    /// @param _value The value in wei to send to the remote contract
    /// @param _maxCopy The maximum number of bytes of returndata to copy
    /// to memory.
    /// @param _calldata The data to send to the remote contract
    /// @return success and returndata, as `.call()`. Returndata is capped to
    /// `_maxCopy` bytes.
    function excessivelySafeCall(
        address _target,
        uint256 _gas,
        uint256 _value,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returnData = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid memcopying a very large returndata
        // returned by a malicious contract
        assembly {
            _success := call(
                _gas, // gas
                _target, // recipient
                _value, // ether value
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returnData, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
        }
        return (_success, _returnData);
    }

    /// @notice Use when you _really_ really _really_ don't trust the called
    /// contract. This prevents the called contract from causing reversion of
    /// the caller in as many ways as we can.
    /// @dev The main difference between this and a solidity low-level call is
    /// that we limit the number of bytes that the callee can cause to be
    /// copied to caller memory. This prevents stupid things like malicious
    /// contracts returning 10,000,000 bytes causing a local OOG when copying
    /// to memory.
    /// @param _target The address to call
    /// @param _gas The amount of gas to forward to the remote contract
    /// @param _maxCopy The maximum number of bytes of returndata to copy
    /// to memory.
    /// @param _calldata The data to send to the remote contract
    /// @return success and returndata, as `.call()`. Returndata is capped to
    /// `_maxCopy` bytes.
    function excessivelySafeStaticCall(
        address _target,
        uint256 _gas,
        uint16 _maxCopy,
        bytes memory _calldata
    ) internal view returns (bool, bytes memory) {
        // set up for assembly call
        uint256 _toCopy;
        bool _success;
        bytes memory _returnData = new bytes(_maxCopy);
        // dispatch message to recipient
        // by assembly calling "handle" function
        // we call via assembly to avoid memcopying a very large returndata
        // returned by a malicious contract
        assembly {
            _success := staticcall(
                _gas, // gas
                _target, // recipient
                add(_calldata, 0x20), // inloc
                mload(_calldata), // inlen
                0, // outloc
                0 // outlen
            )
            // limit our copy to 256 bytes
            _toCopy := returndatasize()
            if gt(_toCopy, _maxCopy) {
                _toCopy := _maxCopy
            }
            // Store the length of the copied bytes
            mstore(_returnData, _toCopy)
            // copy the bytes from returndata[0:_toCopy]
            returndatacopy(add(_returnData, 0x20), 0, _toCopy)
        }
        return (_success, _returnData);
    }

    /**
     * @notice Swaps function selectors in encoded contract calls
     * @dev Allows reuse of encoded calldata for functions with identical
     * argument types but different names. It simply swaps out the first 4 bytes
     * for the new selector. This function modifies memory in place, and should
     * only be used with caution.
     * @param _newSelector The new 4-byte selector
     * @param _buf The encoded contract args
     */
    function swapSelector(bytes4 _newSelector, bytes memory _buf)
        internal
        pure
    {
        require(_buf.length >= 4);
        uint256 _mask = LOW_28_MASK;
        assembly {
            // load the first word of
            let _word := mload(add(_buf, 0x20))
            // mask out the top 4 bytes
            // /x
            _word := and(_word, _mask)
            _word := or(_newSelector, _word)
            mstore(add(_buf, 0x20), _word)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC777Recipient.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-777 Tokens Recipient standard as defined in the ERC.
 *
 * Accounts can be notified of {IERC777} tokens being sent to them by having a
 * contract implement this interface (contract holders can be their own
 * implementer) and registering it on the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC-1820 global registry].
 *
 * See {IERC1820Registry} and {IERC1820Implementer}.
 */
interface IERC777Recipient {
    /**
     * @dev Called by an {IERC777} token contract whenever tokens are being
     * moved or created into a registered account (`to`). The type of operation
     * is conveyed by `from` being the zero address or not.
     *
     * This call occurs _after_ the token contract's state is updated, so
     * {IERC777-balanceOf}, etc., can be used to query the post-operation state.
     *
     * This function may revert to prevent the operation from being executed.
     */
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Receiver.sol)

pragma solidity ^0.8.20;

import {IERC721Receiver} from "../token/ERC721/IERC721Receiver.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the ERC-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface.
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC-165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC-165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     */
    function getSupportedInterfaces(
        address account,
        bytes4[] memory interfaceIds
    ) internal view returns (bool[] memory) {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC-165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC-165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC-165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC-165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     *
     * Some precompiled contracts will falsely indicate support for a given interface, so caution
     * should be exercised when using this function.
     *
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeCall(IERC165.supportsInterface, (interfaceId));

        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }

        return success && returnSize >= 0x20 && returnValue > 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

import {IERC1155Receiver} from "../token/ERC1155/IERC1155Receiver.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 */
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @custom:storage-location erc7201:openzeppelin.storage.EIP712
    struct EIP712Storage {
        /// @custom:oz-renamed-from _HASHED_NAME
        bytes32 _hashedName;
        /// @custom:oz-renamed-from _HASHED_VERSION
        bytes32 _hashedVersion;

        string _name;
        string _version;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;

    function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
        assembly {
            $.slot := EIP712StorageLocation
        }
    }

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
        __EIP712_init_unchained(name, version);
    }

    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
        EIP712Storage storage $ = _getEIP712Storage();
        $._name = name;
        $._version = version;

        // Reset prior values in storage if upgrading
        $._hashedName = 0;
        $._hashedVersion = 0;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        EIP712Storage storage $ = _getEIP712Storage();
        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
        // and the EIP712 domain is not reliable, as it will be missing name and version.
        require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");

        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Name() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._name;
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Version() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._version;
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
     */
    function _EIP712NameHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory name = _EIP712Name();
        if (bytes(name).length > 0) {
            return keccak256(bytes(name));
        } else {
            // If the name is empty, the contract may have been upgraded without initializing the new storage.
            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
            bytes32 hashedName = $._hashedName;
            if (hashedName != 0) {
                return hashedName;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
     */
    function _EIP712VersionHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory version = _EIP712Version();
        if (bytes(version).length > 0) {
            return keccak256(bytes(version));
        } else {
            // If the version is empty, the contract may have been upgraded without initializing the new storage.
            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
            bytes32 hashedVersion = $._hashedVersion;
            if (hashedVersion != 0) {
                return hashedVersion;
            } else {
                return keccak256("");
            }
        }
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {BOOTLOADER_FORMAL_ADDRESS} from '@matterlabs/zksync-contracts/l2/system-contracts/Constants.sol';
import {Errors} from '../libraries/Errors.sol';

/**
 * @title BootloaderAuth
 * @notice Abstract contract that allows only calls from bootloader
 * @author https://getclave.io
 */
abstract contract BootloaderAuth {
    modifier onlyBootloader() {
        if (msg.sender != BOOTLOADER_FORMAL_ADDRESS) {
            revert Errors.NOT_FROM_BOOTLOADER();
        }
        _;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';

/**
 * @title ModuleAuth
 * @notice Abstract contract that allows only calls from modules
 * @author https://getclave.io
 */
abstract contract ModuleAuth {
    function _isModule(address addr) internal view virtual returns (bool);

    modifier onlyModule() {
        if (!_isModule(msg.sender)) {
            revert Errors.NOT_FROM_MODULE();
        }
        _;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {Errors} from '../libraries/Errors.sol';

/**
 * @title HookAuth
 * @notice Abstract contract that allows only calls from hooks
 * @author https://getclave.io
 */
abstract contract HookAuth {
    function _isHook(address addr) internal view virtual returns (bool);

    modifier onlyHook() {
        if (!_isHook(msg.sender)) {
            revert Errors.NOT_FROM_HOOK();
        }
        _;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;

import {AGWStorage} from '../libraries/AGWStorage.sol';
import {BytesLinkedList, AddressLinkedList} from '../libraries/LinkedList.sol';
import {Errors} from '../libraries/Errors.sol';
import {Auth} from '../auth/Auth.sol';
import {IAGWAccount} from '../interfaces/IAGWAccount.sol';
import {IOwnerManager} from '../interfaces/IOwnerManager.sol';

/**
 * @title Manager contract for owners
 * @notice Abstract contract for managing the owners of the account
 * @dev R1 Owners are 64 byte secp256r1 public keys
 * @dev K1 Owners are secp256k1 addresses
 * @dev Owners are stored in a linked list
 * @author https://getclave.io
 */
abstract contract OwnerManager is IOwnerManager, Auth {
    // Helper library for bytes to bytes mappings
    using BytesLinkedList for mapping(bytes => bytes);
    // Helper library for address to address mappings
    using AddressLinkedList for mapping(address => address);

    /// @inheritdoc IOwnerManager
    function r1AddOwner(bytes calldata pubKey) external override onlySelfOrModule {
        _r1AddOwner(pubKey);
    }

    /// @inheritdoc IOwnerManager
    function k1AddOwner(address addr) external override onlySelfOrModule {
        _k1AddOwner(addr);
    }

    /// @inheritdoc IOwnerManager
    function r1RemoveOwner(bytes calldata pubKey) external override onlySelfOrModule {
        _r1RemoveOwner(pubKey);
    }

    /// @inheritdoc IOwnerManager
    function k1RemoveOwner(address addr) external override onlySelfOrModule {
        _k1RemoveOwner(addr);
    }

    /// @inheritdoc IOwnerManager
    function resetOwners(bytes calldata pubKey) external override onlySelfOrModule {
        _r1ClearOwners();
        _k1ClearOwners();

        emit ResetOwners();

        _r1AddOwner(pubKey);
    }

    /// @inheritdoc IOwnerManager
    function r1IsOwner(bytes calldata pubKey) external view override returns (bool) {
        return _r1IsOwner(pubKey);
    }

    /// @inheritdoc IOwnerManager
    function k1IsOwner(address addr) external view override returns (bool) {
        return _k1IsOwner(addr);
    }

    /// @inheritdoc IOwnerManager
    function r1ListOwners() external view override returns (bytes[] memory r1OwnerList) {
        r1OwnerList = _r1OwnersLinkedList().list();
    }

    /// @inheritdoc IOwnerManager
    function k1ListOwners() external view override returns (address[] memory k1OwnerList) {
        k1OwnerList = _k1OwnersLinkedList().list();
    }

    function _r1AddOwner(bytes calldata pubKey) internal {
        if (pubKey.length != 64) {
            revert Errors.INVALID_PUBKEY_LENGTH();
        }

        _r1OwnersLinkedList().add(pubKey);

        emit R1AddOwner(pubKey);
    }

    function _k1AddOwner(address addr) internal {
        _k1OwnersLinkedList().add(addr);

        emit K1AddOwner(addr);
    }

    function _r1RemoveOwner(bytes calldata pubKey) internal {
        _r1OwnersLinkedList().remove(pubKey);

        emit R1RemoveOwner(pubKey);
    }

    function _k1RemoveOwner(address addr) internal {
        _k1OwnersLinkedList().remove(addr);

        // The wallet should have at least one owner
        if (_k1OwnersLinkedList().isEmpty()) {
            revert Errors.EMPTY_OWNERS();
        }

        emit K1RemoveOwner(addr);
    }

    function _r1IsOwner(bytes calldata pubKey) internal view returns (bool) {
        return _r1OwnersLinkedList().exists(pubKey);
    }

    function _k1IsOwner(address addr) internal view returns (bool) {
        return _k1OwnersLinkedList().exists(addr);
    }

    function _r1OwnersLinkedList()
        internal
        view
        returns (mapping(bytes => bytes) storage r1Owners)
    {
        r1Owners = AGWStorage.layout().r1Owners;
    }

    function _k1OwnersLinkedList()
        internal
        view
        returns (mapping(address => address) storage k1Owners)
    {
        k1Owners = AGWStorage.layout().k1Owners;
    }

    function _r1ClearOwners() private {
        _r1OwnersLinkedList().clear();
    }

    function _k1ClearOwners() private {
        _k1OwnersLinkedList().clear();
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";

import { Auth } from "../auth/Auth.sol";
import { Errors } from "../libraries/Errors.sol";
import {AGWStorage} from '../libraries/AGWStorage.sol';
import { AddressLinkedList } from "../libraries/LinkedList.sol";
import { IR1Validator, IK1Validator } from "../interfaces/IValidator.sol";
import { IValidatorManager } from "../interfaces/IValidatorManager.sol";
import { IModuleValidator } from "../interfaces/IModuleValidator.sol";

/**
 * @title Manager contract for validators
 * @notice Abstract contract for managing the validators of the account
 * @dev Validators are stored in a linked list
 * @author https://getclave.io
 */
abstract contract ValidatorManager is IValidatorManager, Auth {
    // Helper library for address to address mappings
    using AddressLinkedList for mapping(address => address);
    // Interface helper library
    using ERC165Checker for address;

    /// @inheritdoc IValidatorManager
    function r1AddValidator(address validator) external override onlySelfOrModule {
        _r1AddValidator(validator);
    }

    function addModuleValidator(address validator, bytes memory initialAccountValidationKey) external onlySelfOrModule {
        _addModuleValidator(validator, initialAccountValidationKey);
    }

    /// @inheritdoc IValidatorManager
    function k1AddValidator(address validator) external override onlySelfOrModule {
        _k1AddValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function r1RemoveValidator(address validator) external override onlySelfOrModule {
        _r1RemoveValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function k1RemoveValidator(address validator) external override onlySelfOrModule {
        _k1RemoveValidator(validator);
    }

    ///@inheritdoc IValidatorManager
    function removeModuleValidator(address validator) external onlySelfOrModule {
        _removeModuleValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function r1IsValidator(address validator) external view override returns (bool) {
        return _r1IsValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function k1IsValidator(address validator) external view override returns (bool) {
        return _k1IsValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function isModuleValidator(address validator) external view override returns (bool) {
        return _isModuleValidator(validator);
    }

    /// @inheritdoc IValidatorManager
    function r1ListValidators() external view override returns (address[] memory validatorList) {
        validatorList = _r1ValidatorsLinkedList().list();
    }

    /// @inheritdoc IValidatorManager
    function k1ListValidators() external view override returns (address[] memory validatorList) {
        validatorList = _k1ValidatorsLinkedList().list();
    }

    /// @inheritdoc IValidatorManager
    function listModuleValidators() external view override returns (address[] memory validatorList) {
        validatorList = _moduleValidatorsLinkedList().list();
    }

    function _r1AddValidator(address validator) internal {
        if (!_supportsR1(validator)) {
            revert Errors.VALIDATOR_ERC165_FAIL();
        }

        _r1ValidatorsLinkedList().add(validator);

        emit R1AddValidator(validator);
    }

    function _addModuleValidator(address validator, bytes memory accountValidationKey) internal {
        if (!_supportsModuleValidator(validator)) {
          revert Errors.VALIDATOR_ERC165_FAIL();
        }

        _moduleValidatorsLinkedList().add(validator);
        IModuleValidator(validator).addValidationKey(accountValidationKey);

        emit AddModuleValidator(validator);
    }

    function _k1AddValidator(address validator) internal {
        if (!_supportsK1(validator)) {
            revert Errors.VALIDATOR_ERC165_FAIL();
        }

        _k1ValidatorsLinkedList().add(validator);

        emit K1AddValidator(validator);
    }

    function _r1RemoveValidator(address validator) internal {
        _r1ValidatorsLinkedList().remove(validator);

        emit R1RemoveValidator(validator);
    }

    function _k1RemoveValidator(address validator) internal {
        _k1ValidatorsLinkedList().remove(validator);

        // At least one validator must be present
        if (_k1ValidatorsLinkedList().isEmpty()) {
            revert Errors.EMPTY_VALIDATORS();
        }

        emit K1RemoveValidator(validator);
    }

    function _removeModuleValidator(address validator) internal {
        _moduleValidatorsLinkedList().remove(validator);

        emit RemoveModuleValidator(validator);
    }

    function _r1IsValidator(address validator) internal view returns (bool) {
        return _r1ValidatorsLinkedList().exists(validator);
    }

    function _isModuleValidator(address validator) internal view returns (bool) {
        return _moduleValidatorsLinkedList().exists(validator);
    }

    function _k1IsValidator(address validator) internal view returns (bool) {
        return _k1ValidatorsLinkedList().exists(validator);
    }

    function _supportsR1(address validator) internal view returns (bool) {
        return validator.supportsInterface(type(IR1Validator).interfaceId);
    }

    function _supportsK1(address validator) internal view returns (bool) {
        return validator.supportsInterface(type(IK1Validator).interfaceId);
    }

    function _supportsModuleValidator(address validator) internal view returns (bool) {
        return validator.supportsInterface(type(IModuleValidator).interfaceId);
    }

    function _r1ValidatorsLinkedList()
        private
        view
        returns (mapping(address => address) storage r1Validators)
    {
        r1Validators = AGWStorage.layout().r1Validators;
    }

    function _moduleValidatorsLinkedList()
        private
        view
        returns (mapping(address => address) storage moduleValidators)
    {
        moduleValidators = AGWStorage.layout().moduleValidators;
    }

    function _k1ValidatorsLinkedList()
        private
        view
        returns (mapping(address => address) storage k1Validators)
    {
        k1Validators = AGWStorage.layout().k1Validators;
    }
}

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.24;

import {OperationType} from './IValidator.sol';

/**
 * @title Modular validator interface for native AA
 * @dev Add signature to module or validate existing signatures for acccount
 */
interface IModuleValidator {
  function handleValidation(OperationType operationType, bytes32 signedHash, bytes memory signature) external view returns (bool);

  function addValidationKey(bytes memory key) external returns (bool);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IAccountCodeStorage {
    function storeAccountConstructingCodeHash(address _address, bytes32 _hash) external;

    function storeAccountConstructedCodeHash(address _address, bytes32 _hash) external;

    function markAccountCodeHashAsConstructed(address _address) external;

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

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

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @author Matter Labs
 * @dev Interface of the nonce holder contract -- a contract used by the system to ensure
 * that there is always a unique identifier for a transaction with a particular account (we call it nonce).
 * In other words, the pair of (address, nonce) should always be unique.
 * @dev Custom accounts should use methods of this contract to store nonces or other possible unique identifiers
 * for the transaction.
 */
interface INonceHolder {
    event ValueSetUnderNonce(address indexed accountAddress, uint256 indexed key, uint256 value);

    /// @dev Returns the current minimal nonce for account.
    function getMinNonce(address _address) external view returns (uint256);

    /// @dev Returns the raw version of the current minimal nonce
    /// (equal to minNonce + 2^128 * deployment nonce).
    function getRawNonce(address _address) external view returns (uint256);

    /// @dev Increases the minimal nonce for the msg.sender.
    function increaseMinNonce(uint256 _value) external returns (uint256);

    /// @dev Sets the nonce value `key` as used.
    function setValueUnderNonce(uint256 _key, uint256 _value) external;

    /// @dev Gets the value stored inside a custom nonce.
    function getValueUnderNonce(uint256 _key) external view returns (uint256);

    /// @dev A convenience method to increment the minimal nonce if it is equal
    /// to the `_expectedNonce`.
    function incrementMinNonceIfEquals(uint256 _expectedNonce) external;

    /// @dev Returns the deployment nonce for the accounts used for CREATE opcode.
    function getDeploymentNonce(address _address) external view returns (uint256);

    /// @dev Increments the deployment nonce for the account and returns the previous one.
    function incrementDeploymentNonce(address _address) external returns (uint256);

    /// @dev Determines whether a certain nonce has been already used for an account.
    function validateNonceUsage(address _address, uint256 _key, bool _shouldBeUsed) external view;

    /// @dev Returns whether a nonce has been used for an account.
    function isNonceUsed(address _address, uint256 _nonce) external view returns (bool);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./interfaces/IBootloaderUtilities.sol";
import "./libraries/TransactionHelper.sol";
import "./libraries/RLPEncoder.sol";
import "./libraries/EfficientCall.sol";

/**
 * @author Matter Labs
 * @notice A contract that provides some utility methods for the bootloader
 * that is very hard to write in Yul.
 */
contract BootloaderUtilities is IBootloaderUtilities {
    using TransactionHelper for *;

    /// @notice Calculates the canonical transaction hash and the recommended transaction hash.
    /// @param _transaction The transaction.
    /// @return txHash and signedTxHash of the transaction, i.e. the transaction hash to be used in the explorer and commits to all
    /// the fields of the transaction and the recommended hash to be signed for this transaction.
    /// @dev txHash must be unique for all transactions.
    function getTransactionHashes(
        Transaction calldata _transaction
    ) external view override returns (bytes32 txHash, bytes32 signedTxHash) {
        signedTxHash = _transaction.encodeHash();
        if (_transaction.txType == EIP_712_TX_TYPE) {
            txHash = keccak256(bytes.concat(signedTxHash, EfficientCall.keccak(_transaction.signature)));
        } else if (_transaction.txType == LEGACY_TX_TYPE) {
            txHash = encodeLegacyTransactionHash(_transaction);
        } else if (_transaction.txType == EIP_1559_TX_TYPE) {
            txHash = encodeEIP1559TransactionHash(_transaction);
        } else if (_transaction.txType == EIP_2930_TX_TYPE) {
            txHash = encodeEIP2930TransactionHash(_transaction);
        } else {
            revert("Unsupported tx type");
        }
    }

    /// @notice Calculates the hash for a legacy transaction.
    /// @param _transaction The legacy transaction.
    /// @return txHash The hash of the transaction.
    function encodeLegacyTransactionHash(Transaction calldata _transaction) internal view returns (bytes32 txHash) {
        // Hash of legacy transactions are encoded as one of the:
        // - RLP(nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0)
        // - RLP(nonce, gasPrice, gasLimit, to, value, data)
        //
        // In this RLP encoding, only the first one above list appears, so we encode each element
        // inside list and then concatenate the length of all elements with them.

        bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
        // Encode `gasPrice` and `gasLimit` together to prevent "stack too deep error".
        bytes memory encodedGasParam;
        {
            bytes memory encodedGasPrice = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            encodedGasParam = bytes.concat(encodedGasPrice, encodedGasLimit);
        }

        bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
        bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        bytes memory rEncoded;
        {
            uint256 rInt = uint256(bytes32(_transaction.signature[0:32]));
            rEncoded = RLPEncoder.encodeUint256(rInt);
        }
        bytes memory sEncoded;
        {
            uint256 sInt = uint256(bytes32(_transaction.signature[32:64]));
            sEncoded = RLPEncoder.encodeUint256(sInt);
        }
        bytes memory vEncoded;
        {
            uint256 vInt = uint256(uint8(_transaction.signature[64]));
            require(vInt == 27 || vInt == 28, "Invalid v value");

            // If the `chainId` is specified in the transaction, then the `v` value is encoded as
            // `35 + y + 2 * chainId == vInt + 8 + 2 * chainId`, where y - parity bit (see EIP-155).
            if (_transaction.reserved[0] != 0) {
                vInt += 8 + block.chainid * 2;
            }

            vEncoded = RLPEncoder.encodeUint256(vInt);
        }

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedNonce.length +
                encodedGasParam.length +
                encodedTo.length +
                encodedValue.length +
                encodedDataLength.length +
                _transaction.data.length +
                rEncoded.length +
                sEncoded.length +
                vEncoded.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    encodedListLength,
                    encodedNonce,
                    encodedGasParam,
                    encodedTo,
                    encodedValue,
                    encodedDataLength,
                    _transaction.data,
                    vEncoded,
                    rEncoded,
                    sEncoded
                )
            );
    }

    /// @notice Calculates the hash for an EIP2930 transaction.
    /// @param _transaction The EIP2930 transaction.
    /// @return txHash The hash of the transaction.
    function encodeEIP2930TransactionHash(Transaction calldata _transaction) internal view returns (bytes32) {
        // Encode all fixed-length params to avoid "stack too deep error"
        bytes memory encodedFixedLengthParams;
        {
            bytes memory encodedChainId = RLPEncoder.encodeUint256(block.chainid);
            bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
            bytes memory encodedGasPrice = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
            bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
            encodedFixedLengthParams = bytes.concat(
                encodedChainId,
                encodedNonce,
                encodedGasPrice,
                encodedGasLimit,
                encodedTo,
                encodedValue
            );
        }

        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        // On zkSync, access lists are always zero length (at least for now).
        bytes memory encodedAccessListLength = RLPEncoder.encodeListLen(0);

        bytes memory rEncoded;
        {
            uint256 rInt = uint256(bytes32(_transaction.signature[0:32]));
            rEncoded = RLPEncoder.encodeUint256(rInt);
        }
        bytes memory sEncoded;
        {
            uint256 sInt = uint256(bytes32(_transaction.signature[32:64]));
            sEncoded = RLPEncoder.encodeUint256(sInt);
        }
        bytes memory vEncoded;
        {
            uint256 vInt = uint256(uint8(_transaction.signature[64]));
            require(vInt == 27 || vInt == 28, "Invalid v value");

            vEncoded = RLPEncoder.encodeUint256(vInt - 27);
        }

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedFixedLengthParams.length +
                encodedDataLength.length +
                _transaction.data.length +
                encodedAccessListLength.length +
                rEncoded.length +
                sEncoded.length +
                vEncoded.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    "\x01",
                    encodedListLength,
                    encodedFixedLengthParams,
                    encodedDataLength,
                    _transaction.data,
                    encodedAccessListLength,
                    vEncoded,
                    rEncoded,
                    sEncoded
                )
            );
    }

    /// @notice Calculates the hash for an EIP1559 transaction.
    /// @param _transaction The legacy transaction.
    /// @return txHash The hash of the transaction.
    function encodeEIP1559TransactionHash(Transaction calldata _transaction) internal view returns (bytes32) {
        // The formula for hash of EIP1559 transaction in the original proposal:
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md

        // Encode all fixed-length params to avoid "stack too deep error"
        bytes memory encodedFixedLengthParams;
        {
            bytes memory encodedChainId = RLPEncoder.encodeUint256(block.chainid);
            bytes memory encodedNonce = RLPEncoder.encodeUint256(_transaction.nonce);
            bytes memory encodedMaxPriorityFeePerGas = RLPEncoder.encodeUint256(_transaction.maxPriorityFeePerGas);
            bytes memory encodedMaxFeePerGas = RLPEncoder.encodeUint256(_transaction.maxFeePerGas);
            bytes memory encodedGasLimit = RLPEncoder.encodeUint256(_transaction.gasLimit);
            bytes memory encodedTo = RLPEncoder.encodeAddress(address(uint160(_transaction.to)));
            bytes memory encodedValue = RLPEncoder.encodeUint256(_transaction.value);
            encodedFixedLengthParams = bytes.concat(
                encodedChainId,
                encodedNonce,
                encodedMaxPriorityFeePerGas,
                encodedMaxFeePerGas,
                encodedGasLimit,
                encodedTo,
                encodedValue
            );
        }

        // Encode only the length of the transaction data, and not the data itself,
        // so as not to copy to memory a potentially huge transaction data twice.
        bytes memory encodedDataLength;
        {
            // Safe cast, because the length of the transaction data can't be so large.
            uint64 txDataLen = uint64(_transaction.data.length);
            if (txDataLen != 1) {
                // If the length is not equal to one, then only using the length can it be encoded definitely.
                encodedDataLength = RLPEncoder.encodeNonSingleBytesLen(txDataLen);
            } else if (_transaction.data[0] >= 0x80) {
                // If input is a byte in [0x80, 0xff] range, RLP encoding will concatenates 0x81 with the byte.
                encodedDataLength = hex"81";
            }
            // Otherwise the length is not encoded at all.
        }

        // On zkSync, access lists are always zero length (at least for now).
        bytes memory encodedAccessListLength = RLPEncoder.encodeListLen(0);

        bytes memory rEncoded;
        {
            uint256 rInt = uint256(bytes32(_transaction.signature[0:32]));
            rEncoded = RLPEncoder.encodeUint256(rInt);
        }
        bytes memory sEncoded;
        {
            uint256 sInt = uint256(bytes32(_transaction.signature[32:64]));
            sEncoded = RLPEncoder.encodeUint256(sInt);
        }
        bytes memory vEncoded;
        {
            uint256 vInt = uint256(uint8(_transaction.signature[64]));
            require(vInt == 27 || vInt == 28, "Invalid v value");

            vEncoded = RLPEncoder.encodeUint256(vInt - 27);
        }

        bytes memory encodedListLength;
        unchecked {
            uint256 listLength = encodedFixedLengthParams.length +
                encodedDataLength.length +
                _transaction.data.length +
                encodedAccessListLength.length +
                rEncoded.length +
                sEncoded.length +
                vEncoded.length;

            // Safe cast, because the length of the list can't be so large.
            encodedListLength = RLPEncoder.encodeListLen(uint64(listLength));
        }

        return
            keccak256(
                bytes.concat(
                    "\x02",
                    encodedListLength,
                    encodedFixedLengthParams,
                    encodedDataLength,
                    _transaction.data,
                    encodedAccessListLength,
                    vEncoded,
                    rEncoded,
                    sEncoded
                )
            );
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IKnownCodesStorage {
    event MarkedAsKnown(bytes32 indexed bytecodeHash, bool indexed sendBytecodeToL1);

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

    function markBytecodeAsPublished(
        bytes32 _bytecodeHash,
        bytes32 _l1PreimageHash,
        uint256 _l1PreimageBytesLen
    ) external;

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

struct ImmutableData {
    uint256 index;
    bytes32 value;
}

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

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IContractDeployer {
    /// @notice Defines the version of the account abstraction protocol
    /// that a contract claims to follow.
    /// - `None` means that the account is just a contract and it should never be interacted
    /// with as a custom account
    /// - `Version1` means that the account follows the first version of the account abstraction protocol
    enum AccountAbstractionVersion {
        None,
        Version1
    }

    /// @notice Defines the nonce ordering used by the account
    /// - `Sequential` means that it is expected that the nonces are monotonic and increment by 1
    /// at a time (the same as EOAs).
    /// - `Arbitrary` means that the nonces for the accounts can be arbitrary. The operator
    /// should serve the transactions from such an account on a first-come-first-serve basis.
    /// @dev This ordering is more of a suggestion to the operator on how the AA expects its transactions
    /// to be processed and is not considered as a system invariant.
    enum AccountNonceOrdering {
        Sequential,
        Arbitrary
    }

    struct AccountInfo {
        AccountAbstractionVersion supportedAAVersion;
        AccountNonceOrdering nonceOrdering;
    }

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

    event AccountNonceOrderingUpdated(address indexed accountAddress, AccountNonceOrdering nonceOrdering);

    event AccountVersionUpdated(address indexed accountAddress, AccountAbstractionVersion aaVersion);

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

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

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

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

    /// @dev While the `_salt` parameter is not used anywhere here,
    /// it is still needed for consistency between `create` and
    /// `create2` functions (required by the compiler).
    function create(
        bytes32 _salt,
        bytes32 _bytecodeHash,
        bytes calldata _input
    ) external payable returns (address newAddress);

    /// @dev While `_salt` is never used here, we leave it here as a parameter
    /// for the consistency with the `create` function.
    function createAccount(
        bytes32 _salt,
        bytes32 _bytecodeHash,
        bytes calldata _input,
        AccountAbstractionVersion _aaVersion
    ) external payable returns (address newAddress);

    /// @notice Returns the information about a certain AA.
    function getAccountInfo(address _address) external view returns (AccountInfo memory info);

    /// @notice Can be called by an account to update its account version
    function updateAccountVersion(AccountAbstractionVersion _version) external;

    /// @notice Can be called by an account to update its nonce ordering
    function updateNonceOrdering(AccountNonceOrdering _nonceOrdering) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IL1Messenger {
    // Possibly in the future we will be able to track the messages sent to L1 with
    // some hooks in the VM. For now, it is much easier to track them with L2 events.
    event L1MessageSent(address indexed _sender, bytes32 indexed _hash, bytes _message);

    function sendToL1(bytes memory _message) external returns (bytes32);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @author Matter Labs
 * @notice Contract that stores some of the context variables, that may be either
 * block-scoped, tx-scoped or system-wide.
 */
interface ISystemContext {
    function chainId() external view returns (uint256);

    function origin() external view returns (address);

    function gasPrice() external view returns (uint256);

    function blockGasLimit() external view returns (uint256);

    function coinbase() external view returns (address);

    function difficulty() external view returns (uint256);

    function baseFee() external view returns (uint256);

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

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

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

    // Note, that for now, the implementation of the bootloader allows this variables to
    // be incremented multiple times inside a block, so it should not relied upon right now.
    function getBlockNumber() external view returns (uint256);

    function getBlockTimestamp() external view returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IEthToken {
    function balanceOf(uint256) external view returns (uint256);

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

    function totalSupply() external view returns (uint256);

    function name() external pure returns (string memory);

    function symbol() external pure returns (string memory);

    function decimals() external pure returns (uint8);

    function mint(address _account, uint256 _amount) external;

    function withdraw(address _l1Receiver) external payable;

    event Mint(address indexed account, uint256 amount);

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

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IBytecodeCompressor {
    function publishCompressedBytecode(
        bytes calldata _bytecode,
        bytes calldata _rawCompressedData
    ) external payable returns (bytes32 bytecodeHash);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @author Matter Labs
 * @dev The interface that is used for encoding/decoding of
 * different types of paymaster flows.
 * @notice This is NOT an interface to be implementated
 * by contracts. It is just used for encoding.
 */
interface IPaymasterFlow {
    function general(bytes calldata input) external;

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

library RLPEncoder {
    function encodeAddress(address _val) internal pure returns (bytes memory encoded) {
        // The size is equal to 20 bytes of the address itself + 1 for encoding bytes length in RLP.
        encoded = new bytes(0x15);

        bytes20 shiftedVal = bytes20(_val);
        assembly {
            // In the first byte we write the encoded length as 0x80 + 0x14 == 0x94.
            mstore(add(encoded, 0x20), 0x9400000000000000000000000000000000000000000000000000000000000000)
            // Write address data without stripping zeros.
            mstore(add(encoded, 0x21), shiftedVal)
        }
    }

    function encodeUint256(uint256 _val) internal pure returns (bytes memory encoded) {
        unchecked {
            if (_val < 128) {
                encoded = new bytes(1);
                // Handle zero as a non-value, since stripping zeroes results in an empty byte array
                encoded[0] = (_val == 0) ? bytes1(uint8(128)) : bytes1(uint8(_val));
            } else {
                uint256 hbs = _highestByteSet(_val);

                encoded = new bytes(hbs + 2);
                encoded[0] = bytes1(uint8(hbs + 0x81));

                uint256 lbs = 31 - hbs;
                uint256 shiftedVal = _val << (lbs * 8);

                assembly {
                    mstore(add(encoded, 0x21), shiftedVal)
                }
            }
        }
    }

    /// @notice Encodes the size of bytes in RLP format.
    /// @param _len The length of the bytes to encode. It has a `uint64` type since as larger values are not supported.
    /// NOTE: panics if the length is 1 since the length encoding is ambiguous in this case.
    function encodeNonSingleBytesLen(uint64 _len) internal pure returns (bytes memory) {
        assert(_len != 1);
        return _encodeLength(_len, 0x80);
    }

    /// @notice Encodes the size of list items in RLP format.
    /// @param _len The length of the bytes to encode. It has a `uint64` type since as larger values are not supported.
    function encodeListLen(uint64 _len) internal pure returns (bytes memory) {
        return _encodeLength(_len, 0xc0);
    }

    function _encodeLength(uint64 _len, uint256 _offset) private pure returns (bytes memory encoded) {
        unchecked {
            if (_len < 56) {
                encoded = new bytes(1);
                encoded[0] = bytes1(uint8(_len + _offset));
            } else {
                uint256 hbs = _highestByteSet(uint256(_len));

                encoded = new bytes(hbs + 2);
                encoded[0] = bytes1(uint8(_offset + hbs + 56));

                uint256 lbs = 31 - hbs;
                uint256 shiftedVal = uint256(_len) << (lbs * 8);

                assembly {
                    mstore(add(encoded, 0x21), shiftedVal)
                }
            }
        }
    }

    /// @notice Computes the index of the highest byte set in number.
    /// @notice Uses little endian ordering (The least significant byte has index `0`).
    /// NOTE: returns `0` for `0`
    function _highestByteSet(uint256 _number) private pure returns (uint256 hbs) {
        unchecked {
            if (_number > type(uint128).max) {
                _number >>= 128;
                hbs += 16;
            }
            if (_number > type(uint64).max) {
                _number >>= 64;
                hbs += 8;
            }
            if (_number > type(uint32).max) {
                _number >>= 32;
                hbs += 4;
            }
            if (_number > type(uint16).max) {
                _number >>= 16;
                hbs += 2;
            }
            if (_number > type(uint8).max) {
                hbs += 1;
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(
            token,
            abi.encodeWithSelector(token.transfer.selector, to, value)
        );
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(
            token,
            abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
        );
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(
            token,
            abi.encodeWithSelector(token.approve.selector, spender, value)
        );
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(
            token,
            abi.encodeWithSelector(
                token.approve.selector,
                spender,
                newAllowance
            )
        );
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(
                oldAllowance >= value,
                "SafeERC20: decreased allowance below zero"
            );
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(
                token,
                abi.encodeWithSelector(
                    token.approve.selector,
                    spender,
                    newAllowance
                )
            );
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(
            nonceAfter == nonceBefore + 1,
            "SafeERC20: permit did not succeed"
        );
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(
            data,
            "SafeERC20: low-level call failed"
        );
        if (returndata.length > 0) {
            // Return data is optional
            require(
                abi.decode(returndata, (bool)),
                "SafeERC20: ERC20 operation did not succeed"
            );
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

import {Strings} from "../Strings.sol";

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../libraries/TransactionHelper.sol";

interface IBootloaderUtilities {
    function getTransactionHashes(
        Transaction calldata _transaction
    ) external view returns (bytes32 txHash, bytes32 signedTxHash);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(
            address(this).balance >= amount,
            "Address: insufficient balance"
        );

        (bool success, ) = recipient.call{value: amount}("");
        require(
            success,
            "Address: unable to send value, recipient may have reverted"
        );
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data)
        internal
        returns (bytes memory)
    {
        return
            functionCallWithValue(
                target,
                data,
                0,
                "Address: low-level call failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return
            functionCallWithValue(
                target,
                data,
                value,
                "Address: low-level call with value failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(
            address(this).balance >= value,
            "Address: insufficient balance for call"
        );
        (bool success, bytes memory returndata) = target.call{value: value}(
            data
        );
        return
            verifyCallResultFromTarget(
                target,
                success,
                returndata,
                errorMessage
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data)
        internal
        view
        returns (bytes memory)
    {
        return
            functionStaticCall(
                target,
                data,
                "Address: low-level static call failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return
            verifyCallResultFromTarget(
                target,
                success,
                returndata,
                errorMessage
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data)
        internal
        returns (bytes memory)
    {
        return
            functionDelegateCall(
                target,
                data,
                "Address: low-level delegate call failed"
            );
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return
            verifyCallResultFromTarget(
                target,
                success,
                returndata,
                errorMessage
            );
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage)
        private
        pure
    {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

Please enter a contract address above to load the contract details and source code.

Context size (optional):