{"file_path":"src/mainnet-bridge/L1BlastBridge.sol","creation_status":"success","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { StandardBridge } from \"src/universal/StandardBridge.sol\";\nimport { L2BlastBridge } from \"src/mainnet-bridge/L2BlastBridge.sol\";\nimport { ISemver } from \"src/universal/ISemver.sol\";\nimport { CrossDomainMessenger } from \"src/universal/CrossDomainMessenger.sol\";\nimport { OptimismPortal } from \"src/L1/OptimismPortal.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\nimport { USDYieldManager } from \"src/mainnet-bridge/USDYieldManager.sol\";\nimport { ETHYieldManager } from \"src/mainnet-bridge/ETHYieldManager.sol\";\nimport { USDB } from \"src/L2/USDB.sol\";\nimport { USDConversions } from \"src/mainnet-bridge/USDConversions.sol\";\n\n/// @custom:proxied\n/// @title L1BlastBridge\n/// @notice The L1BlastBridge is responsible for transferring ETH and yield-bearing ERC20 tokens between L1 and L2.\n///\n///         The current implementation converts all deposited USD tokens to DAI before bridging them to L2 to mint USDB.\n///         Hence, the amount of USDB that is minted on L2 will be equal to the amount of DAI that is received on L1.\n///         This is done to simplify the yield management, as DSR is the only yield provider that is currently supported.\n///         When non-DAI USD tokens are deposited, the user is expected to provide the minimum amount of DAI that should\n///         be received (i.e. the minimum amount of USDB that should be minted on L2). This amount must be specified\n///         in the extraData field of the deposit transaction (uint256 minAmountInWad).\ncontract L1BlastBridge is StandardBridge, ISemver {\n    using SafeERC20 for IERC20;\n\n    struct YieldToken {\n        bool approved;\n        uint8 decimals;\n        address provider;\n        bool reportStakedBalance;\n    }\n\n    /// @notice Numerator for dynamic overhead added to the base gas for a message.\n    uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR = 64;\n\n    /// @notice Denominator for dynamic overhead added to the base gas for a message.\n    uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR = 63;\n\n    /// @notice Mapping of potential deposit tokens to whether they're\n    ///         approved as USD yield tokens and additional metadata.\n    mapping(address => YieldToken) public usdYieldTokens;\n\n    /// @notice Mapping of potential deposit tokens to whether they're\n    ///         approved as ETH yield tokens and additional metadata.\n    mapping(address => YieldToken) public ethYieldTokens;\n\n    /// @notice Address of the USD Yield Manager.\n    USDYieldManager public usdYieldManager;\n\n    /// @notice Address of the ETH Yield Manager.\n    ETHYieldManager public ethYieldManager;\n\n    /// @notice Address of the OptimismPortal.\n    OptimismPortal public portal;\n\n    /// @notice Semantic version.\n    /// @custom:semver 1.0.0\n    string public constant version = \"1.0.0\";\n\n    /// @custom:semver 1.0.0\n    /// @notice Constructs the L1BlastBridge contract.\n    constructor() StandardBridge(StandardBridge(payable(Predeploys.L2_BLAST_BRIDGE))) {\n        initialize({\n            _portal: OptimismPortal(payable(address(0))),\n            _messenger: CrossDomainMessenger(address(0)),\n            _usdYieldManager: USDYieldManager(payable(address(0))),\n            _ethYieldManager: ETHYieldManager(payable(address(0)))\n        });\n    }\n\n    /// @notice Initializer\n    /// @param _portal          Address of the OptimismPortal.\n    /// @param _messenger       Address of the L1CrossDomainMessenger.\n    /// @param _usdYieldManager Address of the USDYieldManager.\n    /// @param _ethYieldManager Address of the ETHYieldManager.\n    function initialize(\n        OptimismPortal _portal,\n        CrossDomainMessenger _messenger,\n        USDYieldManager _usdYieldManager,\n        ETHYieldManager _ethYieldManager\n    ) public initializer {\n        portal = _portal;\n        __StandardBridge_init(_messenger);\n        usdYieldManager = _usdYieldManager;\n        ethYieldManager = _ethYieldManager;\n    }\n\n    /// @notice Add/remove an approved USD yield token.\n    /// @param token               Address of token.\n    /// @param approved            Whether the token is an approved yield token.\n    /// @param decimals            Number of token decimals.\n    /// @param provider            Address of the yield provider for the token.\n    /// @param reportStakedBalance Whether a deposit needs to be reported to the yield provider.\n    function setUSDYieldToken(\n        address token,\n        bool approved,\n        uint8 decimals,\n        address provider,\n        bool reportStakedBalance\n    ) external {\n        require(msg.sender == usdYieldManager.owner(), \"L1BlastBridge: only USDYieldManager owner can call\");\n        usdYieldTokens[token] = YieldToken({\n            approved: approved,\n            decimals: decimals,\n            provider: provider,\n            reportStakedBalance: reportStakedBalance\n        });\n    }\n\n    /// @notice Add/remove an approved ETH yield token.\n    /// @param token               Address of token.\n    /// @param approved            Whether the token is an approved yield token.\n    /// @param decimals            Number of token decimals.\n    /// @param provider            Address of the yield provider for the token.\n    /// @param reportStakedBalance Whether a deposit needs to be reported to the yield provider.\n    function setETHYieldToken(\n        address token,\n        bool approved,\n        uint8 decimals,\n        address provider,\n        bool reportStakedBalance\n    ) external {\n        require(msg.sender == ethYieldManager.owner(), \"L1BlastBridge: only ETHYieldManager owner can call\");\n        require(token != address(0));\n        ethYieldTokens[token] = YieldToken({\n            approved: approved,\n            decimals: decimals,\n            provider: provider,\n            reportStakedBalance: reportStakedBalance\n        });\n    }\n\n    /// @notice Allows EOAs to bridge ETH by sending directly to the bridge.\n    receive() external payable override onlyEOA {\n        _initiateBridgeETH(msg.sender, msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, hex\"\");\n    }\n\n    /// Blast: This function is modified from StandardBridge to enable\n    /// discounted withdrawals on L1. The `msg.value` check is\n    /// less strict and `msg.value` is used instead of `_amount`\n    /// in the following steps.\n    /// @inheritdoc StandardBridge\n    function finalizeBridgeETH(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _extraData\n    )\n        public\n        payable\n        override\n        onlyOtherBridge\n    {\n        // Blast: Accept discounted `msg.value`\n        require(msg.value <= _amount, \"L1BlastBridge: amount sent exceeds amount required\");\n        require(_to != address(this), \"L1BlastBridge: cannot send to self\");\n        require(_to != address(messenger), \"L1BlastBridge: cannot send to messenger\");\n\n        // Emit the correct events. By default this will be _amount, but child\n        // contracts may override this function in order to emit legacy events as well.\n        // Blast: replace `_amount` with `msg.value`\n        _emitETHBridgeFinalized(_from, _to, msg.value, _extraData);\n\n        // Blast: replace `_amount` with `msg.value`\n        bool success = SafeCall.call(_to, gasleft(), msg.value, hex\"\");\n        require(success, \"L2BlastBridge: ETH transfer failed\");\n    }\n\n    /// @notice Finalizes an ERC20 bridge on this chain. Can only be triggered by the other\n    ///         BlastBridge contract on the remote chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _from        Address of the sender.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of the ERC20 being bridged.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function finalizeBridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _extraData\n    )\n        public\n        override\n        onlyOtherBridge\n    {\n        require(_to != address(this), \"StandardBridge: cannot send to self\");\n        require(_to != address(messenger), \"StandardBridge: cannot send to messenger\");\n\n        require(_localToken == usdYieldManager.TOKEN(), \"L1BlastBridge: unsupported local token\");\n        require(_remoteToken == Predeploys.USDB, \"L1BlastBridge: only USDB can be withdrawn through this bridge\");\n\n        // Emit the correct events. By default this will be ERC20BridgeFinalized, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);\n\n        usdYieldManager.requestWithdrawal(_to, _amount);\n    }\n\n    /// @notice Sends approved yield-bearing ERC20 tokens to a receiver's address on the other chain.\n    ///         Only USDB or ETH are accepted as _remoteToken. ETH-based tokens are sent to the\n    ///         Optimism Portal.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of local tokens to deposit.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction. For bridging yield-bearing USD tokens (except DAI),\n    ///                     the extra data should contain the minimum amount of tokens in WAD to be minted.\n    ///                     When the deposited USD tokens are converted to DAI, it ensures that the amount\n    ///                     of DAI received (and hence the amount of USDB minted) is at least the minimum\n    ///                     amount specified.\n    function _initiateBridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes memory _extraData\n    )\n        internal\n        override\n    {\n        YieldToken memory usdYieldToken = usdYieldTokens[_localToken];\n        YieldToken memory ethYieldToken = ethYieldTokens[_localToken];\n        if (usdYieldToken.approved) {\n            require(_remoteToken == Predeploys.USDB, \"L1BlastBridge: this token can only be bridged to USDB\");\n            IERC20(_localToken).safeTransferFrom(_from, address(usdYieldManager), _amount);\n\n            uint256 amountWad = USDConversions._convertDecimals(_amount, usdYieldToken.decimals, USDConversions.WAD_DECIMALS);\n            uint256 amountToMintWad = usdYieldManager.convert(_localToken, amountWad, _extraData);\n\n            // Update the yield provider with the staked deposit.\n            if (usdYieldToken.reportStakedBalance) {\n                require(usdYieldToken.provider != address(0));\n                usdYieldManager.recordStakedDeposit(usdYieldToken.provider, amountToMintWad);\n            }\n\n            // Emit the correct events. By default this will be ERC20BridgeInitiated, but child\n            // contracts may override this function in order to emit legacy events as well.\n            _emitERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, amountToMintWad, _extraData);\n\n            messenger.sendMessage(\n                Predeploys.L2_BLAST_BRIDGE,\n                abi.encodeWithSelector(\n                    StandardBridge.finalizeBridgeERC20.selector,\n                    Predeploys.USDB,\n                    usdYieldManager.TOKEN(),\n                    _from,\n                    _to,\n                    amountToMintWad,\n                    _extraData\n                ),\n                _minGasLimit\n            );\n\n        } else if (ethYieldToken.approved) {\n            require(_remoteToken == address(0), \"L1BlastBridge: this token can only be bridged to ETH\");\n            IERC20(_localToken).safeTransferFrom(_from, address(ethYieldManager), _amount);\n\n            // Update the yield provider with the staked deposit.\n            if (ethYieldToken.reportStakedBalance) {\n                require(ethYieldToken.provider != address(0));\n                ethYieldManager.recordStakedDeposit(ethYieldToken.provider, _amount);\n            }\n\n            uint256 amountWad = USDConversions._convertDecimals(_amount, ethYieldToken.decimals, USDConversions.WAD_DECIMALS);\n\n            // Emit the correct events. By default this will be ERC20BridgeInitiated, but child\n            // contracts may override this function in order to emit legacy events as well.\n            _emitERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, amountWad, _extraData);\n\n            // Message has to be sent to the OptimismPortal directly because we have to\n            // request the L2 message has value without sending ETH.\n            portal.depositTransaction(\n                Predeploys.L2_BLAST_BRIDGE,\n                amountWad,\n                baseGas(_minGasLimit),\n                false,\n                abi.encodeWithSelector(\n                    L2BlastBridge.finalizeBridgeETHDirect.selector,\n                    _from,\n                    _to,\n                    amountWad,\n                    _extraData\n                )\n            );\n        } else {\n            revert(\"L1BlastBridge: bridge token is not supported\");\n        }\n    }\n\n    /// @notice Computes the amount of gas required to guarantee that a given deposit will be\n    ///         received on the other chain without running out of gas.\n    /// @param _minGasLimit Minimum desired gas limit when deposit goes to target.\n    /// @return Amount of gas required to guarantee deposit receipt.\n    function baseGas(uint32 _minGasLimit) public pure returns (uint64) {\n        return\n        // Constant overhead\n        RECEIVE_DEFAULT_GAS_LIMIT\n        // Dynamic overhead (EIP-150)\n        + ((_minGasLimit * MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR) / MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR);\n    }\n}\n","deployed_bytecode":"0x6080604052600436106101445760003560e01c80636734eb24116100b6578063c8fb15331161006f578063c8fb15331461048d578063d81dc899146104ad578063d9ffb9d614610500578063e11013dd14610520578063ebf413eb14610533578063f8c8765e1461055357600080fd5b80636734eb241461031b5780637f46ddb2146103a257806387087623146103d65780638f601f66146103f6578063927ede2d1461043c578063c89701a21461045a57600080fd5b80632828d7e8116101085780632828d7e81461024857806333873a171461025d5780633cb747bf1461027d578063540abf731461029d57806354fd4d50146102bd5780636425666b146102fb57600080fd5b80630166a07a1461019757806309fc8843146101b75780630c568498146101ca5780631635f5fd146101fd57806326a2ebc91461021057600080fd5b3661019257333b156101715760405162461bcd60e51b815260040161016890611eb2565b60405180910390fd5b61019033333462030d4060405180602001604052806000815250610582565b005b600080fd5b3480156101a357600080fd5b506101906101b2366004611f70565b6106dd565b6101906101c5366004612021565b610aab565b3480156101d657600080fd5b506101df603f81565b60405167ffffffffffffffff90911681526020015b60405180910390f35b61019061020b366004612074565b610b12565b34801561021c57600080fd5b50603454610230906001600160a01b031681565b6040516001600160a01b0390911681526020016101f4565b34801561025457600080fd5b506101df604081565b34801561026957600080fd5b506101df6102783660046120e7565b610dda565b34801561028957600080fd5b50600354610230906001600160a01b031681565b3480156102a957600080fd5b506101906102b8366004612102565b610e0c565b3480156102c957600080fd5b506102ee604051806040016040528060058152602001640312e302e360dc1b81525081565b6040516101f491906121d1565b34801561030757600080fd5b50603654610230906001600160a01b031681565b34801561032757600080fd5b5061036e6103363660046121e4565b60326020526000908152604090205460ff8082169161010081048216916001600160a01b036201000083041691600160b01b90041684565b60408051941515855260ff90931660208501526001600160a01b0390911691830191909152151560608201526080016101f4565b3480156103ae57600080fd5b506102307f000000000000000000000000430000000000000000000000000000000000000581565b3480156103e257600080fd5b506101906103f1366004612201565b610e5a565b34801561040257600080fd5b5061042e610411366004612284565b600260209081526000928352604080842090915290825290205481565b6040519081526020016101f4565b34801561044857600080fd5b506003546001600160a01b0316610230565b34801561046657600080fd5b507f0000000000000000000000004300000000000000000000000000000000000005610230565b34801561049957600080fd5b506101906104a83660046122cb565b610ebe565b3480156104b957600080fd5b5061036e6104c83660046121e4565b60336020526000908152604090205460ff8082169161010081048216916001600160a01b036201000083041691600160b01b90041684565b34801561050c57600080fd5b5061019061051b3660046122cb565b611067565b61019061052e366004612342565b6111fd565b34801561053f57600080fd5b50603554610230906001600160a01b031681565b34801561055f57600080fd5b5061019061056e3660046123a5565b611246565b6001600160a01b03163b151590565b8234146105f75760405162461bcd60e51b815260206004820152603e60248201527f5374616e646172644272696467653a206272696467696e6720455448206d757360448201527f7420696e636c7564652073756666696369656e74204554482076616c756500006064820152608401610168565b610603858585846113a7565b6003546040516001600160a01b0390911690633dbb202b9085907f000000000000000000000000430000000000000000000000000000000000000590631635f5fd60e01b9061065c908b908b9086908a90602401612401565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e086901b90921682526106a49291889060040161243e565b6000604051808303818588803b1580156106bd57600080fd5b505af11580156106d1573d6000803e3d6000fd5b50505050505050505050565b6003546001600160a01b03163314801561078c575060035460408051636e296e4560e01b815290516001600160a01b037f00000000000000000000000043000000000000000000000000000000000000058116931691636e296e459160048083019260209291908290030181865afa15801561075d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107819190612478565b6001600160a01b0316145b6107a85760405162461bcd60e51b815260040161016890612495565b306001600160a01b0385160361080c5760405162461bcd60e51b815260206004820152602360248201527f5374616e646172644272696467653a2063616e6e6f742073656e6420746f207360448201526232b63360e91b6064820152608401610168565b6003546001600160a01b039081169085160361087b5760405162461bcd60e51b815260206004820152602860248201527f5374616e646172644272696467653a2063616e6e6f742073656e6420746f206d60448201526732b9b9b2b733b2b960c11b6064820152608401610168565b603460009054906101000a90046001600160a01b03166001600160a01b03166382bfefc86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f29190612478565b6001600160a01b0316876001600160a01b0316146109615760405162461bcd60e51b815260206004820152602660248201527f4c31426c6173744272696467653a20756e737570706f72746564206c6f63616c604482015265103a37b5b2b760d11b6064820152608401610168565b6001600160a01b0386166003604360981b01146109e65760405162461bcd60e51b815260206004820152603d60248201527f4c31426c6173744272696467653a206f6e6c7920555344422063616e2062652060448201527f77697468647261776e207468726f7567682074686973206272696467650000006064820152608401610168565b610a2a878787878787878080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506113fa92505050565b60345460405163da95ebf760e01b81526001600160a01b038681166004830152602482018690529091169063da95ebf7906044016020604051808303816000875af1158015610a7d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa191906124fc565b5050505050505050565b333b15610aca5760405162461bcd60e51b815260040161016890611eb2565b610b0d3333348686868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061058292505050565b505050565b6003546001600160a01b031633148015610bc1575060035460408051636e296e4560e01b815290516001600160a01b037f00000000000000000000000043000000000000000000000000000000000000058116931691636e296e459160048083019260209291908290030181865afa158015610b92573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bb69190612478565b6001600160a01b0316145b610bdd5760405162461bcd60e51b815260040161016890612495565b82341115610c485760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a20616d6f756e742073656e74206578636565604482015271191cc8185b5bdd5b9d081c995c5d5a5c995960721b6064820152608401610168565b306001600160a01b03851603610cab5760405162461bcd60e51b815260206004820152602260248201527f4c31426c6173744272696467653a2063616e6e6f742073656e6420746f207365604482015261363360f11b6064820152608401610168565b6003546001600160a01b0390811690851603610d195760405162461bcd60e51b815260206004820152602760248201527f4c31426c6173744272696467653a2063616e6e6f742073656e6420746f206d6560448201526639b9b2b733b2b960c91b6064820152608401610168565b610d5b85853485858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061145b92505050565b6000610d78855a34604051806020016040528060008152506114a0565b905080610dd25760405162461bcd60e51b815260206004820152602260248201527f4c32426c6173744272696467653a20455448207472616e73666572206661696c604482015261195960f21b6064820152608401610168565b505050505050565b6000603f610def604063ffffffff851661252b565b610df99190612571565b610e069062030d40612598565b92915050565b610e5187873388888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506114ba92505050565b50505050505050565b333b15610e795760405162461bcd60e51b815260040161016890611eb2565b610dd286863333888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506114ba92505050565b603560009054906101000a90046001600160a01b03166001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f359190612478565b6001600160a01b0316336001600160a01b031614610fb05760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a206f6e6c79204554485969656c644d616e6160448201527119d95c881bdddb995c8818d85b8818d85b1b60721b6064820152608401610168565b6001600160a01b038516610fc357600080fd5b60408051608081018252941515855260ff93841660208087019182526001600160a01b03948516878401908152931515606088019081529785166000908152603390915291909120945185549151925196511515600160b01b0260ff60b01b199790941662010000029690961662010000600160b81b0319929094166101000261ff00199615159690961661ffff1990911617949094179390931617919091179055565b603460009054906101000a90046001600160a01b03166001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110de9190612478565b6001600160a01b0316336001600160a01b0316146111595760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a206f6e6c79205553445969656c644d616e6160448201527119d95c881bdddb995c8818d85b8818d85b1b60721b6064820152608401610168565b60408051608081018252941515855260ff93841660208087019182526001600160a01b03948516878401908152931515606088019081529785166000908152603290915291909120945185549151925196511515600160b01b0260ff60b01b199790941662010000029690961662010000600160b81b0319929094166101000261ff00199615159690961661ffff1990911617949094179390931617919091179055565b6112403385348686868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061058292505050565b50505050565b600054610100900460ff16158080156112665750600054600160ff909116105b806112805750303b158015611280575060005460ff166001145b6112e35760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610168565b6000805460ff191660011790558015611306576000805461ff0019166101001790555b603680546001600160a01b0319166001600160a01b03871617905561132a84611ad1565b603480546001600160a01b038086166001600160a01b031992831617909255603580549285169290911691909117905580156113a0576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050505050565b826001600160a01b0316846001600160a01b03167f2849b43074093a05396b6f2a937dee8565b15a48a7b3d4bffb732a5017380af584846040516113ec9291906125c4565b60405180910390a350505050565b836001600160a01b0316856001600160a01b0316876001600160a01b03167fd59c65b35445225835c83f50b6ede06a7be047d22e357073e250d9af537518cd86868660405161144b939291906125dd565b60405180910390a4505050505050565b826001600160a01b0316846001600160a01b03167f31b2166ff604fc5672ea5df08a78081d2bc6d746cadce880747f3643d819e83d84846040516113ec9291906125c4565b600080600080845160208601878a8af19695505050505050565b6001600160a01b038088166000818152603260209081526040808320815160808082018452915460ff80821615158352610100808304821684880152620100008084048b1685880152600160b01b93849004831615156060808701919091529989526033885297869020865195860187525480831615158652908104821696850196909652958504909716928201929092529490910490911615159183019190915280519091901561185c576001600160a01b0388166003604360981b01146115e35760405162461bcd60e51b815260206004820152603560248201527f4c31426c6173744272696467653a207468697320746f6b656e2063616e206f6e604482015274363c90313290313934b233b2b2103a37902aa9a22160591b6064820152608401610168565b6034546115ff906001600160a01b038b8116918a911688611b5e565b600061161486846020015160ff166012611bb8565b6034546040516344f55f8160e11b81529192506000916001600160a01b03909116906389eabf029061164e908e9086908a906004016125dd565b6020604051808303816000875af115801561166d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169191906124fc565b905083606001511561171f5760408401516001600160a01b03166116b457600080fd5b6034546040858101519051632565663160e21b81526001600160a01b0391821660048201526024810184905291169063959598c490604401600060405180830381600087803b15801561170657600080fd5b505af115801561171a573d6000803e3d6000fd5b505050505b61172d8b8b8b8b858a611c0e565b60035460345460408051631057fdf960e31b815290516001600160a01b0393841693633dbb202b936005604360981b019362b3503d60e11b936003604360981b0193909216916382bfefc8916004808201926020929091908290030181865afa15801561179e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c29190612478565b8e8e888d6040516024016117db9695949392919061260d565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e085901b909216825261182392918b9060040161243e565b600060405180830381600087803b15801561183d57600080fd5b505af1158015611851573d6000803e3d6000fd5b505050505050611ac6565b805115611a69576001600160a01b038816156118d75760405162461bcd60e51b815260206004820152603460248201527f4c31426c6173744272696467653a207468697320746f6b656e2063616e206f6e6044820152730d8f240c4ca40c4e4d2c8cecac840e8de408aa8960631b6064820152608401610168565b6035546118f3906001600160a01b038b8116918a911688611b5e565b80606001511561197f5760408101516001600160a01b031661191457600080fd5b6035546040828101519051632565663160e21b81526001600160a01b0391821660048201526024810188905291169063959598c490604401600060405180830381600087803b15801561196657600080fd5b505af115801561197a573d6000803e3d6000fd5b505050505b600061199486836020015160ff166012611bb8565b90506119a48a8a8a8a8589611c0e565b6036546001600160a01b031663e9e05c426005604360981b01836119c789610dda565b600063a47a5c3560e01b8e8e898d6040516024016119e89493929190612401565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e088901b9092168252611a31959493929160040161265c565b600060405180830381600087803b158015611a4b57600080fd5b505af1158015611a5f573d6000803e3d6000fd5b5050505050611ac6565b60405162461bcd60e51b815260206004820152602c60248201527f4c31426c6173744272696467653a2062726964676520746f6b656e206973206e60448201526b1bdd081cdd5c1c1bdc9d195960a21b6064820152608401610168565b505050505050505050565b600054610100900460ff16611b3c5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610168565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052611240908590611c5f565b600081831115611be857611bcc828461269b565b611bd790600a612796565b611be190856127a2565b9050611c07565b611bf2838361269b565b611bfd90600a612796565b611be190856127b6565b9392505050565b836001600160a01b0316856001600160a01b0316876001600160a01b03167f7ff126db8024424bbfd9826e8ab82ff59136289ea440b04b39a0df1b03b9cabf86868660405161144b939291906125dd565b6000611cb4826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611d319092919063ffffffff16565b805190915015610b0d5780806020019051810190611cd291906127d5565b610b0d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610168565b6060611d408484600085611d48565b949350505050565b606082471015611da95760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610168565b6001600160a01b0385163b611e005760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610168565b600080866001600160a01b03168587604051611e1c91906127f2565b60006040518083038185875af1925050503d8060008114611e59576040519150601f19603f3d011682016040523d82523d6000602084013e611e5e565b606091505b5091509150611e6e828286611e79565b979650505050505050565b60608315611e88575081611c07565b825115611e985782518084602001fd5b8160405162461bcd60e51b815260040161016891906121d1565b60208082526037908201527f5374616e646172644272696467653a2066756e6374696f6e2063616e206f6e6c60408201527f792062652063616c6c65642066726f6d20616e20454f41000000000000000000606082015260800190565b6001600160a01b0381168114611f2457600080fd5b50565b60008083601f840112611f3957600080fd5b50813567ffffffffffffffff811115611f5157600080fd5b602083019150836020828501011115611f6957600080fd5b9250929050565b600080600080600080600060c0888a031215611f8b57600080fd5b8735611f9681611f0f565b96506020880135611fa681611f0f565b95506040880135611fb681611f0f565b94506060880135611fc681611f0f565b93506080880135925060a088013567ffffffffffffffff811115611fe957600080fd5b611ff58a828b01611f27565b989b979a50959850939692959293505050565b803563ffffffff8116811461201c57600080fd5b919050565b60008060006040848603121561203657600080fd5b61203f84612008565b9250602084013567ffffffffffffffff81111561205b57600080fd5b61206786828701611f27565b9497909650939450505050565b60008060008060006080868803121561208c57600080fd5b853561209781611f0f565b945060208601356120a781611f0f565b935060408601359250606086013567ffffffffffffffff8111156120ca57600080fd5b6120d688828901611f27565b969995985093965092949392505050565b6000602082840312156120f957600080fd5b611c0782612008565b600080600080600080600060c0888a03121561211d57600080fd5b873561212881611f0f565b9650602088013561213881611f0f565b9550604088013561214881611f0f565b94506060880135935061215d60808901612008565b925060a088013567ffffffffffffffff811115611fe957600080fd5b60005b8381101561219457818101518382015260200161217c565b838111156112405750506000910152565b600081518084526121bd816020860160208601612179565b601f01601f19169290920160200192915050565b602081526000611c0760208301846121a5565b6000602082840312156121f657600080fd5b8135611c0781611f0f565b60008060008060008060a0878903121561221a57600080fd5b863561222581611f0f565b9550602087013561223581611f0f565b94506040870135935061224a60608801612008565b9250608087013567ffffffffffffffff81111561226657600080fd5b61227289828a01611f27565b979a9699509497509295939492505050565b6000806040838503121561229757600080fd5b82356122a281611f0f565b915060208301356122b281611f0f565b809150509250929050565b8015158114611f2457600080fd5b600080600080600060a086880312156122e357600080fd5b85356122ee81611f0f565b945060208601356122fe816122bd565b9350604086013560ff8116811461231457600080fd5b9250606086013561232481611f0f565b91506080860135612334816122bd565b809150509295509295909350565b6000806000806060858703121561235857600080fd5b843561236381611f0f565b935061237160208601612008565b9250604085013567ffffffffffffffff81111561238d57600080fd5b61239987828801611f27565b95989497509550505050565b600080600080608085870312156123bb57600080fd5b84356123c681611f0f565b935060208501356123d681611f0f565b925060408501356123e681611f0f565b915060608501356123f681611f0f565b939692955090935050565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090612434908301846121a5565b9695505050505050565b6001600160a01b0384168152606060208201819052600090612462908301856121a5565b905063ffffffff83166040830152949350505050565b60006020828403121561248a57600080fd5b8151611c0781611f0f565b60208082526041908201527f5374616e646172644272696467653a2066756e6374696f6e2063616e206f6e6c60408201527f792062652063616c6c65642066726f6d20746865206f746865722062726964676060820152606560f81b608082015260a00190565b60006020828403121561250e57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600067ffffffffffffffff8083168185168183048111821515161561255257612552612515565b02949350505050565b634e487b7160e01b600052601260045260246000fd5b600067ffffffffffffffff8084168061258c5761258c61255b565b92169190910492915050565b600067ffffffffffffffff8083168185168083038211156125bb576125bb612515565b01949350505050565b828152604060208201526000611d4060408301846121a5565b60018060a01b038416815282602082015260606040820152600061260460608301846121a5565b95945050505050565b6001600160a01b03878116825286811660208301528581166040830152841660608201526080810183905260c060a08201819052600090612650908301846121a5565b98975050505050505050565b60018060a01b038616815284602082015267ffffffffffffffff84166040820152821515606082015260a060808201526000611e6e60a08301846121a5565b6000828210156126ad576126ad612515565b500390565b600181815b808511156126ed5781600019048211156126d3576126d3612515565b808516156126e057918102915b93841c93908002906126b7565b509250929050565b60008261270457506001610e06565b8161271157506000610e06565b816001811461272757600281146127315761274d565b6001915050610e06565b60ff84111561274257612742612515565b50506001821b610e06565b5060208310610133831016604e8410600b8410161715612770575081810a610e06565b61277a83836126b2565b806000190482111561278e5761278e612515565b029392505050565b6000611c0783836126f5565b6000826127b1576127b161255b565b500490565b60008160001904831182151516156127d0576127d0612515565b500290565b6000602082840312156127e757600080fd5b8151611c07816122bd565b60008251612804818460208701612179565b919091019291505056fea164736f6c634300080f000a","optimization_enabled":true,"verified_twin_address_hash":null,"is_verified":true,"compiler_settings":{"evmVersion":"london","libraries":{},"metadata":{"bytecodeHash":"none"},"optimizer":{"enabled":true,"runs":200},"remappings":[":@cwia/=lib/clones-with-immutable-args/src/",":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",":@rari-capital/solmate/=lib/solmate/",":clones-with-immutable-args/=lib/clones-with-immutable-args/src/",":ds-test/=lib/forge-std/lib/ds-test/src/",":erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",":forge-std/=lib/forge-std/src/",":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",":openzeppelin-contracts/=lib/openzeppelin-contracts/",":openzeppelin/=lib/openzeppelin-contracts-upgradeable/contracts/",":safe-contracts/=lib/safe-contracts/contracts/",":solmate/=lib/solmate/src/"]},"optimization_runs":200,"sourcify_repo_url":"https://repo.sourcify.dev/contracts/partial_match/1/0x7A2075519Dd9598b62075FD397aF0Dd34b14619a/","decoded_constructor_args":null,"compiler_version":"0.8.15+commit.e14f2714","is_verified_via_verifier_alliance":false,"verified_at":"2024-04-23T17:17:16.812945Z","implementations":[],"proxy_type":null,"external_libraries":[],"creation_bytecode":"0x60a06040523480156200001157600080fd5b507343000000000000000000000000000000000000056080526200003960008080806200003f565b6200025f565b600054610100900460ff1615808015620000605750600054600160ff909116105b806200009057506200007d30620001c160201b620005731760201c565b15801562000090575060005460ff166001145b620000f95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff1916600117905580156200011d576000805461ff0019166101001790555b603680546001600160a01b0319166001600160a01b0387161790556200014384620001d0565b603480546001600160a01b038086166001600160a01b03199283161790925560358054928516929091169190911790558015620001ba576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050505050565b6001600160a01b03163b151590565b600054610100900460ff166200023d5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401620000f0565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b60805161281b62000297600039600081816103b4015281816104690152818161061f0152818161070f0152610b44015261281b6000f3fe6080604052600436106101445760003560e01c80636734eb24116100b6578063c8fb15331161006f578063c8fb15331461048d578063d81dc899146104ad578063d9ffb9d614610500578063e11013dd14610520578063ebf413eb14610533578063f8c8765e1461055357600080fd5b80636734eb241461031b5780637f46ddb2146103a257806387087623146103d65780638f601f66146103f6578063927ede2d1461043c578063c89701a21461045a57600080fd5b80632828d7e8116101085780632828d7e81461024857806333873a171461025d5780633cb747bf1461027d578063540abf731461029d57806354fd4d50146102bd5780636425666b146102fb57600080fd5b80630166a07a1461019757806309fc8843146101b75780630c568498146101ca5780631635f5fd146101fd57806326a2ebc91461021057600080fd5b3661019257333b156101715760405162461bcd60e51b815260040161016890611eb2565b60405180910390fd5b61019033333462030d4060405180602001604052806000815250610582565b005b600080fd5b3480156101a357600080fd5b506101906101b2366004611f70565b6106dd565b6101906101c5366004612021565b610aab565b3480156101d657600080fd5b506101df603f81565b60405167ffffffffffffffff90911681526020015b60405180910390f35b61019061020b366004612074565b610b12565b34801561021c57600080fd5b50603454610230906001600160a01b031681565b6040516001600160a01b0390911681526020016101f4565b34801561025457600080fd5b506101df604081565b34801561026957600080fd5b506101df6102783660046120e7565b610dda565b34801561028957600080fd5b50600354610230906001600160a01b031681565b3480156102a957600080fd5b506101906102b8366004612102565b610e0c565b3480156102c957600080fd5b506102ee604051806040016040528060058152602001640312e302e360dc1b81525081565b6040516101f491906121d1565b34801561030757600080fd5b50603654610230906001600160a01b031681565b34801561032757600080fd5b5061036e6103363660046121e4565b60326020526000908152604090205460ff8082169161010081048216916001600160a01b036201000083041691600160b01b90041684565b60408051941515855260ff90931660208501526001600160a01b0390911691830191909152151560608201526080016101f4565b3480156103ae57600080fd5b506102307f000000000000000000000000000000000000000000000000000000000000000081565b3480156103e257600080fd5b506101906103f1366004612201565b610e5a565b34801561040257600080fd5b5061042e610411366004612284565b600260209081526000928352604080842090915290825290205481565b6040519081526020016101f4565b34801561044857600080fd5b506003546001600160a01b0316610230565b34801561046657600080fd5b507f0000000000000000000000000000000000000000000000000000000000000000610230565b34801561049957600080fd5b506101906104a83660046122cb565b610ebe565b3480156104b957600080fd5b5061036e6104c83660046121e4565b60336020526000908152604090205460ff8082169161010081048216916001600160a01b036201000083041691600160b01b90041684565b34801561050c57600080fd5b5061019061051b3660046122cb565b611067565b61019061052e366004612342565b6111fd565b34801561053f57600080fd5b50603554610230906001600160a01b031681565b34801561055f57600080fd5b5061019061056e3660046123a5565b611246565b6001600160a01b03163b151590565b8234146105f75760405162461bcd60e51b815260206004820152603e60248201527f5374616e646172644272696467653a206272696467696e6720455448206d757360448201527f7420696e636c7564652073756666696369656e74204554482076616c756500006064820152608401610168565b610603858585846113a7565b6003546040516001600160a01b0390911690633dbb202b9085907f000000000000000000000000000000000000000000000000000000000000000090631635f5fd60e01b9061065c908b908b9086908a90602401612401565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e086901b90921682526106a49291889060040161243e565b6000604051808303818588803b1580156106bd57600080fd5b505af11580156106d1573d6000803e3d6000fd5b50505050505050505050565b6003546001600160a01b03163314801561078c575060035460408051636e296e4560e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116931691636e296e459160048083019260209291908290030181865afa15801561075d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107819190612478565b6001600160a01b0316145b6107a85760405162461bcd60e51b815260040161016890612495565b306001600160a01b0385160361080c5760405162461bcd60e51b815260206004820152602360248201527f5374616e646172644272696467653a2063616e6e6f742073656e6420746f207360448201526232b63360e91b6064820152608401610168565b6003546001600160a01b039081169085160361087b5760405162461bcd60e51b815260206004820152602860248201527f5374616e646172644272696467653a2063616e6e6f742073656e6420746f206d60448201526732b9b9b2b733b2b960c11b6064820152608401610168565b603460009054906101000a90046001600160a01b03166001600160a01b03166382bfefc86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108f29190612478565b6001600160a01b0316876001600160a01b0316146109615760405162461bcd60e51b815260206004820152602660248201527f4c31426c6173744272696467653a20756e737570706f72746564206c6f63616c604482015265103a37b5b2b760d11b6064820152608401610168565b6001600160a01b0386166003604360981b01146109e65760405162461bcd60e51b815260206004820152603d60248201527f4c31426c6173744272696467653a206f6e6c7920555344422063616e2062652060448201527f77697468647261776e207468726f7567682074686973206272696467650000006064820152608401610168565b610a2a878787878787878080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506113fa92505050565b60345460405163da95ebf760e01b81526001600160a01b038681166004830152602482018690529091169063da95ebf7906044016020604051808303816000875af1158015610a7d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa191906124fc565b5050505050505050565b333b15610aca5760405162461bcd60e51b815260040161016890611eb2565b610b0d3333348686868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061058292505050565b505050565b6003546001600160a01b031633148015610bc1575060035460408051636e296e4560e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116931691636e296e459160048083019260209291908290030181865afa158015610b92573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bb69190612478565b6001600160a01b0316145b610bdd5760405162461bcd60e51b815260040161016890612495565b82341115610c485760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a20616d6f756e742073656e74206578636565604482015271191cc8185b5bdd5b9d081c995c5d5a5c995960721b6064820152608401610168565b306001600160a01b03851603610cab5760405162461bcd60e51b815260206004820152602260248201527f4c31426c6173744272696467653a2063616e6e6f742073656e6420746f207365604482015261363360f11b6064820152608401610168565b6003546001600160a01b0390811690851603610d195760405162461bcd60e51b815260206004820152602760248201527f4c31426c6173744272696467653a2063616e6e6f742073656e6420746f206d6560448201526639b9b2b733b2b960c91b6064820152608401610168565b610d5b85853485858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061145b92505050565b6000610d78855a34604051806020016040528060008152506114a0565b905080610dd25760405162461bcd60e51b815260206004820152602260248201527f4c32426c6173744272696467653a20455448207472616e73666572206661696c604482015261195960f21b6064820152608401610168565b505050505050565b6000603f610def604063ffffffff851661252b565b610df99190612571565b610e069062030d40612598565b92915050565b610e5187873388888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506114ba92505050565b50505050505050565b333b15610e795760405162461bcd60e51b815260040161016890611eb2565b610dd286863333888888888080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506114ba92505050565b603560009054906101000a90046001600160a01b03166001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f359190612478565b6001600160a01b0316336001600160a01b031614610fb05760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a206f6e6c79204554485969656c644d616e6160448201527119d95c881bdddb995c8818d85b8818d85b1b60721b6064820152608401610168565b6001600160a01b038516610fc357600080fd5b60408051608081018252941515855260ff93841660208087019182526001600160a01b03948516878401908152931515606088019081529785166000908152603390915291909120945185549151925196511515600160b01b0260ff60b01b199790941662010000029690961662010000600160b81b0319929094166101000261ff00199615159690961661ffff1990911617949094179390931617919091179055565b603460009054906101000a90046001600160a01b03166001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110de9190612478565b6001600160a01b0316336001600160a01b0316146111595760405162461bcd60e51b815260206004820152603260248201527f4c31426c6173744272696467653a206f6e6c79205553445969656c644d616e6160448201527119d95c881bdddb995c8818d85b8818d85b1b60721b6064820152608401610168565b60408051608081018252941515855260ff93841660208087019182526001600160a01b03948516878401908152931515606088019081529785166000908152603290915291909120945185549151925196511515600160b01b0260ff60b01b199790941662010000029690961662010000600160b81b0319929094166101000261ff00199615159690961661ffff1990911617949094179390931617919091179055565b6112403385348686868080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061058292505050565b50505050565b600054610100900460ff16158080156112665750600054600160ff909116105b806112805750303b158015611280575060005460ff166001145b6112e35760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610168565b6000805460ff191660011790558015611306576000805461ff0019166101001790555b603680546001600160a01b0319166001600160a01b03871617905561132a84611ad1565b603480546001600160a01b038086166001600160a01b031992831617909255603580549285169290911691909117905580156113a0576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b5050505050565b826001600160a01b0316846001600160a01b03167f2849b43074093a05396b6f2a937dee8565b15a48a7b3d4bffb732a5017380af584846040516113ec9291906125c4565b60405180910390a350505050565b836001600160a01b0316856001600160a01b0316876001600160a01b03167fd59c65b35445225835c83f50b6ede06a7be047d22e357073e250d9af537518cd86868660405161144b939291906125dd565b60405180910390a4505050505050565b826001600160a01b0316846001600160a01b03167f31b2166ff604fc5672ea5df08a78081d2bc6d746cadce880747f3643d819e83d84846040516113ec9291906125c4565b600080600080845160208601878a8af19695505050505050565b6001600160a01b038088166000818152603260209081526040808320815160808082018452915460ff80821615158352610100808304821684880152620100008084048b1685880152600160b01b93849004831615156060808701919091529989526033885297869020865195860187525480831615158652908104821696850196909652958504909716928201929092529490910490911615159183019190915280519091901561185c576001600160a01b0388166003604360981b01146115e35760405162461bcd60e51b815260206004820152603560248201527f4c31426c6173744272696467653a207468697320746f6b656e2063616e206f6e604482015274363c90313290313934b233b2b2103a37902aa9a22160591b6064820152608401610168565b6034546115ff906001600160a01b038b8116918a911688611b5e565b600061161486846020015160ff166012611bb8565b6034546040516344f55f8160e11b81529192506000916001600160a01b03909116906389eabf029061164e908e9086908a906004016125dd565b6020604051808303816000875af115801561166d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061169191906124fc565b905083606001511561171f5760408401516001600160a01b03166116b457600080fd5b6034546040858101519051632565663160e21b81526001600160a01b0391821660048201526024810184905291169063959598c490604401600060405180830381600087803b15801561170657600080fd5b505af115801561171a573d6000803e3d6000fd5b505050505b61172d8b8b8b8b858a611c0e565b60035460345460408051631057fdf960e31b815290516001600160a01b0393841693633dbb202b936005604360981b019362b3503d60e11b936003604360981b0193909216916382bfefc8916004808201926020929091908290030181865afa15801561179e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c29190612478565b8e8e888d6040516024016117db9695949392919061260d565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e085901b909216825261182392918b9060040161243e565b600060405180830381600087803b15801561183d57600080fd5b505af1158015611851573d6000803e3d6000fd5b505050505050611ac6565b805115611a69576001600160a01b038816156118d75760405162461bcd60e51b815260206004820152603460248201527f4c31426c6173744272696467653a207468697320746f6b656e2063616e206f6e6044820152730d8f240c4ca40c4e4d2c8cecac840e8de408aa8960631b6064820152608401610168565b6035546118f3906001600160a01b038b8116918a911688611b5e565b80606001511561197f5760408101516001600160a01b031661191457600080fd5b6035546040828101519051632565663160e21b81526001600160a01b0391821660048201526024810188905291169063959598c490604401600060405180830381600087803b15801561196657600080fd5b505af115801561197a573d6000803e3d6000fd5b505050505b600061199486836020015160ff166012611bb8565b90506119a48a8a8a8a8589611c0e565b6036546001600160a01b031663e9e05c426005604360981b01836119c789610dda565b600063a47a5c3560e01b8e8e898d6040516024016119e89493929190612401565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e088901b9092168252611a31959493929160040161265c565b600060405180830381600087803b158015611a4b57600080fd5b505af1158015611a5f573d6000803e3d6000fd5b5050505050611ac6565b60405162461bcd60e51b815260206004820152602c60248201527f4c31426c6173744272696467653a2062726964676520746f6b656e206973206e60448201526b1bdd081cdd5c1c1bdc9d195960a21b6064820152608401610168565b505050505050505050565b600054610100900460ff16611b3c5760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401610168565b600380546001600160a01b0319166001600160a01b0392909216919091179055565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052611240908590611c5f565b600081831115611be857611bcc828461269b565b611bd790600a612796565b611be190856127a2565b9050611c07565b611bf2838361269b565b611bfd90600a612796565b611be190856127b6565b9392505050565b836001600160a01b0316856001600160a01b0316876001600160a01b03167f7ff126db8024424bbfd9826e8ab82ff59136289ea440b04b39a0df1b03b9cabf86868660405161144b939291906125dd565b6000611cb4826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611d319092919063ffffffff16565b805190915015610b0d5780806020019051810190611cd291906127d5565b610b0d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610168565b6060611d408484600085611d48565b949350505050565b606082471015611da95760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610168565b6001600160a01b0385163b611e005760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610168565b600080866001600160a01b03168587604051611e1c91906127f2565b60006040518083038185875af1925050503d8060008114611e59576040519150601f19603f3d011682016040523d82523d6000602084013e611e5e565b606091505b5091509150611e6e828286611e79565b979650505050505050565b60608315611e88575081611c07565b825115611e985782518084602001fd5b8160405162461bcd60e51b815260040161016891906121d1565b60208082526037908201527f5374616e646172644272696467653a2066756e6374696f6e2063616e206f6e6c60408201527f792062652063616c6c65642066726f6d20616e20454f41000000000000000000606082015260800190565b6001600160a01b0381168114611f2457600080fd5b50565b60008083601f840112611f3957600080fd5b50813567ffffffffffffffff811115611f5157600080fd5b602083019150836020828501011115611f6957600080fd5b9250929050565b600080600080600080600060c0888a031215611f8b57600080fd5b8735611f9681611f0f565b96506020880135611fa681611f0f565b95506040880135611fb681611f0f565b94506060880135611fc681611f0f565b93506080880135925060a088013567ffffffffffffffff811115611fe957600080fd5b611ff58a828b01611f27565b989b979a50959850939692959293505050565b803563ffffffff8116811461201c57600080fd5b919050565b60008060006040848603121561203657600080fd5b61203f84612008565b9250602084013567ffffffffffffffff81111561205b57600080fd5b61206786828701611f27565b9497909650939450505050565b60008060008060006080868803121561208c57600080fd5b853561209781611f0f565b945060208601356120a781611f0f565b935060408601359250606086013567ffffffffffffffff8111156120ca57600080fd5b6120d688828901611f27565b969995985093965092949392505050565b6000602082840312156120f957600080fd5b611c0782612008565b600080600080600080600060c0888a03121561211d57600080fd5b873561212881611f0f565b9650602088013561213881611f0f565b9550604088013561214881611f0f565b94506060880135935061215d60808901612008565b925060a088013567ffffffffffffffff811115611fe957600080fd5b60005b8381101561219457818101518382015260200161217c565b838111156112405750506000910152565b600081518084526121bd816020860160208601612179565b601f01601f19169290920160200192915050565b602081526000611c0760208301846121a5565b6000602082840312156121f657600080fd5b8135611c0781611f0f565b60008060008060008060a0878903121561221a57600080fd5b863561222581611f0f565b9550602087013561223581611f0f565b94506040870135935061224a60608801612008565b9250608087013567ffffffffffffffff81111561226657600080fd5b61227289828a01611f27565b979a9699509497509295939492505050565b6000806040838503121561229757600080fd5b82356122a281611f0f565b915060208301356122b281611f0f565b809150509250929050565b8015158114611f2457600080fd5b600080600080600060a086880312156122e357600080fd5b85356122ee81611f0f565b945060208601356122fe816122bd565b9350604086013560ff8116811461231457600080fd5b9250606086013561232481611f0f565b91506080860135612334816122bd565b809150509295509295909350565b6000806000806060858703121561235857600080fd5b843561236381611f0f565b935061237160208601612008565b9250604085013567ffffffffffffffff81111561238d57600080fd5b61239987828801611f27565b95989497509550505050565b600080600080608085870312156123bb57600080fd5b84356123c681611f0f565b935060208501356123d681611f0f565b925060408501356123e681611f0f565b915060608501356123f681611f0f565b939692955090935050565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090612434908301846121a5565b9695505050505050565b6001600160a01b0384168152606060208201819052600090612462908301856121a5565b905063ffffffff83166040830152949350505050565b60006020828403121561248a57600080fd5b8151611c0781611f0f565b60208082526041908201527f5374616e646172644272696467653a2066756e6374696f6e2063616e206f6e6c60408201527f792062652063616c6c65642066726f6d20746865206f746865722062726964676060820152606560f81b608082015260a00190565b60006020828403121561250e57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600067ffffffffffffffff8083168185168183048111821515161561255257612552612515565b02949350505050565b634e487b7160e01b600052601260045260246000fd5b600067ffffffffffffffff8084168061258c5761258c61255b565b92169190910492915050565b600067ffffffffffffffff8083168185168083038211156125bb576125bb612515565b01949350505050565b828152604060208201526000611d4060408301846121a5565b60018060a01b038416815282602082015260606040820152600061260460608301846121a5565b95945050505050565b6001600160a01b03878116825286811660208301528581166040830152841660608201526080810183905260c060a08201819052600090612650908301846121a5565b98975050505050505050565b60018060a01b038616815284602082015267ffffffffffffffff84166040820152821515606082015260a060808201526000611e6e60a08301846121a5565b6000828210156126ad576126ad612515565b500390565b600181815b808511156126ed5781600019048211156126d3576126d3612515565b808516156126e057918102915b93841c93908002906126b7565b509250929050565b60008261270457506001610e06565b8161271157506000610e06565b816001811461272757600281146127315761274d565b6001915050610e06565b60ff84111561274257612742612515565b50506001821b610e06565b5060208310610133831016604e8410600b8410161715612770575081810a610e06565b61277a83836126b2565b806000190482111561278e5761278e612515565b029392505050565b6000611c0783836126f5565b6000826127b1576127b161255b565b500490565b60008160001904831182151516156127d0576127d0612515565b500290565b6000602082840312156127e757600080fd5b8151611c07816122bd565b60008251612804818460208701612179565b919091019291505056fea164736f6c634300080f000a","name":"L1BlastBridge","is_blueprint":false,"license_type":"none","is_fully_verified":false,"is_verified_via_eth_bytecode_db":true,"language":"solidity","evm_version":"london","can_be_visualized_via_sol2uml":true,"is_verified_via_sourcify":true,"additional_sources":[{"file_path":"src/L2/Shares.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { AddressAliasHelper } from \"src/vendor/AddressAliasHelper.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\nimport { Blast, YieldMode, GasMode } from \"src/L2/Blast.sol\";\n\n/// @custom:predeploy 0x4300000000000000000000000000000000000000\n/// @title SharesBase\n/// @notice Base contract to track share rebasing and yield reporting.\nabstract contract SharesBase is Initializable {\n    /// @notice Approved yield reporter.\n    address public immutable REPORTER;\n\n    /// @notice Share price. This value can only increase.\n    uint256 public price;\n\n    /// @notice Accumulated yield that has not been distributed\n    ///         to the share price.\n    uint256 public pending;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    ///         A gap size of 48 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[48] private __gap;\n\n    /// @notice Emitted when a new share price is set after a yield event.\n    event NewPrice(uint256 price);\n\n    error InvalidReporter();\n    error DistributeFailed(uint256 count, uint256 pending);\n    error PriceIsInitialized();\n\n    /// @param _reporter Address of the approved yield reporter.\n    constructor(address _reporter) {\n        REPORTER = _reporter;\n    }\n\n    /// @notice Initializer.\n    /// @param _price Initial share price.\n    // solhint-disable-next-line func-name-mixedcase\n    function __SharesBase_init(uint256 _price) internal onlyInitializing {\n        if (price != 0) {\n            revert PriceIsInitialized();\n        }\n        price = _price;\n    }\n\n    /// @notice Get the total number of shares. Needs to be\n    ///         overridden by the child contract.\n    /// @return Total number of shares.\n    function count() public view virtual returns (uint256);\n\n    /// @notice Report a yield event and update the share price.\n    /// @param value Amount of new yield\n    function addValue(uint256 value) external {\n        _addValue(value);\n    }\n\n    function _addValue(uint256 value) internal virtual {\n        if (AddressAliasHelper.undoL1ToL2Alias(msg.sender) != REPORTER) {\n            revert InvalidReporter();\n        }\n\n        if (value > 0) {\n            pending += value;\n        }\n\n        _tryDistributePending();\n    }\n\n    /// @notice Attempt to distribute pending yields if there\n    ///         are sufficient pending yields to increase the\n    ///         share price.\n    /// @return True if there were sufficient pending yields to\n    ///         increase the share price.\n    function _tryDistributePending() internal returns (bool) {\n        if (pending < count() || count() == 0) {\n            return false;\n        }\n\n        price += pending / count();\n        pending = pending % count();\n\n        emit NewPrice(price);\n\n        return true;\n    }\n}\n\n/// @custom:predeploy 0x4300000000000000000000000000000000000000\n/// @title Shares\n/// @notice Integrated EVM contract to manage native ether share\n///         rebasing from yield reports.\ncontract Shares is SharesBase, Semver {\n    /// @notice Total number of shares. This value is modified directly\n    ///         by the sequencer EVM.\n    uint256 private _count;\n\n    /// @notice _reporter Address of approved yield reporter.\n    constructor(address _reporter) SharesBase(_reporter) Semver(1, 0, 0) {\n        _disableInitializers();\n    }\n\n    /// @notice Initializer.\n    function initialize(uint256 _price) public initializer {\n        __SharesBase_init({ _price: _price });\n        Blast(Predeploys.BLAST).configureContract(\n            address(this),\n            YieldMode.VOID,\n            GasMode.VOID,\n            address(0xdead) /// don't set a governor\n        );\n    }\n\n    /// @inheritdoc SharesBase\n    function count() public view override returns (uint256) {\n        return _count;\n    }\n\n    function _addValue(uint256 value) internal override {\n        super._addValue(value);\n\n        SharesBase(Predeploys.WETH_REBASING).addValue(value);\n    }\n}\n"},{"file_path":"src/mainnet-bridge/yield-providers/YieldProvider.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { YieldManager } from \"src/mainnet-bridge/YieldManager.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\n\n/// @title YieldProvider\n/// @notice Base contract for interacting and accounting for a\n///         specific yield source.\nabstract contract YieldProvider is Semver {\n    YieldManager public immutable YIELD_MANAGER;\n\n    uint256 public stakedPrincipal;\n    uint256 public pendingBalance;\n\n    event YieldCommit(bytes32 indexed provider, int256 yield);\n    event Staked(bytes32 indexed provider, uint256 amount);\n    event Unstaked(bytes32 indexed provider, uint256 amount);\n    event Pending(bytes32 indexed provider, uint256 amount);\n    event Claimed(bytes32 indexed provider, uint256 claimedAmount, uint256 expectedAmount);\n    event InsurancePremiumPaid(bytes32 indexed provider, uint256 amount);\n    event InsuranceWithdrawn(bytes32 indexed provider, uint256 amount);\n\n    error InsufficientStakableFunds();\n    error CallerIsNotYieldManager();\n    error ContextIsNotYieldManager();\n    error NotSupported();\n\n    modifier onlyYieldManager() {\n        if (msg.sender != address(YIELD_MANAGER)) {\n            revert CallerIsNotYieldManager();\n        }\n        _;\n    }\n\n    modifier onlyDelegateCall() {\n        if (address(this) != address(YIELD_MANAGER)) {\n            revert ContextIsNotYieldManager();\n        }\n        _;\n    }\n\n    /// @param _yieldManager Address of the yield manager for the underlying\n    ///        yield asset of this provider.\n    constructor(YieldManager _yieldManager) Semver(1, 0, 0) {\n        require(address(_yieldManager) != address(this));\n        YIELD_MANAGER = _yieldManager;\n    }\n\n    /// @notice initialize\n    function initialize() external onlyDelegateCall virtual {}\n\n    function name() public pure virtual returns (string memory);\n\n    function id() public view returns (bytes32) {\n        return keccak256(abi.encodePacked(name(), version()));\n    }\n\n    /// @notice Whether staking is enabled for the given asset.\n    function isStakingEnabled(address token) external view virtual returns (bool);\n\n    /// @notice Current balance of the provider's staked funds.\n    function stakedBalance() public view virtual returns (uint256);\n\n    /// @notice Total value in the provider's yield method/protocol.\n    function totalValue() public view returns (uint256) {\n        return stakedBalance() + pendingBalance;\n    }\n\n    /// @notice Current amount of yield gained since the previous commit.\n    function yield() public view virtual returns (int256);\n\n    /// @notice Whether the provider supports yield insurance.\n    function supportsInsurancePayment() public view virtual returns (bool) {\n        return false;\n    }\n\n    /// @notice Gets insurance balance available for the provider's assets.\n    function insuranceBalance() public view virtual returns (uint256) {\n        revert(\"not supported\");\n    }\n\n    /// @notice Commit the current amount of yield and checkpoint the accounting\n    ///         variables.\n    /// @return Amount of yield at this checkpoint.\n    function commitYield() external onlyYieldManager returns (int256) {\n        _beforeCommitYield();\n\n        int256 _yield = yield();\n        stakedPrincipal = stakedBalance();\n\n        _afterCommitYield();\n\n        emit YieldCommit(id(), _yield);\n        return _yield;\n    }\n\n    /// @notice Stake YieldManager funds using the provider's yield method/protocol.\n    ///         Must be called via `delegatecall` from the YieldManager.\n    function stake(uint256) external virtual;\n\n    /// @notice Unstake YieldManager funds from the provider's yield method/protocol.\n    ///         Must be called via `delegatecall` from the YieldManager.\n    /// @return pending Amount of funds pending in an unstaking delay\n    /// @return claimed Amount of funds that have been claimed.\n    ///         The yield provider is expected to return\n    ///         (pending = 0, claimed = non-zero) if the funds are immediately\n    ///         available for withdrawal, and (pending = non-zero, claimed = 0)\n    ///         if the funds are in an unstaking delay.\n    function unstake(uint256) external virtual returns (uint256 pending, uint256 claimed);\n\n    /// @notice Pay insurance premium during a yield report. Must be called via\n    ///         `delegatecall` from the YieldManager.\n    function payInsurancePremium(uint256) external virtual onlyDelegateCall {\n        revert NotSupported();\n    }\n\n    /// @notice Withdraw insurance funds to cover yield losses during a yield report.\n    ///         Must be called via `delegatecall` from the YieldManager.\n    function withdrawFromInsurance(uint256) external virtual onlyDelegateCall {\n        revert NotSupported();\n    }\n\n    /// @notice Record a deposit to the stake balance of the provider to track the\n    ///         principal balance.\n    /// @param amount Amount of new staked balance to record.\n    function recordStakedDeposit(uint256 amount) external virtual onlyYieldManager {\n        stakedPrincipal += amount;\n        emit Staked(id(), amount);\n    }\n\n    /// @notice Record a withdraw to the stake balance of the provider to track the\n    ///         principal balance. This method should be called by the Yield Manager\n    ///         after delegate-calling the provider's `unstake` method, which should\n    ///         return the arguments to this method.\n    function recordUnstaked(uint256 pending, uint256 claimed, uint256 expected) external virtual onlyYieldManager {\n        _recordStakedWithdraw(expected);\n\n        if (pending > 0) {\n            require(claimed == 0 && pending == expected, \"invalid yield provider implementation\");\n            _recordPending(pending);\n        }\n\n        if (claimed > 0) {\n            require(pending == 0 && claimed == expected, \"invalid yield provider implementation\");\n            _recordClaimed(claimed, expected);\n        }\n    }\n\n    /// @notice A hook that is DELEGATE-CALLed by the Yield Manager for the provider\n    ///         to perform any actions before the yield report process begins.\n    function preCommitYieldReportDelegateCallHook() external virtual onlyDelegateCall {}\n\n    /// @notice Record a withdraw the stake balance of the provider.\n    /// @param amount Amount of staked balance to remove.\n    function _recordStakedWithdraw(uint256 amount) internal virtual {\n        stakedPrincipal -= amount;\n        emit Unstaked(id(), amount);\n    }\n\n    /// @notice Record a pending balance to the provider. Needed only for providers\n    ///         that use two-step withdrawals (e.g. Lido).\n    function _recordPending(uint256 amount) internal virtual {\n        pendingBalance += amount;\n        emit Pending(id(), amount);\n    }\n\n    /// @notice Record a claimed balance to the provider. For providers with one-step\n    ///         withdrawals, this method should be overriden to just emit the event\n    ///         to avoid integer underflow.\n    function _recordClaimed(uint256 claimed, uint256 expected) internal virtual {\n        require(claimed <= expected, \"invalid yield provider implementation\");\n        // Decrements pending balance by the expected amount, not the claimed amount.\n        // If claimed < expected, the difference (expected - claimed) must be considered\n        // as realized negative yield. To correctly reflect this, the difference is\n        // subtracted from the pending balance (and totalProviderValue).\n        pendingBalance -= expected;\n        emit Claimed(id(), claimed, expected);\n    }\n\n    function _beforeCommitYield() internal virtual {}\n    function _afterCommitYield() internal virtual {}\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/Math.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a >= b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1);\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator,\n        Rounding rounding\n    ) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`.\n        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.\n        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.\n        // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a\n        // good first aproximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1;\n        uint256 x = a;\n        if (x >> 128 > 0) {\n            x >>= 128;\n            result <<= 64;\n        }\n        if (x >> 64 > 0) {\n            x >>= 64;\n            result <<= 32;\n        }\n        if (x >> 32 > 0) {\n            x >>= 32;\n            result <<= 16;\n        }\n        if (x >> 16 > 0) {\n            x >>= 16;\n            result <<= 8;\n        }\n        if (x >> 8 > 0) {\n            x >>= 8;\n            result <<= 4;\n        }\n        if (x >> 4 > 0) {\n            x >>= 4;\n            result <<= 2;\n        }\n        if (x >> 2 > 0) {\n            result <<= 1;\n        }\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = sqrt(a);\n        if (rounding == Rounding.Up && result * result < a) {\n            result += 1;\n        }\n        return result;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.8;\n\nimport \"./ECDSAUpgradeable.sol\";\nimport \"../../interfaces/IERC5267Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable {\n    bytes32 private constant _TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    /// @custom:oz-renamed-from _HASHED_NAME\n    bytes32 private _hashedName;\n    /// @custom:oz-renamed-from _HASHED_VERSION\n    bytes32 private _hashedVersion;\n\n    string private _name;\n    string private _version;\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n        __EIP712_init_unchained(name, version);\n    }\n\n    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n        _name = name;\n        _version = version;\n\n        // Reset prior values in storage if upgrading\n        _hashedName = 0;\n        _hashedVersion = 0;\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        return _buildDomainSeparator();\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /**\n     * @dev See {EIP-5267}.\n     *\n     * _Available since v4.9._\n     */\n    function eip712Domain()\n        public\n        view\n        virtual\n        override\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized\n        // and the EIP712 domain is not reliable, as it will be missing name and version.\n        require(_hashedName == 0 && _hashedVersion == 0, \"EIP712: Uninitialized\");\n\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Name() internal virtual view returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Version() internal virtual view returns (string memory) {\n        return _version;\n    }\n\n    /**\n     * @dev The hash of the name parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.\n     */\n    function _EIP712NameHash() internal view returns (bytes32) {\n        string memory name = _EIP712Name();\n        if (bytes(name).length > 0) {\n            return keccak256(bytes(name));\n        } else {\n            // If the name is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.\n            bytes32 hashedName = _hashedName;\n            if (hashedName != 0) {\n                return hashedName;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n\n    /**\n     * @dev The hash of the version parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.\n     */\n    function _EIP712VersionHash() internal view returns (bytes32) {\n        string memory version = _EIP712Version();\n        if (bytes(version).length > 0) {\n            return keccak256(bytes(version));\n        } else {\n            // If the version is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.\n            bytes32 hashedVersion = _hashedVersion;\n            if (hashedVersion != 0) {\n                return hashedVersion;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[48] private __gap;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value\n    ) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 newAllowance = token.allowance(address(this), spender) + value;\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n    }\n\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            uint256 newAllowance = oldAllowance - value;\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n        }\n    }\n\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        if (returndata.length > 0) {\n            // Return data is optional\n            require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n        }\n    }\n}\n"},{"file_path":"src/libraries/rlp/RLPReader.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.8;\n\n/// @custom:attribution https://github.com/hamdiallam/Solidity-RLP\n/// @title RLPReader\n/// @notice RLPReader is a library for parsing RLP-encoded byte arrays into Solidity types. Adapted\n///         from Solidity-RLP (https://github.com/hamdiallam/Solidity-RLP) by Hamdi Allam with\n///         various tweaks to improve readability.\nlibrary RLPReader {\n    /// @notice Custom pointer type to avoid confusion between pointers and uint256s.\n    type MemoryPointer is uint256;\n\n    /// @notice RLP item types.\n    /// @custom:value DATA_ITEM Represents an RLP data item (NOT a list).\n    /// @custom:value LIST_ITEM Represents an RLP list item.\n    enum RLPItemType {\n        DATA_ITEM,\n        LIST_ITEM\n    }\n\n    /// @notice Struct representing an RLP item.\n    /// @custom:field length Length of the RLP item.\n    /// @custom:field ptr    Pointer to the RLP item in memory.\n    struct RLPItem {\n        uint256 length;\n        MemoryPointer ptr;\n    }\n\n    /// @notice Max list length that this library will accept.\n    uint256 internal constant MAX_LIST_LENGTH = 32;\n\n    /// @notice Converts bytes to a reference to memory position and length.\n    /// @param _in Input bytes to convert.\n    /// @return out_ Output memory reference.\n    function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory out_) {\n        // Empty arrays are not RLP items.\n        require(_in.length > 0, \"RLPReader: length of an RLP item must be greater than zero to be decodable\");\n\n        MemoryPointer ptr;\n        assembly {\n            ptr := add(_in, 32)\n        }\n\n        out_ = RLPItem({ length: _in.length, ptr: ptr });\n    }\n\n    /// @notice Reads an RLP list value into a list of RLP items.\n    /// @param _in RLP list value.\n    /// @return out_ Decoded RLP list items.\n    function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory out_) {\n        (uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);\n\n        require(itemType == RLPItemType.LIST_ITEM, \"RLPReader: decoded item type for list is not a list item\");\n\n        require(listOffset + listLength == _in.length, \"RLPReader: list item has an invalid data remainder\");\n\n        // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by\n        // writing to the length. Since we can't know the number of RLP items without looping over\n        // the entire input, we'd have to loop twice to accurately size this array. It's easier to\n        // simply set a reasonable maximum list length and decrease the size before we finish.\n        out_ = new RLPItem[](MAX_LIST_LENGTH);\n\n        uint256 itemCount = 0;\n        uint256 offset = listOffset;\n        while (offset < _in.length) {\n            (uint256 itemOffset, uint256 itemLength,) = _decodeLength(\n                RLPItem({ length: _in.length - offset, ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset) })\n            );\n\n            // We don't need to check itemCount < out.length explicitly because Solidity already\n            // handles this check on our behalf, we'd just be wasting gas.\n            out_[itemCount] = RLPItem({\n                length: itemLength + itemOffset,\n                ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)\n            });\n\n            itemCount += 1;\n            offset += itemOffset + itemLength;\n        }\n\n        // Decrease the array size to match the actual item count.\n        assembly {\n            mstore(out_, itemCount)\n        }\n    }\n\n    /// @notice Reads an RLP list value into a list of RLP items.\n    /// @param _in RLP list value.\n    /// @return out_ Decoded RLP list items.\n    function readList(bytes memory _in) internal pure returns (RLPItem[] memory out_) {\n        out_ = readList(toRLPItem(_in));\n    }\n\n    /// @notice Reads an RLP bytes value into bytes.\n    /// @param _in RLP bytes value.\n    /// @return out_ Decoded bytes.\n    function readBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {\n        (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);\n\n        require(itemType == RLPItemType.DATA_ITEM, \"RLPReader: decoded item type for bytes is not a data item\");\n\n        require(_in.length == itemOffset + itemLength, \"RLPReader: bytes value contains an invalid remainder\");\n\n        out_ = _copy(_in.ptr, itemOffset, itemLength);\n    }\n\n    /// @notice Reads an RLP bytes value into bytes.\n    /// @param _in RLP bytes value.\n    /// @return out_ Decoded bytes.\n    function readBytes(bytes memory _in) internal pure returns (bytes memory out_) {\n        out_ = readBytes(toRLPItem(_in));\n    }\n\n    /// @notice Reads the raw bytes of an RLP item.\n    /// @param _in RLP item to read.\n    /// @return out_ Raw RLP bytes.\n    function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {\n        out_ = _copy(_in.ptr, 0, _in.length);\n    }\n\n    /// @notice Decodes the length of an RLP item.\n    /// @param _in RLP item to decode.\n    /// @return offset_ Offset of the encoded data.\n    /// @return length_ Length of the encoded data.\n    /// @return type_ RLP item type (LIST_ITEM or DATA_ITEM).\n    function _decodeLength(RLPItem memory _in)\n        private\n        pure\n        returns (uint256 offset_, uint256 length_, RLPItemType type_)\n    {\n        // Short-circuit if there's nothing to decode, note that we perform this check when\n        // the user creates an RLP item via toRLPItem, but it's always possible for them to bypass\n        // that function and create an RLP item directly. So we need to check this anyway.\n        require(_in.length > 0, \"RLPReader: length of an RLP item must be greater than zero to be decodable\");\n\n        MemoryPointer ptr = _in.ptr;\n        uint256 prefix;\n        assembly {\n            prefix := byte(0, mload(ptr))\n        }\n\n        if (prefix <= 0x7f) {\n            // Single byte.\n            return (0, 1, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xb7) {\n            // Short string.\n\n            // slither-disable-next-line variable-scope\n            uint256 strLen = prefix - 0x80;\n\n            require(\n                _in.length > strLen, \"RLPReader: length of content must be greater than string length (short string)\"\n            );\n\n            bytes1 firstByteOfContent;\n            assembly {\n                firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))\n            }\n\n            require(\n                strLen != 1 || firstByteOfContent >= 0x80,\n                \"RLPReader: invalid prefix, single byte < 0x80 are not prefixed (short string)\"\n            );\n\n            return (1, strLen, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xbf) {\n            // Long string.\n            uint256 lenOfStrLen = prefix - 0xb7;\n\n            require(\n                _in.length > lenOfStrLen,\n                \"RLPReader: length of content must be > than length of string length (long string)\"\n            );\n\n            bytes1 firstByteOfContent;\n            assembly {\n                firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))\n            }\n\n            require(\n                firstByteOfContent != 0x00, \"RLPReader: length of content must not have any leading zeros (long string)\"\n            );\n\n            uint256 strLen;\n            assembly {\n                strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))\n            }\n\n            require(strLen > 55, \"RLPReader: length of content must be greater than 55 bytes (long string)\");\n\n            require(\n                _in.length > lenOfStrLen + strLen,\n                \"RLPReader: length of content must be greater than total length (long string)\"\n            );\n\n            return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);\n        } else if (prefix <= 0xf7) {\n            // Short list.\n            // slither-disable-next-line variable-scope\n            uint256 listLen = prefix - 0xc0;\n\n            require(_in.length > listLen, \"RLPReader: length of content must be greater than list length (short list)\");\n\n            return (1, listLen, RLPItemType.LIST_ITEM);\n        } else {\n            // Long list.\n            uint256 lenOfListLen = prefix - 0xf7;\n\n            require(\n                _in.length > lenOfListLen,\n                \"RLPReader: length of content must be > than length of list length (long list)\"\n            );\n\n            bytes1 firstByteOfContent;\n            assembly {\n                firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))\n            }\n\n            require(\n                firstByteOfContent != 0x00, \"RLPReader: length of content must not have any leading zeros (long list)\"\n            );\n\n            uint256 listLen;\n            assembly {\n                listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))\n            }\n\n            require(listLen > 55, \"RLPReader: length of content must be greater than 55 bytes (long list)\");\n\n            require(\n                _in.length > lenOfListLen + listLen,\n                \"RLPReader: length of content must be greater than total length (long list)\"\n            );\n\n            return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);\n        }\n    }\n\n    /// @notice Copies the bytes from a memory location.\n    /// @param _src    Pointer to the location to read from.\n    /// @param _offset Offset to start reading from.\n    /// @param _length Number of bytes to read.\n    /// @return out_ Copied bytes.\n    function _copy(MemoryPointer _src, uint256 _offset, uint256 _length) private pure returns (bytes memory out_) {\n        out_ = new bytes(_length);\n        if (_length == 0) {\n            return out_;\n        }\n\n        // Mostly based on Solidity's copy_memory_to_memory:\n        // solhint-disable max-line-length\n        // https://github.com/ethereum/solidity/blob/34dd30d71b4da730488be72ff6af7083cf2a91f6/libsolidity/codegen/YulUtilFunctions.cpp#L102-L114\n        uint256 src = MemoryPointer.unwrap(_src) + _offset;\n        assembly {\n            let dest := add(out_, 32)\n            let i := 0\n            for { } lt(i, _length) { i := add(i, 32) } { mstore(add(dest, i), mload(add(src, i))) }\n\n            if gt(i, _length) { mstore(add(dest, _length), 0) }\n        }\n    }\n}\n"},{"file_path":"src/mainnet-bridge/YieldManager.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { SignedMath } from \"@openzeppelin/contracts/utils/math/SignedMath.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { WithdrawalQueue } from \"src/mainnet-bridge/withdrawal-queue/WithdrawalQueue.sol\";\nimport { YieldProvider } from \"src/mainnet-bridge/yield-providers/YieldProvider.sol\";\nimport { Types } from \"src/libraries/Types.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { CrossDomainMessenger } from \"src/universal/CrossDomainMessenger.sol\";\nimport { SharesBase } from \"src/L2/Shares.sol\";\nimport { DelegateCalls } from \"src/mainnet-bridge/DelegateCalls.sol\";\nimport { USDConversions } from \"src/mainnet-bridge/USDConversions.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { OptimismPortal } from \"src/L1/OptimismPortal.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\n\ninterface IInsurance {\n    function coverLoss(address token, uint256 amount) external;\n}\n\n/// @title YieldManager\n/// @notice Base contract to centralize accounting, asset management and\n///         yield reporting from yield providers of a common base asset.\nabstract contract YieldManager is Ownable2StepUpgradeable, WithdrawalQueue, DelegateCalls {\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    /// @notice Maximum gas limit for the yield report call on L2.\n    uint32 internal constant REPORT_YIELD_DEFAULT_GAS_LIMIT = 200_000;\n\n    /// @notice Maximum insurance fee the owner is allowed to set.\n    uint256 public constant MAX_INSURANCE_FEE_BIPS = 10_000; // 100%\n\n    /// @notice Number of basis points representing 100 percent.\n    uint256 internal constant BASIS_POINTS = 10_000;\n\n    /// @notice Set of provider addresses.\n    EnumerableSet.AddressSet private _providers;\n\n    /// @notice Address of the admin handling regular tasks such as\n    ///         `stake`, `unstake`, `claim`, `commitYieldReport`, and\n    ///         `finalize`.\n    address public admin;\n\n    /// @notice Address of the insurance module.\n    address public insurance;\n\n    /// @notice Address of the L1BlastBridge.\n    address public blastBridge;\n\n    /// @notice Sum of negative yields to track the slippage between L2-L1 share price.\n    ///         If negative yields accumulate, L1 withdrawals are discounted to cover the\n    ///         loss.\n    uint256 public accumulatedNegativeYields;\n\n    /// @notice Current insurance fee in bips.\n    uint256 public insuranceFeeBips;\n\n    /// @notice Amount of additional funds to withdraw from insurance.\n    ///         This buffer addresses the scenario where the transfer of the exact amount of accumulated\n    ///         negative yields from insurance does not fully pay off the outstanding amount. In Lido's\n    ///         system, the transfer logic is based on shares, which may lead to discrepancies in the\n    ///         withdrawal of insurance funds. By including this buffer, the system ensures that when\n    ///         insurance funds are withdrawn, the total amount withdrawn is the exact required amount\n    ///         plus an additional buffer. This approach guarantees the complete payoff of any negative\n    ///         yields, accommodating for any potential rounding discrepancies inherent in the share-based\n    ///         transfer logic.\n    uint256 public insuranceWithdrawalBuffer;\n\n    /// @notice Address of the OptimismPortal.\n    OptimismPortal public portal;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    ///         A gap size of 41 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[41] private __gap;\n\n    struct ProviderInfo {\n        bytes32 id;\n        address providerAddress;\n        uint256 stakedBalance;\n        uint256 pendingBalance;\n        uint256 stakedPrincipal;\n        uint256 totalValue;\n        int256 yield;\n    }\n\n    /// @notice Emitted when the yield report is committed on L1 and\n    ///         the yield is communicated to L2.\n    /// @param yield                Amount of yield generated at this checkpoint.\n    /// @param insurancePremiumPaid Amount paid in insurance.\n    /// @param insuranceWithdrawn   Amount withdrawn from insurance.\n    event YieldReport(\n        int256  yield,\n        uint256 insurancePremiumPaid,\n        uint256 insuranceWithdrawn\n    );\n\n    error CallerIsNotAdmin();\n    error FailedToInitializeProvider();\n    error ProviderAddressDoesNotMatchIndex();\n    error InsufficientInsuranceBalance();\n    error NegativeYieldFromInsuredProvider();\n    error TotalValueIsZero();\n    error CallerIsNotBlastBridge();\n    error ProviderNotFound();\n    error YieldProviderIsNotMeantForThisManager();\n    error NegativeYieldIncrease();\n\n    modifier onlyAdmin() {\n        if (msg.sender != admin) {\n            revert CallerIsNotAdmin();\n        }\n        _;\n    }\n\n    /// @notice Modifier only allowing the L1BlastBridge to call a function.\n    modifier onlyBlastBridge() {\n        if (msg.sender != blastBridge) {\n            revert CallerIsNotBlastBridge();\n        }\n        _;\n    }\n\n    /// @param _token Address of withdrawal token.\n    constructor(address _token) WithdrawalQueue(_token) {}\n\n    /// @notice initializer\n    /// @param _portal Address of the OptimismPortal.\n    /// @param _owner  Address of the YieldManager owner.\n    function __YieldManager_init(OptimismPortal _portal, address _owner) internal onlyInitializing {\n        __Ownable2Step_init();\n        __WithdrawalQueue_init();\n        _transferOwnership(_owner);\n\n        portal = _portal;\n    }\n\n    /* ========== OWNER FUNCTIONS ========== */\n\n    /// @notice Set new admin account to handle regular tasks including\n    ///         (stake, unstake, claim).\n    /// @param _admin Address of new admin\n    function setAdmin(address _admin) external onlyOwner {\n        require(_admin != address(0));\n        admin = _admin;\n    }\n\n    /// @notice Set the yield insurance parameters.\n    /// @param _insurance        Address of the insurance module.\n    /// @param _insuranceFeeBips Insurance fee to take from positive yields.\n    /// @param _withdrawalBuffer Amount of additional funds to withdraw from insurance.\n    function setInsurance(address _insurance, uint256 _insuranceFeeBips, uint256 _withdrawalBuffer) external onlyOwner {\n        require(_insurance != address(0));\n        require(_insuranceFeeBips <= MAX_INSURANCE_FEE_BIPS);\n        insurance = _insurance;\n        insuranceFeeBips = _insuranceFeeBips;\n        insuranceWithdrawalBuffer = _withdrawalBuffer;\n    }\n\n    /// @notice Set the address of the L1BlastBridge.\n    /// @param _blastBridge Address of the L1BlastBridge.\n    function setBlastBridge(address _blastBridge) external onlyOwner {\n        require(_blastBridge != address(0));\n        blastBridge = _blastBridge;\n    }\n\n    /// @notice Add a yield provider contract.\n    /// @param provider Address of the yield provider.\n    function addProvider(address provider) external onlyOwner {\n        if (address(YieldProvider(provider).YIELD_MANAGER()) != address(this)) {\n            revert YieldProviderIsNotMeantForThisManager();\n        }\n        _providers.add(provider);\n        (bool success,) = provider.delegatecall(abi.encodeWithSignature(\"initialize()\"));\n        if (!success) {\n            revert FailedToInitializeProvider();\n        }\n    }\n\n    /// @notice Remove a yield provider contract.\n    /// @param provider Address of the yield provider.\n    function removeProvider(address provider) external onlyOwner {\n        _providers.remove(provider);\n    }\n\n    /* ========== ADMIN FUNCTIONS ========== */\n\n    /// @notice Stake funds for a particular yield provider and record the\n    ///         staked deposit. The stake call is made via 'delegatecall'\n    ///         so the yield provider implementation is executed with the\n    ///         yield manager's funds.\n    /// @param idx             Index of the provider.\n    /// @param providerAddress Address of the provider at index 'idx'.\n    /// @param amount          Amount to stake (wad).\n    function stake(uint256 idx, address providerAddress, uint256 amount) external onlyAdmin {\n        if (_providers.at(idx) != providerAddress) {\n            revert ProviderAddressDoesNotMatchIndex();\n        }\n        _delegatecall_stake(providerAddress, amount);\n        YieldProvider(providerAddress).recordStakedDeposit(amount);\n    }\n\n    /// @notice Unstake funds for a particular yield provider and record the\n    ///         staked withdraw. The stake call is made via 'delegatecall'\n    ///         so the yield provider implementation is executed with the\n    ///         yield manager's funds.\n    /// @param idx             Index of the provider.\n    /// @param providerAddress Address of the provider at index 'idx'.\n    /// @param amount          Amount to stake (wad).\n    function unstake(uint256 idx, address providerAddress, uint256 amount) external onlyAdmin {\n        if (_providers.at(idx) != providerAddress) {\n            revert ProviderAddressDoesNotMatchIndex();\n        }\n        (uint256 pending, uint256 claimed) = _delegatecall_unstake(providerAddress, amount);\n        YieldProvider(providerAddress).recordUnstaked(pending, claimed, amount);\n    }\n\n    /// @notice Commit yield report.\n    /// @param enableInsurance Whether insurance should be taken from positive yields\n    ///        and paid out for negative yields. If false, negative yields will\n    ///        accumulate and withdrawals will be discounted. If true (and insurance\n    ///        is supported by the provider), it will guarantee that committed yield\n    ///        is always non-negative, or else revert. It also guarantees that\n    ///        accumulated negative yields never increase.\n    function commitYieldReport(bool enableInsurance) public onlyAdmin {\n        uint256 providersLength = _providers.length();\n        uint256 negativeYieldBefore = accumulatedNegativeYields;\n        uint256 totalInsurancePremiumPaid;\n        uint256 totalInsuranceWithdrawal;\n        int256 totalYield;\n\n        // For each provider, commit yield after paying to/from the insurance as necessary\n        for (uint256 i; i < providersLength; i++) {\n            // run the pre-commit yield report hook\n            _delegatecall_preCommitYieldReportDelegateCallHook(_providers.at(i));\n\n            // read the current yield from the provider\n            int256 yield = YieldProvider(_providers.at(i)).yield();\n            uint256 insurancePayment;\n\n            // take care of insurance payments and withdrawals\n            if (\n                enableInsurance &&\n                YieldProvider(_providers.at(i)).supportsInsurancePayment() &&\n                insurance != address(0)\n            ) {\n                if (yield > 0) {\n                    // pay the insurance premium\n                    insurancePayment = uint256(yield) * insuranceFeeBips / BASIS_POINTS;\n                    _delegatecall_payInsurancePremium(_providers.at(i), insurancePayment);\n                    totalInsurancePremiumPaid += insurancePayment;\n                } else if (yield < 0) {\n                    // withdraw from the insurance to cover the loss\n                    uint256 insuranceWithdrawal = SignedMath.abs(yield) + insuranceWithdrawalBuffer;\n                    uint256 insuranceBalance = YieldProvider(_providers.at(i)).insuranceBalance();\n                    if (insuranceBalance < insuranceWithdrawal) {\n                        revert InsufficientInsuranceBalance();\n                    }\n                    _delegatecall_withdrawFromInsurance(_providers.at(i), insuranceWithdrawal);\n                    totalInsuranceWithdrawal += insuranceWithdrawal;\n                }\n            }\n\n            // Commit the yield for the provider\n            int256 committedYield = YieldProvider(_providers.at(i)).commitYield();\n\n            // Sanity check\n            if (\n                enableInsurance &&\n                YieldProvider(_providers.at(i)).supportsInsurancePayment() &&\n                insurance != address(0)\n            ) {\n                if (committedYield < 0) {\n                    revert NegativeYieldFromInsuredProvider();\n                }\n            }\n\n            // update totalYield\n            totalYield += committedYield;\n        }\n\n        // reflect the accumulated negative yield in totalYield\n        if (accumulatedNegativeYields > 0) {\n            totalYield -= SafeCast.toInt256(accumulatedNegativeYields);\n        }\n\n        emit YieldReport(totalYield, totalInsurancePremiumPaid, totalInsuranceWithdrawal);\n\n        if (totalYield < 0) {\n            accumulatedNegativeYields = uint256(-1 * totalYield);\n        } else {\n            accumulatedNegativeYields = 0;\n            if (totalYield > 0) {\n                _reportYield(\n                    abi.encodeWithSelector(\n                        SharesBase.addValue.selector,\n                        totalYield\n                    )\n                );\n            }\n        }\n\n        if (enableInsurance && accumulatedNegativeYields > negativeYieldBefore) {\n            revert NegativeYieldIncrease();\n        }\n    }\n\n    /// @notice Helper function to atomically withdraw from insurance and commit yield report.\n    ///         This function can be used to maintain share price = 1e27 when yield from\n    ///         the registered providers is not sufficient to cover negative yield from\n    ///         LidoYieldProvider._claim().\n    function commitYieldReportAfterInsuranceWithdrawal(\n        address token,\n        uint256 amount\n    ) external onlyAdmin {\n        require(insurance != address(0));\n        IInsurance(insurance).coverLoss(token, amount);\n        commitYieldReport(true);\n    }\n\n    /// @notice Report realized negative yield. This is meant to be called inside a YieldProvider\n    ///         method that is executed via 'delegatecall' by the YieldManager.\n    function recordNegativeYield(uint256 amount) external {\n        require(msg.sender == address(this), \"Caller is not this contract\");\n        accumulatedNegativeYields += amount;\n    }\n\n    /// @notice Finalize withdrawal requests up to 'requestId'.\n    /// @param requestId Last request id to finalize in this batch.\n    function finalize(uint256 requestId) external onlyAdmin returns (uint256 checkpointId) {\n        uint256 nominalAmount; uint256 realAmount;\n        (nominalAmount, realAmount, checkpointId) = _finalize(requestId, availableBalance(), sharePrice());\n        // nominalAmount - realAmount is the share of the accumulated negative yield\n        // that should be paid by the current withdrawal\n        if (nominalAmount > realAmount) {\n            accumulatedNegativeYields = _subClamped(accumulatedNegativeYields, nominalAmount - realAmount);\n        }\n    }\n\n    /* ========== VIRTUAL FUNCTIONS ========== */\n\n    /// @notice Get the amount of the withdrawal token that is held by the yield manager.\n    function tokenBalance() public view virtual returns (uint256);\n\n    /// @notice Send the yield report to the L2 contract that is responsible for\n    ///         updating the L2 share price.\n    /// @param data Calldata to send in the message.\n    function _reportYield(bytes memory data) internal virtual;\n\n    /* ========== VIEW FUNCTIONS ========== */\n\n    /// @notice Available balance.\n    function availableBalance() public view returns (uint256) {\n        return tokenBalance() - getLockedBalance();\n    }\n\n    /// @notice Get the total value of all yield providers denominated in the withdrawal token.\n    function totalProviderValue() public view returns (uint256 sum) {\n        uint256 providersLength = _providers.length();\n        for (uint256 i; i < providersLength; i++) {\n            sum += YieldProvider(_providers.at(i)).totalValue();\n        }\n    }\n\n    /// @notice Get the total value of all yield providers plus the available balance value.\n    function totalValue() public view returns (uint256) {\n        return availableBalance() + totalProviderValue();\n    }\n\n    /// @notice Get the share price of the withdrawal token with 1e27 precision.\n    ///         The share price is capped at 1e27 and can only go down if there\n    ///         are accumulated negative yields.\n    function sharePrice() public view returns (uint256) {\n        uint256 value = totalValue();\n        if (value == 0) {\n            revert TotalValueIsZero();\n        }\n        return value * E27_PRECISION_BASE / (value + accumulatedNegativeYields);\n    }\n\n    /// @notice Get an accounting report on the current state of a yield provider.\n    ///         Due to how EnumerableSet works, 'idx' is not guaranteed to be stable\n    ///         across add/remove operations so admin should verify the idx before\n    ///         calling state-changing functions (e.g. stake, unstake).\n    /// @param idx Index of the provider.\n    /// @return info Accounting report on the yield provider.\n    function getProviderInfoAt(uint256 idx) external view returns (ProviderInfo memory info) {\n        YieldProvider provider = YieldProvider(_providers.at(idx));\n\n        info.id = provider.id();\n        info.providerAddress = address(provider);\n        info.stakedBalance = provider.stakedBalance();\n        info.pendingBalance = provider.pendingBalance();\n        info.stakedPrincipal = provider.stakedPrincipal();\n        info.totalValue = provider.totalValue();\n        info.yield = provider.yield();\n    }\n\n    /// @notice Record an increase to the staked funds represented\n    ///         by the provider.\n    /// @param providerAddress Address of yield provider.\n    /// @param amount          Amount of additional staked funds.\n    function recordStakedDeposit(address providerAddress, uint256 amount) external onlyBlastBridge {\n        if (!_providers.contains(providerAddress)) {\n            revert ProviderNotFound();\n        }\n        YieldProvider(providerAddress).recordStakedDeposit(amount);\n    }\n\n    /// @notice Returns max(0, x - y) without reverting on underflow.\n    function _subClamped(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x > y ? x - y : 0;\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},{"file_path":"src/mainnet-bridge/USDConversions.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n\nimport { YieldManager } from \"src/mainnet-bridge/YieldManager.sol\";\n\ninterface IUSDT {\n    function approve(address spender, uint256 amount) external;\n    function balanceOf(address) external view returns (uint256);\n}\n\ninterface IDssPsm {\n    function sellGem(address usr, uint256 gemAmt) external;\n    function buyGem(address usr, uint256 gemAmt) external;\n    function gemJoin() external view returns (address);\n}\n\ninterface ICurve3Pool {\n    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;\n}\n\n/// @title USDConversions\n/// @notice Stateless helper module for converting between USD tokens (DAI/USDC/USDT).\n///\n///         DAI and USDC are converted 1-to-1 using Maker's Peg Stability Mechanism.\n///         All other tokens conversions are completed through Curve's 3Pool.\nlibrary USDConversions {\n    uint256 constant WAD_DECIMALS = 18;\n    uint256 constant USD_DECIMALS = 6;\n    int128 constant DAI_INDEX = 0;\n    int128 constant USDC_INDEX = 1;\n    int128 constant USDT_INDEX = 2;\n\n    IERC20 constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);\n    IERC20 constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);\n    IUSDT constant USDT = IUSDT(0xdAC17F958D2ee523a2206206994597C13D831ec7);\n    IDssPsm constant PSM = IDssPsm(0x89B78CfA322F6C5dE0aBcEecab66Aee45393cC5A);\n    ICurve3Pool constant CURVE_3POOL = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);\n\n    /// @notice immutable address of PSM's GemJoin contract\n    address constant GEM_JOIN = 0x0A59649758aa4d66E25f08Dd01271e891fe52199;\n\n    error InsufficientBalance();\n    error MinimumAmountNotMet();\n    error IncorrectInputAmountUsed();\n    error UnsupportedToken();\n    error InvalidExtraData();\n    error InvalidTokenIndex();\n\n    /// @notice Initializer\n    function _init() internal {\n        USDC.approve(address(CURVE_3POOL), type(uint256).max);\n        USDC.approve(GEM_JOIN, type(uint256).max);\n        USDT.approve(address(CURVE_3POOL), type(uint256).max);\n        DAI.approve(address(CURVE_3POOL), type(uint256).max);\n        DAI.approve(GEM_JOIN, type(uint256).max);\n        DAI.approve(address(PSM), type(uint256).max);\n    }\n\n    /// @notice Convert between the 3 stablecoin tokens using Curve's 3Pool and Maker's\n    ///         Peg Stability Mechanism.\n    /// @param inputToken         Input token index.\n    /// @param outputToken        Output token index.\n    /// @param inputAmountWad     Input amount in WAD.\n    /// @param minOutputAmountWad Minimum amount of output token accepted in WAD.\n    /// @return amountReceived Amount of output token received in the token's\n    ///         decimal representation.\n    function _convert(int128 inputToken, int128 outputToken, uint256 inputAmountWad, uint256 minOutputAmountWad) internal returns (uint256 amountReceived) {\n        require(inputToken >= 0 && inputToken < 3 && outputToken >= 0 && outputToken < 3);\n        require(inputToken != outputToken);\n        if (inputAmountWad > 0) {\n            uint256 inputAmount = _convertDecimals(inputAmountWad, inputToken);\n            uint256 minOutputAmount = _convertDecimals(minOutputAmountWad, outputToken);\n            if (_tokenBalance(inputToken) < inputAmount) {\n                revert InsufficientBalance();\n            }\n            uint256 beforeBalance = _tokenBalance(outputToken);\n            if (inputToken == USDC_INDEX && outputToken == DAI_INDEX) {\n                PSM.sellGem(address(this), inputAmount);\n            } else if (inputToken == DAI_INDEX && outputToken == USDC_INDEX) {\n                uint256 beforeInputBalance = _tokenBalance(inputToken);\n                PSM.buyGem(address(this), _wadToUSD(minOutputAmountWad)); // buyGem expects the input amount in USDC\n                uint256 amountSent = beforeInputBalance - _tokenBalance(inputToken);\n                if (amountSent != inputAmountWad) {\n                    revert IncorrectInputAmountUsed();\n                }\n            } else {\n                CURVE_3POOL.exchange(\n                    inputToken,\n                    outputToken,\n                    inputAmount,\n                    minOutputAmount\n                );\n            }\n            amountReceived = _tokenBalance(outputToken) - beforeBalance;\n            if (amountReceived < minOutputAmount) {\n                revert MinimumAmountNotMet();\n            }\n        }\n    }\n\n    /// @notice Convert between supported token pairs, reverting if not supported.\n    /// @param inputTokenAddress  Address of the input token.\n    /// @param outputTokenAddress Address of the output token.\n    /// @param inputAmountWad     Amount of input token to convert in WAD.\n    /// @param _extraData         Extra data containing the minimum amount of output token to receive in WAD.\n    /// @return amountReceived Amount of output token received in WAD.\n    function _convertTo(\n        address inputTokenAddress,\n        address outputTokenAddress,\n        uint256 inputAmountWad,\n        bytes memory _extraData\n    ) internal returns (uint256 amountReceived) {\n        if (inputTokenAddress == outputTokenAddress) {\n            return inputAmountWad;\n        }\n\n        if (outputTokenAddress == address(DAI)) {\n            return _convertToDAI(inputTokenAddress, inputAmountWad, _extraData);\n        } else {\n            revert UnsupportedToken();\n        }\n    }\n\n    /// @notice Convert USDC, USDT, and DAI to DAI. If the input token is DAI,\n    ///         the input amount is returned without conversion.\n    /// @param inputTokenAddress Address of the input token.\n    /// @param inputAmountWad    Amount of input token to convert in WAD.\n    /// @param _extraData        Extra data containing the minimum amount of USDB to be minted in WAD.\n    ///                          Only needed for USDC and USDT. The expected format is: (uint256 minOutputAmountWad).\n    /// @return amountReceived Amount of DAI received.\n    function _convertToDAI(address inputTokenAddress, uint256 inputAmountWad, bytes memory _extraData) internal returns (uint256 amountReceived) {\n        if (inputTokenAddress == address(DAI)) {\n            return inputAmountWad;\n        }\n\n        if (_extraData.length != 32) {\n            revert InvalidExtraData();\n        }\n\n        uint256 minOutputAmountWad = abi.decode(_extraData, (uint256));\n\n        if (inputTokenAddress == address(USDC)) {\n            return USDConversions._convert(USDC_INDEX, DAI_INDEX, inputAmountWad, minOutputAmountWad);\n        } else if (inputTokenAddress == address(USDT)) {\n            return USDConversions._convert(USDT_INDEX, DAI_INDEX, inputAmountWad, minOutputAmountWad);\n        } else {\n            revert UnsupportedToken();\n        }\n    }\n\n    /// @notice Get the token address from the Curve token index.\n    /// @param index Curve token index.\n    /// @return Address of the token.\n    function _token(int128 index) private pure returns (address) {\n        if (index == USDC_INDEX) {\n            return address(USDC);\n        } else if (index == USDT_INDEX) {\n            return address(USDT);\n        } else if (index == DAI_INDEX) {\n            return address(DAI);\n        } else {\n            revert InvalidTokenIndex();\n        }\n    }\n\n    /// @notice Get the contract's token balance from the Curve token index.\n    /// @param index Curve token index.\n    /// @return Token balance.\n    function _tokenBalance(int128 index) internal view returns (uint256) {\n        if (_token(index) == YieldManager(address(this)).TOKEN()) {\n            return YieldManager(address(this)).availableBalance();\n        } else {\n            return IERC20(_token(index)).balanceOf(address(this));\n        }\n    }\n\n    /// @notice Convert WAD representation to the token's native decimal representation.\n    ///         USDT and USDC are both 6 decimals and are converted.\n    /// @param wad   Amount in WAD.\n    /// @param index Curve 3Pool index of the token.\n    /// @return result Amount in native decimals representation.\n    function _convertDecimals(uint256 wad, int128 index) internal pure returns (uint256 result) {\n        if (index == USDT_INDEX || index == USDC_INDEX) {\n            result = _wadToUSD(wad);\n        } else {\n            result = wad;\n        }\n    }\n\n    /// @notice Convert value in WAD (18 decimals) to USD (6 decimals).\n    /// @param wad Amount to convert in WAD.\n    /// @return Amount in USD.\n    function _wadToUSD(uint256 wad) internal pure returns (uint256) {\n        return _convertDecimals(wad, WAD_DECIMALS, USD_DECIMALS);\n    }\n\n    /// @notice Convert value in USD (6 decimals) to WAD (18 decimals).\n    /// @param usd Amount to convert in USD.\n    /// @return Amount in WAD.\n    function _usdToWad(uint256 usd) internal pure returns (uint256) {\n        return _convertDecimals(usd, USD_DECIMALS, WAD_DECIMALS);\n    }\n\n    /// @notice Convert value to desired output decimals representation.\n    /// @param input          Input amount.\n    /// @param inputDecimals  Number of decimals in the input.\n    /// @param outputDecimals Desired number of decimals in the output.\n    /// @return `input` in `outputDecimals`.\n    function _convertDecimals(uint256 input, uint256 inputDecimals, uint256 outputDecimals) internal pure returns (uint256) {\n        if (inputDecimals > outputDecimals) {\n            return input / (10 ** (inputDecimals - outputDecimals));\n        } else {\n            return input * (10 ** (outputDecimals - inputDecimals));\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/draft-IERC20Permit.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},{"file_path":"src/L2/ERC20Rebasing.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n\nimport { SharesBase } from \"src/L2/Shares.sol\";\nimport { YieldMode } from \"src/L2/Blast.sol\";\nimport { ERC20PermitUpgradeable } from \"src/L2/ERC20PermitUpgradeable.sol\";\n\n/// @custom:upgradeable\n/// @title ERC20Rebasing\n/// @notice ERC20 implementation with rebasing token balances. There are 3 yield\n/// modes with different rebasing behaviors.\n///\n/// AUTOMATIC dynamically updates the balance as the share price increases.\n///\n/// VOID fixes the balance and exempts the account from receiving yields.\n///\n/// CLAIMABLE fixes the balance and allows the account to claim yields to\n/// another account.\n///\n/// The child implementation is responsible for deciding how the share price is set.\nabstract contract ERC20Rebasing is ERC20PermitUpgradeable, SharesBase, IERC20 {\n    /// @notice Number of decimals.\n    uint8 public immutable decimals;\n\n    /// @notice Name of the token.\n    string public name;\n    /// @notice Symbol of the token.\n    string public symbol;\n\n    /// @notice Mapping that stores the number of shares for each account.\n    mapping(address => uint256) private _shares;\n\n    /// @notice Total number of shares distributed.\n    uint256 internal _totalShares;\n\n    /// @notice Mapping that stores the number of remainder tokens for each account.\n    mapping(address => uint256) private _remainders;\n\n    /// @notice Mapping that stores the number of fixed tokens for each account.\n    mapping(address => uint256) private _fixed;\n\n    /// @notice Total number of non-rebasing tokens.\n    uint256 internal _totalVoidAndRemainders;\n\n    /// @notice Mapping that stores the configured yield mode for each account.\n    mapping(address => YieldMode) private _yieldMode;\n\n    /// @notice Mapping that stores the allowance for a given spender and operator pair.\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    ///         A gap size of 41 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[41] private __gap;\n\n    /// @notice Emitted when an account configures their yield mode.\n    /// @param account   Address of the account.\n    /// @param yieldMode Yield mode that was configured.\n    event Configure(address indexed account, YieldMode yieldMode);\n\n    /// @notice Emitted when a CLAIMABLE account claims their yield.\n    /// @param account   Address of the account.\n    /// @param recipient Address of the recipient.\n    /// @param amount    Amount of yield claimed.\n    event Claim(address indexed account, address indexed recipient, uint256 amount);\n\n    error InsufficientBalance();\n    error InsufficientAllowance();\n    error TransferFromZeroAddress();\n    error TransferToZeroAddress();\n    error ApproveFromZeroAddress();\n    error ApproveToZeroAddress();\n    error ClaimToZeroAddress();\n    error NotClaimableAccount();\n\n    /// @param _decimals Number of decimals.\n    constructor(address _reporter, uint8 _decimals) SharesBase(_reporter) {\n        decimals = _decimals;\n    }\n\n    /// @param _name     Token name.\n    /// @param _symbol   Token symbol.\n    /// @param _price    Initial share price.\n    function __ERC20Rebasing_init(string memory _name, string memory _symbol, uint256 _price) internal onlyInitializing {\n        __ERC20Permit_init(_name);\n        __SharesBase_init({ _price: _price });\n        name = _name;\n        symbol = _symbol;\n    }\n\n    /// @inheritdoc SharesBase\n    function count() public view override returns (uint256) {\n        return _totalShares;\n    }\n\n    /// @notice --- ERC20 Interface ---\n\n    /// @inheritdoc IERC20\n    function totalSupply() external view returns (uint256) {\n        return price * _totalShares + _totalVoidAndRemainders;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account)\n        public\n        view\n        virtual\n        returns (uint256 value)\n    {\n        YieldMode yieldMode = _yieldMode[account];\n        if (yieldMode == YieldMode.AUTOMATIC) {\n            value = _computeShareValue(_shares[account], _remainders[account]);\n        } else {\n            value = _fixed[account];\n        }\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender)\n        public\n        view\n        virtual\n        returns (uint256)\n    {\n        return _allowances[owner][spender];\n    }\n\n    /// @inheritdoc IERC20\n    function transfer(address to, uint256 amount)\n        public\n        virtual\n        returns (bool)\n    {\n        _transfer(msg.sender, to, amount);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function approve(address spender, uint256 amount)\n        public\n        virtual\n        returns (bool)\n    {\n        address owner = msg.sender;\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        _spendAllowance(from, msg.sender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /// @notice --- Blast Interface ---\n\n    /// @notice Query an account's configured yield mode.\n    /// @param account Address to query the configuration.\n    /// @return Configured yield mode.\n    function getConfiguration(address account) public view returns (YieldMode) {\n        return _yieldMode[account];\n    }\n\n    /// @notice Query an CLAIMABLE account's claimable yield.\n    /// @param account Address to query the claimable amount.\n    /// @return amount Claimable amount.\n    function getClaimableAmount(address account) public view returns (uint256) {\n        if (getConfiguration(account) != YieldMode.CLAIMABLE) {\n            revert NotClaimableAccount();\n        }\n\n        uint256 shareValue = _computeShareValue(_shares[account], _remainders[account]);\n        return shareValue - _fixed[account];\n    }\n\n    /// @notice Claim yield from a CLAIMABLE account and send to\n    ///         a recipient.\n    /// @param recipient Address to receive the claimed balance.\n    /// @param amount    Amount to claim.\n    /// @return Amount claimed.\n    function claim(address recipient, uint256 amount) external returns (uint256) {\n        address account = msg.sender;\n        if (recipient == address(0)) {\n            revert ClaimToZeroAddress();\n        }\n\n        if (getConfiguration(account) != YieldMode.CLAIMABLE) {\n            revert NotClaimableAccount();\n        }\n\n        uint256 shareValue = _computeShareValue(_shares[account], _remainders[account]);\n\n        uint256 claimableAmount = shareValue - _fixed[account];\n        if (amount > claimableAmount) {\n            revert InsufficientBalance();\n        }\n\n        (uint256 newShares, uint256 newRemainder) = _computeSharesAndRemainder(shareValue - amount);\n\n        _updateBalance(account, newShares, newRemainder, _fixed[account]);\n        _deposit(recipient, amount);\n\n        emit Claim(msg.sender, recipient, amount);\n\n        return amount;\n    }\n\n    /// @notice Change the yield mode of the caller and update the\n    ///         balance to reflect the configuration.\n    /// @param yieldMode Yield mode to configure\n    /// @return Current user balance\n    function configure(YieldMode yieldMode) external returns (uint256) {\n        _configure(msg.sender, yieldMode);\n\n        emit Configure(msg.sender, yieldMode);\n\n        return balanceOf(msg.sender);\n    }\n\n    /// @notice Moves `amount` of tokens from `from` to `to`.\n    /// @param from   Address of the sender.\n    /// @param to     Address of the recipient.\n    /// @param amount Amount of tokens to send.\n    function _transfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {\n        if (from == address(0)) revert TransferFromZeroAddress();\n        if (to == address(0)) revert TransferToZeroAddress();\n\n        _withdraw(from, amount);\n        _deposit(to, amount);\n\n        emit Transfer(from, to, amount);\n    }\n\n    /// @notice Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n    /// @param owner   Address of the owner.\n    /// @param spender Address of the spender.\n    /// @param amount  Amount of tokens to approve.\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal override {\n        if (owner == address(0)) revert ApproveFromZeroAddress();\n        if (spender == address(0)) revert ApproveToZeroAddress();\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /// @notice Updates `owner` s allowance for `spender` based on spent `amount`.\n    /// @param owner   Address of the owner.\n    /// @param spender Address of the spender.\n    /// @param amount  Amount of tokens to spender.\n    function _spendAllowance(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            if (amount > currentAllowance) revert InsufficientAllowance();\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /// @notice Deposit to an account.\n    /// @param account Address of the account to deposit to.\n    /// @param amount  Amount to deposit to the account.\n    function _deposit(address account, uint256 amount) internal {\n        uint256 balanceAfter = balanceOf(account) + amount;\n        _setBalance(account, balanceAfter, false);\n\n        /// If the user is configured as VOID, then the amount\n        /// is added to the total voided funds.\n        YieldMode yieldMode = getConfiguration(account);\n        if (yieldMode == YieldMode.VOID) {\n            _totalVoidAndRemainders += amount;\n        }\n    }\n\n    /// @notice Withdraw from an account.\n    /// @param account Address of the account to withdraw from.\n    /// @param amount  Amount to withdraw to the account.\n    function _withdraw(address account, uint256 amount) internal {\n        uint256 balance = balanceOf(account);\n        if (amount > balance) {\n            revert InsufficientBalance();\n        }\n\n        unchecked {\n            _setBalance(account, balance - amount, false);\n        }\n\n        /// If the user is configured as VOID, then the amount\n        /// is deducted from the total voided funds.\n        YieldMode yieldMode = getConfiguration(account);\n        if (yieldMode == YieldMode.VOID) {\n            _totalVoidAndRemainders -= amount;\n        }\n    }\n\n    /// @notice Configures a new yield mode for an account and updates\n    ///         the balance storage to reflect the change.\n    /// @param account      Address of the account to configure.\n    /// @param newYieldMode New yield mode to configure.\n    function _configure(address account, YieldMode newYieldMode) internal {\n        YieldMode prevYieldMode = getConfiguration(account);\n\n        uint256 balance;\n        if (prevYieldMode == YieldMode.CLAIMABLE) {\n            /// If the balance is claimable, we need to use their share balance so they\n            /// don't lose their claimable yield.\n            balance = _computeShareValue(_shares[account], _remainders[account]);\n        } else {\n            balance = balanceOf(account);\n        }\n\n        _yieldMode[account] = newYieldMode;\n\n        uint256 prevFixed = _fixed[account];\n\n        _setBalance(account, balance, true);\n\n        /// If the previous yield mode was VOID, then the amount\n        /// is deducted from the total voided funds.\n        if (prevYieldMode == YieldMode.VOID) {\n            _totalVoidAndRemainders -= prevFixed;\n        }\n\n        /// If the new yield mode is VOID, then the amount\n        /// is added to the total voided funds.\n        if (newYieldMode == YieldMode.VOID) {\n            _totalVoidAndRemainders += balance;\n        }\n    }\n\n    /// @notice Sets the balance of an account according to its yield mode\n    ///         configuration.\n    /// @param account           Address of the account to set the balance of.\n    /// @param amount            Balance to set for the account.\n    /// @param resetClaimable    If the account is CLAIMABLE, true if the share\n    ///                          balance should be set to the amount. Should only be true when\n    ///                          configuring the account.\n    function _setBalance(address account, uint256 amount, bool resetClaimable) internal {\n        uint256 newShares; uint256 newRemainder; uint256 newFixed;\n        YieldMode yieldMode = getConfiguration(account);\n        if (yieldMode == YieldMode.AUTOMATIC) {\n            (newShares, newRemainder) = _computeSharesAndRemainder(amount);\n        } else if (yieldMode == YieldMode.VOID) {\n            newFixed = amount;\n        } else if (yieldMode == YieldMode.CLAIMABLE) {\n            newFixed = amount;\n            uint256 shareValue = amount;\n            if (!resetClaimable) {\n                /// In order to not reset the claimable balance, we have to compute\n                /// the user's current share balance and add or subtract the change in\n                /// fixed balance before computing the new shares balance parameters.\n                shareValue = _computeShareValue(_shares[account], _remainders[account]);\n                shareValue = shareValue + amount - _fixed[account];\n            }\n            (newShares, newRemainder) = _computeSharesAndRemainder(shareValue);\n        }\n\n        _updateBalance(account, newShares, newRemainder, newFixed);\n    }\n\n    /// @notice Update the balance parameters of an account and appropriately refresh the global sums\n    ///         to reflect the change of allocation.\n    /// @param account      Address of account to update.\n    /// @param newShares    New shares value for account.\n    /// @param newRemainder New remainder value for account.\n    /// @param newFixed     New fixed value for account.\n    function _updateBalance(address account, uint256 newShares, uint256 newRemainder, uint256 newFixed) internal {\n        _totalShares = _totalShares + newShares - _shares[account];\n        _totalVoidAndRemainders = _totalVoidAndRemainders + newRemainder - _remainders[account];\n\n        _shares[account] = newShares;\n        _remainders[account] = newRemainder;\n        _fixed[account] = newFixed;\n    }\n\n    /// @notice Convert nominal value to number of shares with remainder.\n    /// @param value Amount to convert to shares (wad).\n    /// @return shares Number of shares (wad), remainder Remainder (wad).\n    function _computeSharesAndRemainder(uint256 value) internal view returns (uint256 shares, uint256 remainder) {\n        if (price == 0) {\n            remainder = value;\n        } else {\n            shares = value / price;\n            remainder = value % price;\n        }\n    }\n\n    /// @notice Compute nominal value from number of shares.\n    /// @param shares     Number of shares (wad).\n    /// @param remainders Amount of remainder (wad).\n    /// @return value (wad).\n    function _computeShareValue(uint256 shares, uint256 remainders) internal view returns (uint256) {\n        return price * shares + remainders;\n    }\n}\n"},{"file_path":"src/mainnet-bridge/DelegateCalls.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\ninterface IDelegateCalls {\n    function payInsurancePremium(uint256) external;\n    function withdrawFromInsurance(uint256) external;\n    function stake(uint256) external;\n    function unstake(uint256) external returns (uint256, uint256);\n    function preCommitYieldReportDelegateCallHook() external;\n}\n\nabstract contract DelegateCalls {\n    function _delegatecall_payInsurancePremium(address provider, uint256 arg) internal {\n        (bool success,) = provider.delegatecall(\n            abi.encodeCall(IDelegateCalls.payInsurancePremium, (arg))\n        );\n        require(success, \"delegatecall failed\");\n    }\n\n    function _delegatecall_withdrawFromInsurance(address provider, uint256 arg) internal {\n        (bool success,) = provider.delegatecall(\n            abi.encodeCall(IDelegateCalls.withdrawFromInsurance, (arg))\n        );\n        require(success, \"delegatecall failed\");\n    }\n\n    function _delegatecall_stake(address provider, uint256 arg) internal {\n        (bool success,) = provider.delegatecall(\n            abi.encodeCall(IDelegateCalls.stake, (arg))\n        );\n        require(success, \"delegatecall failed\");\n    }\n\n    function _delegatecall_unstake(address provider, uint256 arg) internal returns (uint256, uint256) {\n        (bool success, bytes memory res) = provider.delegatecall(\n            abi.encodeCall(IDelegateCalls.unstake, (arg))\n        );\n        require(success, \"delegatecall failed\");\n        return abi.decode(res, (uint256, uint256));\n    }\n\n    function _delegatecall_preCommitYieldReportDelegateCallHook(address provider) internal {\n        (bool success,) = provider.delegatecall(\n            abi.encodeCall(IDelegateCalls.preCommitYieldReportDelegateCallHook, ())\n        );\n        require(success, \"delegatecall failed\");\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20PermitUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC20_init_unchained(name_, symbol_);\n    }\n\n    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(address from, address to, uint256 amount) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n            // decrementing then incrementing.\n            _balances[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        unchecked {\n            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n            _balances[account] += amount;\n        }\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n            // Overflow not possible: amount <= accountBalance <= totalSupply.\n            _totalSupply -= amount;\n        }\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[45] private __gap;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.2) (utils/introspection/ERC165Checker.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Library used to query support of an interface declared via {IERC165}.\n *\n * Note that these functions return the actual result of the query: they do not\n * `revert` if an interface is not supported. It is up to the caller to decide\n * what to do in these cases.\n */\nlibrary ERC165Checker {\n    // As per the EIP-165 spec, no interface should ever match 0xffffffff\n    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;\n\n    /**\n     * @dev Returns true if `account` supports the {IERC165} interface,\n     */\n    function supportsERC165(address account) internal view returns (bool) {\n        // Any contract that implements ERC165 must explicitly indicate support of\n        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n        return\n            _supportsERC165Interface(account, type(IERC165).interfaceId) &&\n            !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\n    }\n\n    /**\n     * @dev Returns true if `account` supports the interface defined by\n     * `interfaceId`. Support for {IERC165} itself is queried automatically.\n     *\n     * See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {\n        // query support of both ERC165 as per the spec and support of _interfaceId\n        return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);\n    }\n\n    /**\n     * @dev Returns a boolean array where each value corresponds to the\n     * interfaces passed in and whether they're supported or not. This allows\n     * you to batch check interfaces for a contract where your expectation\n     * is that some interfaces may not be supported.\n     *\n     * See {IERC165-supportsInterface}.\n     *\n     * _Available since v3.4._\n     */\n    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)\n        internal\n        view\n        returns (bool[] memory)\n    {\n        // an array of booleans corresponding to interfaceIds and whether they're supported or not\n        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n        // query support of ERC165 itself\n        if (supportsERC165(account)) {\n            // query support of each interface in interfaceIds\n            for (uint256 i = 0; i < interfaceIds.length; i++) {\n                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);\n            }\n        }\n\n        return interfaceIdsSupported;\n    }\n\n    /**\n     * @dev Returns true if `account` supports all the interfaces defined in\n     * `interfaceIds`. Support for {IERC165} itself is queried automatically.\n     *\n     * Batch-querying can lead to gas savings by skipping repeated checks for\n     * {IERC165} support.\n     *\n     * See {IERC165-supportsInterface}.\n     */\n    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n        // query support of ERC165 itself\n        if (!supportsERC165(account)) {\n            return false;\n        }\n\n        // query support of each interface in _interfaceIds\n        for (uint256 i = 0; i < interfaceIds.length; i++) {\n            if (!_supportsERC165Interface(account, interfaceIds[i])) {\n                return false;\n            }\n        }\n\n        // all interfaces supported\n        return true;\n    }\n\n    /**\n     * @notice Query if a contract implements an interface, does not check ERC165 support\n     * @param account The address of the contract to query for support of an interface\n     * @param interfaceId The interface identifier, as specified in ERC-165\n     * @return true if the contract at account indicates support of the interface with\n     * identifier interfaceId, false otherwise\n     * @dev Assumes that account contains a contract that supports ERC165, otherwise\n     * the behavior of this method is undefined. This precondition can be checked\n     * with {supportsERC165}.\n     * Interface identification is specified in ERC-165.\n     */\n    function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {\n        // prepare call\n        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);\n\n        // perform static call\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly {\n            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0x00)\n        }\n\n        return success && returnSize >= 0x20 && returnValue > 0;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n     * initialization step. This is essential to configure modules that are added through upgrades and that require\n     * initialization.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized < type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n}\n"},{"file_path":"src/L1/OptimismPortal.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { L2OutputOracle } from \"src/L1/L2OutputOracle.sol\";\nimport { SystemConfig } from \"src/L1/SystemConfig.sol\";\nimport { Constants } from \"src/libraries/Constants.sol\";\nimport { Types } from \"src/libraries/Types.sol\";\nimport { Hashing } from \"src/libraries/Hashing.sol\";\nimport { SecureMerkleTrie } from \"src/libraries/trie/SecureMerkleTrie.sol\";\nimport { AddressAliasHelper } from \"src/vendor/AddressAliasHelper.sol\";\nimport { ResourceMetering } from \"src/L1/ResourceMetering.sol\";\nimport { ISemver } from \"src/universal/ISemver.sol\";\nimport { ETHYieldManager } from \"src/mainnet-bridge/ETHYieldManager.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\n\n/// @custom:proxied\n/// @title OptimismPortal\n/// @notice The OptimismPortal is a low-level contract responsible for passing messages between L1\n///         and L2. Messages sent directly to the OptimismPortal have no form of replayability.\n///         Users are encouraged to use the L1CrossDomainMessenger for a higher-level interface.\ncontract OptimismPortal is Initializable, ResourceMetering, ISemver {\n    /// @notice Represents a proven withdrawal.\n    /// @custom:field outputRoot    Root of the L2 output this was proven against.\n    /// @custom:field timestamp     Timestamp at which the withdrawal was proven.\n    /// @custom:field l2OutputIndex Index of the output this was proven against.\n    struct ProvenWithdrawal {\n        bytes32 outputRoot;\n        uint128 timestamp;\n        uint128 l2OutputIndex;\n        uint256 requestId;\n    }\n\n    /// @notice Version of the deposit event.\n    uint256 internal constant DEPOSIT_VERSION = 0;\n\n    /// @notice The L2 gas limit set when eth is deposited using the receive() function.\n    uint64 internal constant RECEIVE_DEFAULT_GAS_LIMIT = 100_000;\n\n    /// @notice The L1 gas limit set when sending eth to the YieldManager.\n    uint64 internal constant SEND_DEFAULT_GAS_LIMIT = 100_000;\n\n    /// @notice Address of the L2 account which initiated a withdrawal in this transaction.\n    ///         If the address of this variable is the default L2 sender address, then we\n    ///         are NOT inside of a call to finalizeWithdrawalTransaction.\n    address public l2Sender;\n\n    /// @notice A list of withdrawal hashes which have been successfully finalized.\n    mapping(bytes32 => bool) public finalizedWithdrawals;\n\n    /// @notice A mapping of withdrawal hashes to `ProvenWithdrawal` data.\n    mapping(bytes32 => ProvenWithdrawal) public provenWithdrawals;\n\n    /// @notice Determines if cross domain messaging is paused.\n    ///         When set to true, withdrawals are paused.\n    ///         This may be removed in the future.\n    bool public paused;\n\n    /// @notice Address of the L2OutputOracle contract.\n    /// @custom:network-specific\n    L2OutputOracle public l2Oracle;\n\n    /// @notice Address of the SystemConfig contract.\n    /// @custom:network-specific\n    SystemConfig public systemConfig;\n\n    /// @notice Address that has the ability to pause and unpause withdrawals.\n    /// @custom:network-specific\n    address public guardian;\n\n    /// @notice Address of the ETH yield manager.\n    ETHYieldManager public yieldManager;\n\n    /// @notice Emitted when a transaction is deposited from L1 to L2.\n    ///         The parameters of this event are read by the rollup node and used to derive deposit\n    ///         transactions on L2.\n    /// @param from       Address that triggered the deposit transaction.\n    /// @param to         Address that the deposit transaction is directed to.\n    /// @param version    Version of this deposit transaction event.\n    /// @param opaqueData ABI encoded deposit data to be parsed off-chain.\n    event TransactionDeposited(address indexed from, address indexed to, uint256 indexed version, bytes opaqueData);\n\n    /// @notice Emitted when a withdrawal transaction is proven.\n    /// @param withdrawalHash Hash of the withdrawal transaction.\n    /// @param from           Address that triggered the withdrawal transaction.\n    /// @param to             Address that the withdrawal transaction is directed to.\n    /// @param requestId      Id of the withdrawal request\n    event WithdrawalProven(bytes32 indexed withdrawalHash, address indexed from, address indexed to, uint256 requestId);\n\n    /// @notice Emitted when a withdrawal transaction is finalized.\n    /// @param withdrawalHash Hash of the withdrawal transaction.\n    /// @param hintId is the checkpoint ID produce by YieldManager\n    /// @param success        Whether the withdrawal transaction was successful.\n    event WithdrawalFinalized(bytes32 indexed withdrawalHash, uint256 indexed hintId, bool success);\n\n    /// @notice Emitted when the pause is triggered.\n    /// @param account Address of the account triggering the pause.\n    event Paused(address account);\n\n    /// @notice Emitted when the pause is lifted.\n    /// @param account Address of the account triggering the unpause.\n    event Unpaused(address account);\n\n    /// @notice Reverts when paused.\n    modifier whenNotPaused() {\n        require(paused == false, \"OptimismPortal: paused\");\n        _;\n    }\n\n    /// @notice Semantic version.\n    /// @custom:semver 1.10.0\n    string public constant version = \"1.10.0\";\n\n    /// @notice Constructs the OptimismPortal contract.\n    constructor() {\n        initialize({\n            _l2Oracle: L2OutputOracle(address(0)),\n            _guardian: address(0),\n            _systemConfig: SystemConfig(address(0)),\n            _paused: true,\n            _yieldManager: ETHYieldManager(payable(address(0)))\n        });\n    }\n\n    /// @notice Initializer.\n    /// @param _l2Oracle Address of the L2OutputOracle contract.\n    /// @param _guardian Address that can pause withdrawals.\n    /// @param _paused Sets the contract's pausability state.\n    /// @param _systemConfig Address of the SystemConfig contract.\n    function initialize(\n        L2OutputOracle _l2Oracle,\n        address _guardian,\n        SystemConfig _systemConfig,\n        bool _paused,\n        ETHYieldManager _yieldManager\n    )\n        public\n        reinitializer(Constants.INITIALIZER)\n    {\n        if (l2Sender == address(0)) {\n            l2Sender = Constants.DEFAULT_L2_SENDER;\n        }\n        l2Oracle = _l2Oracle;\n        systemConfig = _systemConfig;\n        guardian = _guardian;\n        paused = _paused;\n        yieldManager = _yieldManager;\n        __ResourceMetering_init();\n    }\n\n    /// @notice Getter for the L2OutputOracle\n    /// @custom:legacy\n    function L2_ORACLE() external view returns (L2OutputOracle) {\n        return l2Oracle;\n    }\n\n    /// @notice Getter for the SystemConfig\n    /// @custom:legacy\n    function SYSTEM_CONFIG() external view returns (SystemConfig) {\n        return systemConfig;\n    }\n\n    /// @notice Getter for the Guardian\n    /// @custom:legacy\n    function GUARDIAN() external view returns (address) {\n        return guardian;\n    }\n\n    /// @notice Pauses withdrawals.\n    function pause() external {\n        require(msg.sender == guardian, \"OptimismPortal: only guardian can pause\");\n        paused = true;\n        emit Paused(msg.sender);\n    }\n\n    /// @notice Unpauses withdrawals.\n    function unpause() external {\n        require(msg.sender == guardian, \"OptimismPortal: only guardian can unpause\");\n        paused = false;\n        emit Unpaused(msg.sender);\n    }\n\n    /// @notice Computes the minimum gas limit for a deposit.\n    ///         The minimum gas limit linearly increases based on the size of the calldata.\n    ///         This is to prevent users from creating L2 resource usage without paying for it.\n    ///         This function can be used when interacting with the portal to ensure forwards\n    ///         compatibility.\n    /// @param _byteCount Number of bytes in the calldata.\n    /// @return The minimum gas limit for a deposit.\n    function minimumGasLimit(uint64 _byteCount) public pure returns (uint64) {\n        return _byteCount * 16 + 21000;\n    }\n\n    /// @notice Accepts value so that users can send ETH directly to this contract and have the\n    ///         funds be deposited to their address on L2. This is intended as a convenience\n    ///         function for EOAs. Contracts should call the depositTransaction() function directly\n    ///         otherwise any deposited funds will be lost due to address aliasing.\n    // solhint-disable-next-line ordering\n    receive() external payable {\n        if (msg.sender != address(yieldManager)) {\n            depositTransaction(msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, false, bytes(\"\"));\n        }\n    }\n\n    /// @notice Getter for the resource config.\n    ///         Used internally by the ResourceMetering contract.\n    ///         The SystemConfig is the source of truth for the resource config.\n    /// @return ResourceMetering ResourceConfig\n    function _resourceConfig() internal view override returns (ResourceMetering.ResourceConfig memory) {\n        return systemConfig.resourceConfig();\n    }\n\n    /// @notice Proves a withdrawal transaction.\n    /// @param _tx              Withdrawal transaction to finalize.\n    /// @param _l2OutputIndex   L2 output index to prove against.\n    /// @param _outputRootProof Inclusion proof of the L2ToL1MessagePasser contract's storage root.\n    /// @param _withdrawalProof Inclusion proof of the withdrawal in L2ToL1MessagePasser contract.\n    function proveWithdrawalTransaction(\n        Types.WithdrawalTransaction memory _tx,\n        uint256 _l2OutputIndex,\n        Types.OutputRootProof calldata _outputRootProof,\n        bytes[] calldata _withdrawalProof\n    )\n        external\n        whenNotPaused\n    {\n        // Prevent users from creating a deposit transaction where this address is the message\n        // sender on L2. Because this is checked here, we do not need to check again in\n        // `finalizeWithdrawalTransaction`.\n        require(_tx.target != address(this), \"OptimismPortal: you cannot send messages to the portal contract\");\n\n        // Get the output root and load onto the stack to prevent multiple mloads. This will\n        // revert if there is no output root for the given block number.\n        bytes32 outputRoot = l2Oracle.getL2Output(_l2OutputIndex).outputRoot;\n\n        // Verify that the output root can be generated with the elements in the proof.\n        require(\n            outputRoot == Hashing.hashOutputRootProof(_outputRootProof), \"OptimismPortal: invalid output root proof\"\n        );\n\n        // Load the ProvenWithdrawal into memory, using the withdrawal hash as a unique identifier.\n        bytes32 withdrawalHash = Hashing.hashWithdrawal(_tx);\n        ProvenWithdrawal memory provenWithdrawal = provenWithdrawals[withdrawalHash];\n\n        // We generally want to prevent users from proving the same withdrawal multiple times\n        // because each successive proof will update the timestamp. A malicious user can take\n        // advantage of this to prevent other users from finalizing their withdrawal. However,\n        // since withdrawals are proven before an output root is finalized, we need to allow users\n        // to re-prove their withdrawal only in the case that the output root for their specified\n        // output index has been updated.\n        require(\n            provenWithdrawal.timestamp == 0\n                || l2Oracle.getL2Output(provenWithdrawal.l2OutputIndex).outputRoot != provenWithdrawal.outputRoot,\n            \"OptimismPortal: withdrawal hash has already been proven\"\n        );\n\n        // Compute the storage slot of the withdrawal hash in the L2ToL1MessagePasser contract.\n        // Refer to the Solidity documentation for more information on how storage layouts are\n        // computed for mappings.\n        bytes32 storageKey = keccak256(\n            abi.encode(\n                withdrawalHash,\n                uint256(0) // The withdrawals mapping is at the first slot in the layout.\n            )\n        );\n\n        // Verify that the hash of this withdrawal was stored in the L2toL1MessagePasser contract\n        // on L2. If this is true, under the assumption that the SecureMerkleTrie does not have\n        // bugs, then we know that this withdrawal was actually triggered on L2 and can therefore\n        // be relayed on L1.\n        require(\n            SecureMerkleTrie.verifyInclusionProof(\n                abi.encode(storageKey), hex\"01\", _withdrawalProof, _outputRootProof.messagePasserStorageRoot\n            ),\n            \"OptimismPortal: invalid withdrawal inclusion proof\"\n        );\n\n        // Blast: request ether withdrawal from the yield manager. Should not request a withdrawal\n        // when the withdrawal is being re-proven.\n        uint256 requestId;\n        if (_tx.value > 0 && provenWithdrawal.timestamp == 0) {\n            requestId = yieldManager.requestWithdrawal(_tx.value);\n        } else {\n            // If withdrawal is being re-proven, then set original requestId.\n            requestId = provenWithdrawal.requestId;\n        }\n\n        require(_tx.target != address(yieldManager), \"OptimismPortal: unauthorized call to yield manager\");\n\n        // Designate the withdrawalHash as proven by storing the `outputRoot`, `timestamp`, and\n        // `l2BlockNumber` in the `provenWithdrawals` mapping. A `withdrawalHash` can only be\n        // proven once unless it is submitted again with a different outputRoot.\n        provenWithdrawals[withdrawalHash] = ProvenWithdrawal({\n            outputRoot: outputRoot,\n            timestamp: uint128(block.timestamp),\n            l2OutputIndex: uint128(_l2OutputIndex),\n            requestId: requestId\n        });\n\n        // Emit a `WithdrawalProven` event.\n        emit WithdrawalProven(withdrawalHash, _tx.sender, _tx.target, requestId);\n    }\n\n    /// @notice Finalizes a withdrawal transaction.\n    /// @param hintId Hint ID of the withdrawal transaction to finalize. The caller can find this\n    ///               value by calling ETHYieldManager.findCheckpointHint().\n    /// @param _tx Withdrawal transaction to finalize.\n    function finalizeWithdrawalTransaction(uint256 hintId, Types.WithdrawalTransaction memory _tx) external whenNotPaused {\n        // Make sure that the l2Sender has not yet been set. The l2Sender is set to a value other\n        // than the default value when a withdrawal transaction is being finalized. This check is\n        // a defacto reentrancy guard.\n        require(\n            l2Sender == Constants.DEFAULT_L2_SENDER, \"OptimismPortal: can only trigger one withdrawal per transaction\"\n        );\n\n        // Grab the proven withdrawal from the `provenWithdrawals` map.\n        bytes32 withdrawalHash = Hashing.hashWithdrawal(_tx);\n        ProvenWithdrawal memory provenWithdrawal = provenWithdrawals[withdrawalHash];\n\n        // A withdrawal can only be finalized if it has been proven. We know that a withdrawal has\n        // been proven at least once when its timestamp is non-zero. Unproven withdrawals will have\n        // a timestamp of zero.\n        require(provenWithdrawal.timestamp != 0, \"OptimismPortal: withdrawal has not been proven yet\");\n\n        // As a sanity check, we make sure that the proven withdrawal's timestamp is greater than\n        // starting timestamp inside the L2OutputOracle. Not strictly necessary but extra layer of\n        // safety against weird bugs in the proving step.\n        require(\n            provenWithdrawal.timestamp >= l2Oracle.startingTimestamp(),\n            \"OptimismPortal: withdrawal timestamp less than L2 Oracle starting timestamp\"\n        );\n\n        // A proven withdrawal must wait at least the finalization period before it can be\n        // finalized. This waiting period can elapse in parallel with the waiting period for the\n        // output the withdrawal was proven against. In effect, this means that the minimum\n        // withdrawal time is proposal submission time + finalization period.\n        require(\n            _isFinalizationPeriodElapsed(provenWithdrawal.timestamp),\n            \"OptimismPortal: proven withdrawal finalization period has not elapsed\"\n        );\n\n        // Grab the OutputProposal from the L2OutputOracle, will revert if the output that\n        // corresponds to the given index has not been proposed yet.\n        Types.OutputProposal memory proposal = l2Oracle.getL2Output(provenWithdrawal.l2OutputIndex);\n\n        // Check that the output root that was used to prove the withdrawal is the same as the\n        // current output root for the given output index. An output root may change if it is\n        // deleted by the challenger address and then re-proposed.\n        require(\n            proposal.outputRoot == provenWithdrawal.outputRoot,\n            \"OptimismPortal: output root proven is not the same as current output root\"\n        );\n\n        // Check that the output proposal has also been finalized.\n        require(\n            _isFinalizationPeriodElapsed(proposal.timestamp),\n            \"OptimismPortal: output proposal finalization period has not elapsed\"\n        );\n\n        // Check that this withdrawal has not already been finalized, this is replay protection.\n        require(finalizedWithdrawals[withdrawalHash] == false, \"OptimismPortal: withdrawal has already been finalized\");\n\n        // Mark the withdrawal as finalized so it can't be replayed.\n        finalizedWithdrawals[withdrawalHash] = true;\n\n        // Set the l2Sender so contracts know who triggered this withdrawal on L2.\n        l2Sender = _tx.sender;\n\n        // Blast: claim withdrawal for ether\n        uint256 txValueWithDiscount;\n        if (_tx.value > 0) {\n            uint256 etherBalance = address(this).balance;\n            yieldManager.claimWithdrawal(provenWithdrawal.requestId, hintId);\n            txValueWithDiscount = address(this).balance - etherBalance;\n        }\n\n        // Trigger the call to the target contract. We use a custom low level method\n        // SafeCall.callWithMinGas to ensure two key properties\n        //   1. Target contracts cannot force this call to run out of gas by returning a very large\n        //      amount of data (and this is OK because we don't care about the returndata here).\n        //   2. The amount of gas provided to the execution context of the target is at least the\n        //      gas limit specified by the user. If there is not enough gas in the current context\n        //      to accomplish this, `callWithMinGas` will revert.\n        bool success = SafeCall.callWithMinGas(_tx.target, _tx.gasLimit, txValueWithDiscount, _tx.data);\n\n        // Reset the l2Sender back to the default value.\n        l2Sender = Constants.DEFAULT_L2_SENDER;\n\n        // All withdrawals are immediately finalized. Replayability can\n        // be achieved through contracts built on top of this contract\n        emit WithdrawalFinalized(withdrawalHash, hintId, success);\n\n        // Reverting here is useful for determining the exact gas cost to successfully execute the\n        // sub call to the target contract if the minimum gas limit specified by the user would not\n        // be sufficient to execute the sub call.\n        if (success == false && tx.origin == Constants.ESTIMATION_ADDRESS) {\n            revert(\"OptimismPortal: withdrawal failed\");\n        }\n    }\n\n    /// @notice Accepts deposits of ETH and data, and emits a TransactionDeposited event for use in\n    ///         deriving deposit transactions. Note that if a deposit is made by a contract, its\n    ///         address will be aliased when retrieved using `tx.origin` or `msg.sender`. Consider\n    ///         using the CrossDomainMessenger contracts for a simpler developer experience.\n    /// @param _to         Target address on L2.\n    /// @param _value      ETH value to send to the recipient.\n    /// @param _gasLimit   Amount of L2 gas to purchase by burning gas on L1.\n    /// @param _isCreation Whether or not the transaction is a contract creation.\n    /// @param _data       Data to trigger the recipient with.\n    function depositTransaction(\n        address _to,\n        uint256 _value,\n        uint64 _gasLimit,\n        bool _isCreation,\n        bytes memory _data\n    )\n        public\n        payable\n        metered(_gasLimit)\n    {\n        // Just to be safe, make sure that people specify address(0) as the target when doing\n        // contract creations.\n        if (_isCreation) {\n            require(_to == address(0), \"OptimismPortal: must send to address(0) when creating a contract\");\n        }\n\n        // Prevent depositing transactions that have too small of a gas limit. Users should pay\n        // more for more resource usage.\n        require(_gasLimit >= minimumGasLimit(uint64(_data.length)), \"OptimismPortal: gas limit too small\");\n\n        // Prevent the creation of deposit transactions that have too much calldata. This gives an\n        // upper limit on the size of unsafe blocks over the p2p network. 120kb is chosen to ensure\n        // that the transaction can fit into the p2p network policy of 128kb even though deposit\n        // transactions are not gossipped over the p2p network.\n        require(_data.length <= 120_000, \"OptimismPortal: data too large\");\n\n        // Transform the from-address to its alias if the caller is a contract.\n        address from = msg.sender;\n        if (msg.sender != tx.origin) {\n            from = AddressAliasHelper.applyL1ToL2Alias(msg.sender);\n        }\n\n        // Compute the opaque data that will be emitted as part of the TransactionDeposited event.\n        // We use opaque data so that we can update the TransactionDeposited event in the future\n        // without breaking the current interface.\n        bytes memory opaqueData;\n\n        // Blast: When receiving already staked funds (stETH) to be bridged for ether on L2, we\n        // have to request that `_value` is minted on L2 without an equivalent `msg.value` being\n        // sent in the call. This bypass allows the L1BlastBridge to request `_value` to be minted\n        // in exchange for a deposit of the equivalent amount of a staked ether asset.\n        if (_to == Predeploys.L2_BLAST_BRIDGE) {\n            if (msg.sender != yieldManager.blastBridge() || yieldManager.blastBridge() == address(0)) {\n                // second case is when the blast bridge address has not been set on the yield manager\n                revert(\"OptimismPortal: only the BlastBridge can deposit\");\n            }\n            opaqueData = abi.encodePacked(_value, _value, _gasLimit, _isCreation, _data);\n        } else {\n            opaqueData = abi.encodePacked(msg.value, _value, _gasLimit, _isCreation, _data);\n        }\n\n        // Blast: Send the received ether to the yield manager to handle staking the funds.\n        if (msg.value > 0) {\n            (bool success) = SafeCall.send(address(yieldManager), SEND_DEFAULT_GAS_LIMIT, msg.value);\n            require(success, \"OptimismPortal: ETH transfer to YieldManager failed\");\n        }\n\n        // Emit a TransactionDeposited event so that the rollup node can derive a deposit\n        // transaction for this deposit.\n        emit TransactionDeposited(from, _to, DEPOSIT_VERSION, opaqueData);\n    }\n\n    /// @notice Determine if a given output is finalized.\n    ///         Reverts if the call to L2_ORACLE.getL2Output reverts.\n    ///         Returns a boolean otherwise.\n    /// @param _l2OutputIndex Index of the L2 output to check.\n    /// @return Whether or not the output is finalized.\n    function isOutputFinalized(uint256 _l2OutputIndex) external view returns (bool) {\n        return _isFinalizationPeriodElapsed(l2Oracle.getL2Output(_l2OutputIndex).timestamp);\n    }\n\n    /// @notice Determines whether the finalization period has elapsed with respect to\n    ///         the provided block timestamp.\n    /// @param _timestamp Timestamp to check.\n    /// @return Whether or not the finalization period has elapsed.\n    function _isFinalizationPeriodElapsed(uint256 _timestamp) internal view returns (bool) {\n        return block.timestamp > _timestamp + l2Oracle.FINALIZATION_PERIOD_SECONDS();\n    }\n}\n"},{"file_path":"src/universal/CrossDomainMessenger.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { Hashing } from \"src/libraries/Hashing.sol\";\nimport { Encoding } from \"src/libraries/Encoding.sol\";\nimport { Constants } from \"src/libraries/Constants.sol\";\n\n/// @custom:legacy\n/// @title CrossDomainMessengerLegacySpacer0\n/// @notice Contract only exists to add a spacer to the CrossDomainMessenger where the\n///         libAddressManager variable used to exist. Must be the first contract in the inheritance\n///         tree of the CrossDomainMessenger.\ncontract CrossDomainMessengerLegacySpacer0 {\n    /// @custom:legacy\n    /// @custom:spacer libAddressManager\n    /// @notice Spacer for backwards compatibility.\n    address private spacer_0_0_20;\n}\n\n/// @custom:legacy\n/// @title CrossDomainMessengerLegacySpacer1\n/// @notice Contract only exists to add a spacer to the CrossDomainMessenger where the\n///         PausableUpgradable and OwnableUpgradeable variables used to exist. Must be\n///         the third contract in the inheritance tree of the CrossDomainMessenger.\ncontract CrossDomainMessengerLegacySpacer1 {\n    /// @custom:legacy\n    /// @custom:spacer ContextUpgradable's __gap\n    /// @notice Spacer for backwards compatibility. Comes from OpenZeppelin\n    ///         ContextUpgradable.\n    uint256[50] private spacer_1_0_1600;\n\n    /// @custom:legacy\n    /// @custom:spacer OwnableUpgradeable's _owner\n    /// @notice Spacer for backwards compatibility.\n    ///         Come from OpenZeppelin OwnableUpgradeable.\n    address private spacer_51_0_20;\n\n    /// @custom:legacy\n    /// @custom:spacer OwnableUpgradeable's __gap\n    /// @notice Spacer for backwards compatibility. Comes from OpenZeppelin\n    ///         OwnableUpgradeable.\n    uint256[49] private spacer_52_0_1568;\n\n    /// @custom:legacy\n    /// @custom:spacer PausableUpgradable's _paused\n    /// @notice Spacer for backwards compatibility. Comes from OpenZeppelin\n    ///         PausableUpgradable.\n    bool private spacer_101_0_1;\n\n    /// @custom:legacy\n    /// @custom:spacer PausableUpgradable's __gap\n    /// @notice Spacer for backwards compatibility. Comes from OpenZeppelin\n    ///         PausableUpgradable.\n    uint256[49] private spacer_102_0_1568;\n\n    /// @custom:legacy\n    /// @custom:spacer ReentrancyGuardUpgradeable's `_status` field.\n    /// @notice Spacer for backwards compatibility.\n    uint256 private spacer_151_0_32;\n\n    /// @custom:legacy\n    /// @custom:spacer ReentrancyGuardUpgradeable's __gap\n    /// @notice Spacer for backwards compatibility.\n    uint256[49] private spacer_152_0_1568;\n\n    /// @custom:legacy\n    /// @custom:spacer blockedMessages\n    /// @notice Spacer for backwards compatibility.\n    mapping(bytes32 => bool) private spacer_201_0_32;\n\n    /// @custom:legacy\n    /// @custom:spacer relayedMessages\n    /// @notice Spacer for backwards compatibility.\n    mapping(bytes32 => bool) private spacer_202_0_32;\n}\n\n/// @custom:upgradeable\n/// @title CrossDomainMessenger\n/// @notice CrossDomainMessenger is a base contract that provides the core logic for the L1 and L2\n///         cross-chain messenger contracts. It's designed to be a universal interface that only\n///         needs to be extended slightly to provide low-level message passing functionality on each\n///         chain it's deployed on. Currently only designed for message passing between two paired\n///         chains and does not support one-to-many interactions.\n///         Any changes to this contract MUST result in a semver bump for contracts that inherit it.\nabstract contract CrossDomainMessenger is\n    CrossDomainMessengerLegacySpacer0,\n    Initializable,\n    CrossDomainMessengerLegacySpacer1\n{\n    /// @notice Current message version identifier.\n    uint16 public constant MESSAGE_VERSION = 1;\n\n    /// @notice Constant overhead added to the base gas for a message.\n    uint64 public constant RELAY_CONSTANT_OVERHEAD = 200_000;\n\n    /// @notice Numerator for dynamic overhead added to the base gas for a message.\n    uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR = 64;\n\n    /// @notice Denominator for dynamic overhead added to the base gas for a message.\n    uint64 public constant MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR = 63;\n\n    /// @notice Extra gas added to base gas for each byte of calldata in a message.\n    uint64 public constant MIN_GAS_CALLDATA_OVERHEAD = 16;\n\n    /// @notice Gas reserved for performing the external call in `relayMessage`.\n    uint64 public constant RELAY_CALL_OVERHEAD = 40_000;\n\n    /// @notice Gas reserved for finalizing the execution of `relayMessage` after the safe call.\n    uint64 public constant RELAY_RESERVED_GAS = 60_000;\n\n    /// @notice Gas reserved for the execution between the `hasMinGas` check and the external\n    ///         call in `relayMessage`.\n    uint64 public constant RELAY_GAS_CHECK_BUFFER = 5_000;\n\n    /// @notice Address of the paired CrossDomainMessenger contract on the other chain.\n    address public immutable OTHER_MESSENGER;\n\n    /// @notice Mapping of message hashes to boolean receipt values. Note that a message will only\n    ///         be present in this mapping if it has successfully been relayed on this chain, and\n    ///         can therefore not be relayed again.\n    mapping(bytes32 => bool) public successfulMessages;\n\n    /// @notice Address of the sender of the currently executing message on the other chain. If the\n    ///         value of this variable is the default value (0x00000000...dead) then no message is\n    ///         currently being executed. Use the xDomainMessageSender getter which will throw an\n    ///         error if this is the case.\n    address internal xDomainMsgSender;\n\n    /// @notice Nonce for the next message to be sent, without the message version applied. Use the\n    ///         messageNonce getter which will insert the message version into the nonce to give you\n    ///         the actual nonce to be used for the message.\n    uint240 internal msgNonce;\n\n    /// @notice Mapping of message hashes to a boolean if and only if the message has failed to be\n    ///         executed at least once. A message will not be present in this mapping if it\n    ///         successfully executed on the first attempt.\n    mapping(bytes32 => bool) public failedMessages;\n\n    /// @notice Reserve extra slots in the storage layout for future upgrades.\n    ///         A gap size of 42 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[42] private __gap;\n\n    /// @notice Emitted whenever a message is sent to the other chain.\n    /// @param target       Address of the recipient of the message.\n    /// @param sender       Address of the sender of the message.\n    /// @param message      Message to trigger the recipient address with.\n    /// @param messageNonce Unique nonce attached to the message.\n    /// @param gasLimit     Minimum gas limit that the message can be executed with.\n    event SentMessage(address indexed target, address sender, bytes message, uint256 messageNonce, uint256 gasLimit);\n\n    /// @notice Additional event data to emit, required as of Bedrock. Cannot be merged with the\n    ///         SentMessage event without breaking the ABI of this contract, this is good enough.\n    /// @param sender Address of the sender of the message.\n    /// @param value  ETH value sent along with the message to the recipient.\n    event SentMessageExtension1(address indexed sender, uint256 value);\n\n    /// @notice Emitted whenever a message is successfully relayed on this chain.\n    /// @param msgHash Hash of the message that was relayed.\n    event RelayedMessage(bytes32 indexed msgHash);\n\n    /// @notice Emitted whenever a message fails to be relayed on this chain.\n    /// @param msgHash Hash of the message that failed to be relayed.\n    event FailedRelayedMessage(bytes32 indexed msgHash);\n\n    /// @param _otherMessenger Address of the messenger on the paired chain.\n    constructor(address _otherMessenger) {\n        OTHER_MESSENGER = _otherMessenger;\n    }\n\n    /// @notice Sends a message to some target address on the other chain. Note that if the call\n    ///         always reverts, then the message will be unrelayable, and any ETH sent will be\n    ///         permanently locked. The same will occur if the target on the other chain is\n    ///         considered unsafe (see the _isUnsafeTarget() function).\n    /// @param _target      Target contract or wallet address.\n    /// @param _message     Message to trigger the target address with.\n    /// @param _minGasLimit Minimum gas limit that the message can be executed with.\n    function sendMessage(address _target, bytes calldata _message, uint32 _minGasLimit) external payable {\n        // Triggers a message to the other messenger. Note that the amount of gas provided to the\n        // message is the amount of gas requested by the user PLUS the base gas value. We want to\n        // guarantee the property that the call to the target contract will always have at least\n        // the minimum gas limit specified by the user.\n        _sendMessage(\n            OTHER_MESSENGER,\n            baseGas(_message, _minGasLimit),\n            msg.value,\n            abi.encodeWithSelector(\n                this.relayMessage.selector, messageNonce(), msg.sender, _target, msg.value, _minGasLimit, _message\n            )\n        );\n\n        emit SentMessage(_target, msg.sender, _message, messageNonce(), _minGasLimit);\n        emit SentMessageExtension1(msg.sender, msg.value);\n\n        unchecked {\n            ++msgNonce;\n        }\n    }\n\n    /// @notice Relays a message that was sent by the other CrossDomainMessenger contract. Can only\n    ///         be executed via cross-chain call from the other messenger OR if the message was\n    ///         already received once and is currently being replayed.\n    /// @param _nonce       Nonce of the message being relayed.\n    /// @param _sender      Address of the user who sent the message.\n    /// @param _target      Address that the message is targeted at.\n    /// @param _value       ETH value to send with the message.\n    /// @param _minGasLimit Minimum amount of gas that the message can be executed with.\n    /// @param _message     Message to send to the target.\n    function relayMessage(\n        uint256 _nonce,\n        address _sender,\n        address _target,\n        uint256 _value,\n        uint256 _minGasLimit,\n        bytes calldata _message\n    )\n        external\n        payable\n        virtual\n    {\n        (, uint16 version) = Encoding.decodeVersionedNonce(_nonce);\n        require(version < 2, \"CrossDomainMessenger: only version 0 or 1 messages are supported at this time\");\n\n        // If the message is version 0, then it's a migrated legacy withdrawal. We therefore need\n        // to check that the legacy version of the message has not already been relayed.\n        if (version == 0) {\n            bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce);\n            require(successfulMessages[oldHash] == false, \"CrossDomainMessenger: legacy withdrawal already relayed\");\n        }\n\n        // We use the v1 message hash as the unique identifier for the message because it commits\n        // to the value and minimum gas limit of the message.\n        bytes32 versionedHash =\n            Hashing.hashCrossDomainMessageV1(_nonce, _sender, _target, _value, _minGasLimit, _message);\n\n        if (_isOtherMessenger()) {\n            // These properties should always hold when the message is first submitted (as\n            // opposed to being replayed).\n            assert(msg.value == _value);\n            assert(!failedMessages[versionedHash]);\n        } else {\n            require(msg.value == 0, \"CrossDomainMessenger: value must be zero unless message is from a system address\");\n\n            require(failedMessages[versionedHash], \"CrossDomainMessenger: message cannot be replayed\");\n        }\n\n        require(\n            _isUnsafeTarget(_target) == false, \"CrossDomainMessenger: cannot send message to blocked system address\"\n        );\n\n        require(successfulMessages[versionedHash] == false, \"CrossDomainMessenger: message has already been relayed\");\n\n        // If there is not enough gas left to perform the external call and finish the execution,\n        // return early and assign the message to the failedMessages mapping.\n        // We are asserting that we have enough gas to:\n        // 1. Call the target contract (_minGasLimit + RELAY_CALL_OVERHEAD + RELAY_GAS_CHECK_BUFFER)\n        //   1.a. The RELAY_CALL_OVERHEAD is included in `hasMinGas`.\n        // 2. Finish the execution after the external call (RELAY_RESERVED_GAS).\n        //\n        // If `xDomainMsgSender` is not the default L2 sender, this function\n        // is being re-entered. This marks the message as failed to allow it to be replayed.\n        if (\n            !SafeCall.hasMinGas(_minGasLimit, RELAY_RESERVED_GAS + RELAY_GAS_CHECK_BUFFER)\n                || xDomainMsgSender != Constants.DEFAULT_L2_SENDER\n        ) {\n            failedMessages[versionedHash] = true;\n            emit FailedRelayedMessage(versionedHash);\n\n            // Revert in this case if the transaction was triggered by the estimation address. This\n            // should only be possible during gas estimation or we have bigger problems. Reverting\n            // here will make the behavior of gas estimation change such that the gas limit\n            // computed will be the amount required to relay the message, even if that amount is\n            // greater than the minimum gas limit specified by the user.\n            if (tx.origin == Constants.ESTIMATION_ADDRESS) {\n                revert(\"CrossDomainMessenger: failed to relay message\");\n            }\n\n            return;\n        }\n\n        xDomainMsgSender = _sender;\n        bool success = SafeCall.call(_target, gasleft() - RELAY_RESERVED_GAS, _value, _message);\n        xDomainMsgSender = Constants.DEFAULT_L2_SENDER;\n\n        if (success) {\n            // This check is identical to one above, but it ensures that the same message cannot be relayed\n            // twice, and adds a layer of protection against rentrancy.\n            assert(successfulMessages[versionedHash] == false);\n            successfulMessages[versionedHash] = true;\n            emit RelayedMessage(versionedHash);\n        } else {\n            failedMessages[versionedHash] = true;\n            emit FailedRelayedMessage(versionedHash);\n\n            // Revert in this case if the transaction was triggered by the estimation address. This\n            // should only be possible during gas estimation or we have bigger problems. Reverting\n            // here will make the behavior of gas estimation change such that the gas limit\n            // computed will be the amount required to relay the message, even if that amount is\n            // greater than the minimum gas limit specified by the user.\n            if (tx.origin == Constants.ESTIMATION_ADDRESS) {\n                revert(\"CrossDomainMessenger: failed to relay message\");\n            }\n        }\n    }\n\n    /// @notice Retrieves the address of the contract or wallet that initiated the currently\n    ///         executing message on the other chain. Will throw an error if there is no message\n    ///         currently being executed. Allows the recipient of a call to see who triggered it.\n    /// @return Address of the sender of the currently executing message on the other chain.\n    function xDomainMessageSender() external view returns (address) {\n        require(\n            xDomainMsgSender != Constants.DEFAULT_L2_SENDER, \"CrossDomainMessenger: xDomainMessageSender is not set\"\n        );\n\n        return xDomainMsgSender;\n    }\n\n    /// @notice Retrieves the next message nonce. Message version will be added to the upper two\n    ///         bytes of the message nonce. Message version allows us to treat messages as having\n    ///         different structures.\n    /// @return Nonce of the next message to be sent, with added message version.\n    function messageNonce() public view returns (uint256) {\n        return Encoding.encodeVersionedNonce(msgNonce, MESSAGE_VERSION);\n    }\n\n    /// @notice Computes the amount of gas required to guarantee that a given message will be\n    ///         received on the other chain without running out of gas. Guaranteeing that a message\n    ///         will not run out of gas is important because this ensures that a message can always\n    ///         be replayed on the other chain if it fails to execute completely.\n    /// @param _message     Message to compute the amount of required gas for.\n    /// @param _minGasLimit Minimum desired gas limit when message goes to target.\n    /// @return Amount of gas required to guarantee message receipt.\n    function baseGas(bytes calldata _message, uint32 _minGasLimit) public pure returns (uint64) {\n        return\n        // Constant overhead\n        RELAY_CONSTANT_OVERHEAD\n        // Calldata overhead\n        + (uint64(_message.length) * MIN_GAS_CALLDATA_OVERHEAD)\n        // Dynamic overhead (EIP-150)\n        + ((_minGasLimit * MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR) / MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR)\n        // Gas reserved for the worst-case cost of 3/5 of the `CALL` opcode's dynamic gas\n        // factors. (Conservative)\n        + RELAY_CALL_OVERHEAD\n        // Relay reserved gas (to ensure execution of `relayMessage` completes after the\n        // subcontext finishes executing) (Conservative)\n        + RELAY_RESERVED_GAS\n        // Gas reserved for the execution between the `hasMinGas` check and the `CALL`\n        // opcode. (Conservative)\n        + RELAY_GAS_CHECK_BUFFER;\n    }\n\n    /// @notice Initializer.\n    // solhint-disable-next-line func-name-mixedcase\n    function __CrossDomainMessenger_init() internal onlyInitializing {\n        // We only want to set the xDomainMsgSender to the default value if it hasn't been initialized yet,\n        // meaning that this is a fresh contract deployment.\n        // This prevents resetting the xDomainMsgSender to the default value during an upgrade, which would enable\n        // a reentrant withdrawal to sandwich the upgrade replay a withdrawal twice.\n        if (xDomainMsgSender == address(0)) {\n            xDomainMsgSender = Constants.DEFAULT_L2_SENDER;\n        }\n    }\n\n    /// @notice Sends a low-level message to the other messenger. Needs to be implemented by child\n    ///         contracts because the logic for this depends on the network where the messenger is\n    ///         being deployed.\n    /// @param _to       Recipient of the message on the other chain.\n    /// @param _gasLimit Minimum gas limit the message can be executed with.\n    /// @param _value    Amount of ETH to send with the message.\n    /// @param _data     Message data.\n    function _sendMessage(address _to, uint64 _gasLimit, uint256 _value, bytes memory _data) internal virtual;\n\n    /// @notice Checks whether the message is coming from the other messenger. Implemented by child\n    ///         contracts because the logic for this depends on the network where the messenger is\n    ///         being deployed.\n    /// @return Whether the message is coming from the other messenger.\n    function _isOtherMessenger() internal view virtual returns (bool);\n\n    /// @notice Checks whether a given call target is a system address that could cause the\n    ///         messenger to peform an unsafe action. This is NOT a mechanism for blocking user\n    ///         addresses. This is ONLY used to prevent the execution of messages to specific\n    ///         system addresses that could cause security issues, e.g., having the\n    ///         CrossDomainMessenger send messages to itself.\n    /// @param _target Address of the contract to check.\n    /// @return Whether or not the address is an unsafe system address.\n    function _isUnsafeTarget(address _target) internal view virtual returns (bool);\n}\n"},{"file_path":"src/L2/USDB.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\nimport { IERC165 } from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\nimport { ERC20Rebasing } from \"src/L2/ERC20Rebasing.sol\";\nimport { SharesBase } from \"src/L2/Shares.sol\";\nimport { CrossDomainMessenger } from \"src/universal/CrossDomainMessenger.sol\";\nimport { StandardBridge } from \"src/universal/StandardBridge.sol\";\nimport { IOptimismMintableERC20 } from \"src/universal/IOptimismMintableERC20.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { Blast, YieldMode, GasMode } from \"src/L2/Blast.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\n\n/// @custom:proxied\n/// @custom:predeploy 0x4300000000000000000000000000000000000003\n/// @title USDB\n/// @notice Rebasing ERC20 token with the share price determined by an L1\n///         REPORTER. Conforms to OptimismMintableERC20 interface to allow mint/burn\n///         interactions from the L1BlastBridge.\ncontract USDB is ERC20Rebasing, Semver, IOptimismMintableERC20 {\n    /// @notice Address of the corresponding version of this token on the remote chain.\n    address public immutable REMOTE_TOKEN;\n\n    /// @notice Address of the BlastBridge on this network.\n    address public immutable BRIDGE;\n\n    error CallerIsNotBridge();\n\n    /// @notice A modifier that only allows the bridge to call\n    modifier onlyBridge() {\n        if (msg.sender != BRIDGE) {\n            revert CallerIsNotBridge();\n        }\n        _;\n    }\n\n    /// @custom:semver 1.0.0\n    /// @param _usdYieldManager Address of the USD Yield Manager. SharesBase yield reporter.\n    /// @param _l2Bridge        Address of the L2 Blast bridge.\n    /// @param _remoteToken     Address of the corresponding L1 token.\n    constructor(address _usdYieldManager, address _l2Bridge, address _remoteToken)\n        ERC20Rebasing(_usdYieldManager, 18)\n        Semver(1, 0, 0)\n    {\n        BRIDGE = _l2Bridge;\n        REMOTE_TOKEN = _remoteToken;\n        _disableInitializers();\n    }\n\n    /// @notice Initializer\n    function initialize() public initializer {\n        __ERC20Rebasing_init(\"USDB\", \"USDB\", 1e9);\n        Blast(Predeploys.BLAST).configureContract(\n            address(this),\n            YieldMode.VOID,\n            GasMode.VOID,\n            address(0xdead) /// don't set a governor\n        );\n    }\n\n    /// @notice ERC165 interface check function.\n    /// @param _interfaceId Interface ID to check.\n    /// @return Whether or not the interface is supported by this contract.\n    function supportsInterface(bytes4 _interfaceId) external pure returns (bool) {\n        bytes4 iface1 = type(IERC165).interfaceId;\n        // Interface corresponding to the updated OptimismMintableERC20.\n        bytes4 iface2 = type(IOptimismMintableERC20).interfaceId;\n        return _interfaceId == iface1 || _interfaceId == iface2;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for REMOTE_TOKEN.\n    function remoteToken() public view returns (address) {\n        return REMOTE_TOKEN;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for BRIDGE.\n    function bridge() public view returns (address) {\n        return BRIDGE;\n    }\n\n    /// @notice Allows the StandardBridge on this network to mint tokens.\n    /// @param _to     Address to mint tokens to.\n    /// @param _amount Amount of tokens to mint.\n    function mint(address _to, uint256 _amount)\n        external\n        virtual\n        onlyBridge\n    {\n        if (_to == address(0)) {\n            revert TransferToZeroAddress();\n        }\n\n        _deposit(_to, _amount);\n        emit Transfer(address(0), _to, _amount);\n    }\n\n    /// @notice Allows the StandardBridge on this network to burn tokens.\n    /// @param _from   Address to burn tokens from.\n    /// @param _amount Amount of tokens to burn.\n    function burn(address _from, uint256 _amount)\n        external\n        virtual\n        onlyBridge\n    {\n        if (_from == address(0)) {\n            revert TransferFromZeroAddress();\n        }\n\n        _withdraw(_from, _amount);\n        emit Transfer(_from, address(0), _amount);\n    }\n}\n"},{"file_path":"src/vendor/AddressAliasHelper.sol","source_code":"// SPDX-License-Identifier: Apache-2.0\n\n/*\n * Copyright 2019-2021, Offchain Labs, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npragma solidity ^0.8.0;\n\nlibrary AddressAliasHelper {\n    uint160 constant offset = uint160(0x1111000000000000000000000000000000001111);\n\n    /// @notice Utility function that converts the address in the L1 that submitted a tx to\n    /// the inbox to the msg.sender viewed in the L2\n    /// @param l1Address the address in the L1 that triggered the tx to L2\n    /// @return l2Address L2 address as viewed in msg.sender\n    function applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) {\n        unchecked {\n            l2Address = address(uint160(l1Address) + offset);\n        }\n    }\n\n    /// @notice Utility function that converts the msg.sender viewed in the L2 to the\n    /// address in the L1 that submitted a tx to the inbox\n    /// @param l2Address L2 address as viewed in msg.sender\n    /// @return l1Address the address in the L1 that triggered the tx to L2\n    function undoL1ToL2Alias(address l2Address) internal pure returns (address l1Address) {\n        unchecked {\n            l1Address = address(uint160(l2Address) - offset);\n        }\n    }\n}\n"},{"file_path":"src/libraries/Storage.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @title Storage\n/// @notice Storage handles reading and writing to arbitary storage locations\nlibrary Storage {\n    /// @notice Returns an address stored in an arbitrary storage slot.\n    ///         These storage slots decouple the storage layout from\n    ///         solc's automation.\n    /// @param _slot The storage slot to retrieve the address from.\n    function getAddress(bytes32 _slot) internal view returns (address addr_) {\n        assembly {\n            addr_ := sload(_slot)\n        }\n    }\n\n    /// @notice Stores an address in an arbitrary storage slot, `_slot`.\n    /// @param _slot The storage slot to store the address in.\n    /// @param _address The protocol version to store\n    /// @dev WARNING! This function must be used cautiously, as it allows for overwriting addresses\n    ///      in arbitrary storage slots.\n    function setAddress(bytes32 _slot, address _address) internal {\n        assembly {\n            sstore(_slot, _address)\n        }\n    }\n\n    /// @notice Returns a uint256 stored in an arbitrary storage slot.\n    ///         These storage slots decouple the storage layout from\n    ///         solc's automation.\n    /// @param _slot The storage slot to retrieve the address from.\n    function getUint(bytes32 _slot) internal view returns (uint256 value_) {\n        assembly {\n            value_ := sload(_slot)\n        }\n    }\n\n    /// @notice Stores a value in an arbitrary storage slot, `_slot`.\n    /// @param _slot The storage slot to store the address in.\n    /// @param _value The protocol version to store\n    /// @dev WARNING! This function must be used cautiously, as it allows for overwriting values\n    ///      in arbitrary storage slots.\n    function setUint(bytes32 _slot, uint256 _value) internal {\n        assembly {\n            sstore(_slot, _value)\n        }\n    }\n\n    /// @notice Returns a bytes32 stored in an arbitrary storage slot.\n    ///         These storage slots decouple the storage layout from\n    ///         solc's automation.\n    /// @param _slot The storage slot to retrieve the address from.\n    function getBytes32(bytes32 _slot) internal view returns (bytes32 value_) {\n        assembly {\n            value_ := sload(_slot)\n        }\n    }\n\n    /// @notice Stores a bytes32 value in an arbitrary storage slot, `_slot`.\n    /// @param _slot The storage slot to store the address in.\n    /// @param _value The protocol version to store\n    /// @dev WARNING! This function must be used cautiously, as it allows for overwriting values\n    ///      in arbitrary storage slots.\n    function setBytes32(bytes32 _slot, bytes32 _value) internal {\n        assembly {\n            sstore(_slot, _value)\n        }\n    }\n}\n"},{"file_path":"src/libraries/SafeCall.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\n/// @title SafeCall\n/// @notice Perform low level safe calls\nlibrary SafeCall {\n    /// @notice Performs a low level call without copying any returndata.\n    /// @dev Passes no calldata to the call context.\n    /// @param _target   Address to call\n    /// @param _gas      Amount of gas to pass to the call\n    /// @param _value    Amount of value to pass to the call\n    function send(address _target, uint256 _gas, uint256 _value) internal returns (bool) {\n        bool _success;\n        assembly {\n            _success :=\n                call(\n                    _gas, // gas\n                    _target, // recipient\n                    _value, // ether value\n                    0, // inloc\n                    0, // inlen\n                    0, // outloc\n                    0 // outlen\n                )\n        }\n        return _success;\n    }\n\n    /// @notice Perform a low level call without copying any returndata\n    /// @param _target   Address to call\n    /// @param _gas      Amount of gas to pass to the call\n    /// @param _value    Amount of value to pass to the call\n    /// @param _calldata Calldata to pass to the call\n    function call(address _target, uint256 _gas, uint256 _value, bytes memory _calldata) internal returns (bool) {\n        bool _success;\n        assembly {\n            _success :=\n                call(\n                    _gas, // gas\n                    _target, // recipient\n                    _value, // ether value\n                    add(_calldata, 32), // inloc\n                    mload(_calldata), // inlen\n                    0, // outloc\n                    0 // outlen\n                )\n        }\n        return _success;\n    }\n\n    /// @notice Helper function to determine if there is sufficient gas remaining within the context\n    ///         to guarantee that the minimum gas requirement for a call will be met as well as\n    ///         optionally reserving a specified amount of gas for after the call has concluded.\n    /// @param _minGas      The minimum amount of gas that may be passed to the target context.\n    /// @param _reservedGas Optional amount of gas to reserve for the caller after the execution\n    ///                     of the target context.\n    /// @return `true` if there is enough gas remaining to safely supply `_minGas` to the target\n    ///         context as well as reserve `_reservedGas` for the caller after the execution of\n    ///         the target context.\n    /// @dev !!!!! FOOTGUN ALERT !!!!!\n    ///      1.) The 40_000 base buffer is to account for the worst case of the dynamic cost of the\n    ///          `CALL` opcode's `address_access_cost`, `positive_value_cost`, and\n    ///          `value_to_empty_account_cost` factors with an added buffer of 5,700 gas. It is\n    ///          still possible to self-rekt by initiating a withdrawal with a minimum gas limit\n    ///          that does not account for the `memory_expansion_cost` & `code_execution_cost`\n    ///          factors of the dynamic cost of the `CALL` opcode.\n    ///      2.) This function should *directly* precede the external call if possible. There is an\n    ///          added buffer to account for gas consumed between this check and the call, but it\n    ///          is only 5,700 gas.\n    ///      3.) Because EIP-150 ensures that a maximum of 63/64ths of the remaining gas in the call\n    ///          frame may be passed to a subcontext, we need to ensure that the gas will not be\n    ///          truncated.\n    ///      4.) Use wisely. This function is not a silver bullet.\n    function hasMinGas(uint256 _minGas, uint256 _reservedGas) internal view returns (bool) {\n        bool _hasMinGas;\n        assembly {\n            // Equation: gas × 63 ≥ minGas × 64 + 63(40_000 + reservedGas)\n            _hasMinGas := iszero(lt(mul(gas(), 63), add(mul(_minGas, 64), mul(add(40000, _reservedGas), 63))))\n        }\n        return _hasMinGas;\n    }\n\n    /// @notice Perform a low level call without copying any returndata. This function\n    ///         will revert if the call cannot be performed with the specified minimum\n    ///         gas.\n    /// @param _target   Address to call\n    /// @param _minGas   The minimum amount of gas that may be passed to the call\n    /// @param _value    Amount of value to pass to the call\n    /// @param _calldata Calldata to pass to the call\n    function callWithMinGas(\n        address _target,\n        uint256 _minGas,\n        uint256 _value,\n        bytes memory _calldata\n    )\n        internal\n        returns (bool)\n    {\n        bool _success;\n        bool _hasMinGas = hasMinGas(_minGas, 0);\n        assembly {\n            // Assertion: gasleft() >= (_minGas * 64) / 63 + 40_000\n            if iszero(_hasMinGas) {\n                // Store the \"Error(string)\" selector in scratch space.\n                mstore(0, 0x08c379a0)\n                // Store the pointer to the string length in scratch space.\n                mstore(32, 32)\n                // Store the string.\n                //\n                // SAFETY:\n                // - We pad the beginning of the string with two zero bytes as well as the\n                // length (24) to ensure that we override the free memory pointer at offset\n                // 0x40. This is necessary because the free memory pointer is likely to\n                // be greater than 1 byte when this function is called, but it is incredibly\n                // unlikely that it will be greater than 3 bytes. As for the data within\n                // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.\n                // - It's fine to clobber the free memory pointer, we're reverting.\n                mstore(88, 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173)\n\n                // Revert with 'Error(\"SafeCall: Not enough gas\")'\n                revert(28, 100)\n            }\n\n            // The call will be supplied at least ((_minGas * 64) / 63) gas due to the\n            // above assertion. This ensures that, in all circumstances (except for when the\n            // `_minGas` does not account for the `memory_expansion_cost` and `code_execution_cost`\n            // factors of the dynamic cost of the `CALL` opcode), the call will receive at least\n            // the minimum amount of gas specified.\n            _success :=\n                call(\n                    gas(), // gas\n                    _target, // recipient\n                    _value, // ether value\n                    add(_calldata, 32), // inloc\n                    mload(_calldata), // inlen\n                    0x00, // outloc\n                    0x00 // outlen\n                )\n        }\n        return _success;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\n"},{"file_path":"src/libraries/Burn.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\n/// @title Burn\n/// @notice Utilities for burning stuff.\nlibrary Burn {\n    /// @notice Burns a given amount of ETH.\n    /// @param _amount Amount of ETH to burn.\n    function eth(uint256 _amount) internal {\n        new Burner{ value: _amount }();\n    }\n\n    /// @notice Burns a given amount of gas.\n    /// @param _amount Amount of gas to burn.\n    function gas(uint256 _amount) internal view {\n        uint256 i = 0;\n        uint256 initialGas = gasleft();\n        while (initialGas - gasleft() < _amount) {\n            ++i;\n        }\n    }\n}\n\n/// @title Burner\n/// @notice Burner self-destructs on creation and sends all ETH to itself, removing all ETH given to\n///         the contract from the circulating supply. Self-destructing is the only way to remove ETH\n///         from the circulating supply.\ncontract Burner {\n    constructor() payable {\n        selfdestruct(payable(address(this)));\n    }\n}\n"},{"file_path":"src/L1/L2OutputOracle.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport { ISemver } from \"src/universal/ISemver.sol\";\nimport { Types } from \"src/libraries/Types.sol\";\nimport { Constants } from \"src/libraries/Constants.sol\";\n\n/// @custom:proxied\n/// @title L2OutputOracle\n/// @notice The L2OutputOracle contains an array of L2 state outputs, where each output is a\n///         commitment to the state of the L2 chain. Other contracts like the OptimismPortal use\n///         these outputs to verify information about the state of L2.\ncontract L2OutputOracle is Initializable, ISemver {\n    /// @notice The interval in L2 blocks at which checkpoints must be submitted.\n    ///         Although this is immutable, it can safely be modified by upgrading the\n    ///         implementation contract.\n    ///         Public getter is legacy and will be removed in the future. Use `submissionInterval`\n    ///         instead.\n    /// @custom:legacy\n    uint256 public immutable SUBMISSION_INTERVAL;\n\n    /// @notice The time between L2 blocks in seconds. Once set, this value MUST NOT be modified.\n    ///         Public getter is legacy and will be removed in the future. Use `l2BlockTime`\n    ///         instead.\n    /// @custom:legacy\n    uint256 public immutable L2_BLOCK_TIME;\n\n    /// @notice The minimum time (in seconds) that must elapse before a withdrawal can be finalized.\n    ///         Public getter is legacy and will be removed in the future. Use\n    //          `finalizationPeriodSeconds` instead.\n    /// @custom:legacy\n    uint256 public immutable FINALIZATION_PERIOD_SECONDS;\n\n    /// @notice The number of the first L2 block recorded in this contract.\n    uint256 public startingBlockNumber;\n\n    /// @notice The timestamp of the first L2 block recorded in this contract.\n    uint256 public startingTimestamp;\n\n    /// @notice An array of L2 output proposals.\n    Types.OutputProposal[] internal l2Outputs;\n\n    /// @notice The address of the challenger. Can be updated via reinitialize.\n    /// @custom:network-specific\n    address public challenger;\n\n    /// @notice The address of the proposer. Can be updated via reinitialize.\n    /// @custom:network-specific\n    address public proposer;\n\n    /// @notice Emitted when an output is proposed.\n    /// @param outputRoot    The output root.\n    /// @param l2OutputIndex The index of the output in the l2Outputs array.\n    /// @param l2BlockNumber The L2 block number of the output root.\n    /// @param l1Timestamp   The L1 timestamp when proposed.\n    event OutputProposed(\n        bytes32 indexed outputRoot, uint256 indexed l2OutputIndex, uint256 indexed l2BlockNumber, uint256 l1Timestamp\n    );\n\n    /// @notice Emitted when outputs are deleted.\n    /// @param prevNextOutputIndex Next L2 output index before the deletion.\n    /// @param newNextOutputIndex  Next L2 output index after the deletion.\n    event OutputsDeleted(uint256 indexed prevNextOutputIndex, uint256 indexed newNextOutputIndex);\n\n    /// @notice Semantic version.\n    /// @custom:semver 1.6.0\n    string public constant version = \"1.6.0\";\n\n    /// @notice Constructs the L2OutputOracle contract.\n    /// @param _submissionInterval  Interval in blocks at which checkpoints must be submitted.\n    /// @param _l2BlockTime         The time per L2 block, in seconds.\n    /// @param _finalizationPeriodSeconds The amount of time that must pass for an output proposal\n    //                                    to be considered canonical.\n    constructor(uint256 _submissionInterval, uint256 _l2BlockTime, uint256 _finalizationPeriodSeconds) {\n        require(_l2BlockTime > 0, \"L2OutputOracle: L2 block time must be greater than 0\");\n        require(_submissionInterval > 0, \"L2OutputOracle: submission interval must be greater than 0\");\n\n        SUBMISSION_INTERVAL = _submissionInterval;\n        L2_BLOCK_TIME = _l2BlockTime;\n        FINALIZATION_PERIOD_SECONDS = _finalizationPeriodSeconds;\n\n        initialize({ _startingBlockNumber: 0, _startingTimestamp: 0, _proposer: address(0), _challenger: address(0) });\n    }\n\n    /// @notice Initializer.\n    /// @param _startingBlockNumber Block number for the first recoded L2 block.\n    /// @param _startingTimestamp   Timestamp for the first recoded L2 block.\n    /// @param _proposer            The address of the proposer.\n    /// @param _challenger          The address of the challenger.\n    function initialize(\n        uint256 _startingBlockNumber,\n        uint256 _startingTimestamp,\n        address _proposer,\n        address _challenger\n    )\n        public\n        reinitializer(Constants.INITIALIZER)\n    {\n        require(\n            _startingTimestamp <= block.timestamp,\n            \"L2OutputOracle: starting L2 timestamp must be less than current time\"\n        );\n\n        startingTimestamp = _startingTimestamp;\n        startingBlockNumber = _startingBlockNumber;\n        proposer = _proposer;\n        challenger = _challenger;\n    }\n\n    /// @notice Getter for the output proposal submission interval.\n    function submissionInterval() external view returns (uint256) {\n        return SUBMISSION_INTERVAL;\n    }\n\n    /// @notice Getter for the L2 block time.\n    function l2BlockTime() external view returns (uint256) {\n        return L2_BLOCK_TIME;\n    }\n\n    /// @notice Getter for the finalization period.\n    function finalizationPeriodSeconds() external view returns (uint256) {\n        return FINALIZATION_PERIOD_SECONDS;\n    }\n\n    /// @notice Getter for the challenger address. This will be removed\n    ///         in the future, use `challenger` instead.\n    /// @custom:legacy\n    function CHALLENGER() external view returns (address) {\n        return challenger;\n    }\n\n    /// @notice Getter for the proposer address. This will be removed in the\n    ///         future, use `proposer` instead.\n    /// @custom:legacy\n    function PROPOSER() external view returns (address) {\n        return proposer;\n    }\n\n    /// @notice Deletes all output proposals after and including the proposal that corresponds to\n    ///         the given output index. Only the challenger address can delete outputs.\n    /// @param _l2OutputIndex Index of the first L2 output to be deleted.\n    ///                       All outputs after this output will also be deleted.\n    // solhint-disable-next-line ordering\n    function deleteL2Outputs(uint256 _l2OutputIndex) external {\n        require(msg.sender == challenger, \"L2OutputOracle: only the challenger address can delete outputs\");\n\n        // Make sure we're not *increasing* the length of the array.\n        require(\n            _l2OutputIndex < l2Outputs.length, \"L2OutputOracle: cannot delete outputs after the latest output index\"\n        );\n\n        // Do not allow deleting any outputs that have already been finalized.\n        require(\n            block.timestamp - l2Outputs[_l2OutputIndex].timestamp < FINALIZATION_PERIOD_SECONDS,\n            \"L2OutputOracle: cannot delete outputs that have already been finalized\"\n        );\n\n        uint256 prevNextL2OutputIndex = nextOutputIndex();\n\n        // Use assembly to delete the array elements because Solidity doesn't allow it.\n        assembly {\n            sstore(l2Outputs.slot, _l2OutputIndex)\n        }\n\n        emit OutputsDeleted(prevNextL2OutputIndex, _l2OutputIndex);\n    }\n\n    /// @notice Accepts an outputRoot and the timestamp of the corresponding L2 block.\n    ///         The timestamp must be equal to the current value returned by `nextTimestamp()` in\n    ///         order to be accepted. This function may only be called by the Proposer.\n    /// @param _outputRoot    The L2 output of the checkpoint block.\n    /// @param _l2BlockNumber The L2 block number that resulted in _outputRoot.\n    /// @param _l1BlockHash   A block hash which must be included in the current chain.\n    /// @param _l1BlockNumber The block number with the specified block hash.\n    function proposeL2Output(\n        bytes32 _outputRoot,\n        uint256 _l2BlockNumber,\n        bytes32 _l1BlockHash,\n        uint256 _l1BlockNumber\n    )\n        external\n        payable\n    {\n        require(msg.sender == proposer, \"L2OutputOracle: only the proposer address can propose new outputs\");\n\n        require(\n            _l2BlockNumber == nextBlockNumber(),\n            \"L2OutputOracle: block number must be equal to next expected block number\"\n        );\n\n        require(\n            computeL2Timestamp(_l2BlockNumber) < block.timestamp,\n            \"L2OutputOracle: cannot propose L2 output in the future\"\n        );\n\n        require(_outputRoot != bytes32(0), \"L2OutputOracle: L2 output proposal cannot be the zero hash\");\n\n        if (_l1BlockHash != bytes32(0)) {\n            // This check allows the proposer to propose an output based on a given L1 block,\n            // without fear that it will be reorged out.\n            // It will also revert if the blockheight provided is more than 256 blocks behind the\n            // chain tip (as the hash will return as zero). This does open the door to a griefing\n            // attack in which the proposer's submission is censored until the block is no longer\n            // retrievable, if the proposer is experiencing this attack it can simply leave out the\n            // blockhash value, and delay submission until it is confident that the L1 block is\n            // finalized.\n            require(\n                blockhash(_l1BlockNumber) == _l1BlockHash,\n                \"L2OutputOracle: block hash does not match the hash at the expected height\"\n            );\n        }\n\n        emit OutputProposed(_outputRoot, nextOutputIndex(), _l2BlockNumber, block.timestamp);\n\n        l2Outputs.push(\n            Types.OutputProposal({\n                outputRoot: _outputRoot,\n                timestamp: uint128(block.timestamp),\n                l2BlockNumber: uint128(_l2BlockNumber)\n            })\n        );\n    }\n\n    /// @notice Returns an output by index. Needed to return a struct instead of a tuple.\n    /// @param _l2OutputIndex Index of the output to return.\n    /// @return The output at the given index.\n    function getL2Output(uint256 _l2OutputIndex) external view returns (Types.OutputProposal memory) {\n        return l2Outputs[_l2OutputIndex];\n    }\n\n    /// @notice Returns the index of the L2 output that checkpoints a given L2 block number.\n    ///         Uses a binary search to find the first output greater than or equal to the given\n    ///         block.\n    /// @param _l2BlockNumber L2 block number to find a checkpoint for.\n    /// @return Index of the first checkpoint that commits to the given L2 block number.\n    function getL2OutputIndexAfter(uint256 _l2BlockNumber) public view returns (uint256) {\n        // Make sure an output for this block number has actually been proposed.\n        require(\n            _l2BlockNumber <= latestBlockNumber(),\n            \"L2OutputOracle: cannot get output for a block that has not been proposed\"\n        );\n\n        // Make sure there's at least one output proposed.\n        require(l2Outputs.length > 0, \"L2OutputOracle: cannot get output as no outputs have been proposed yet\");\n\n        // Find the output via binary search, guaranteed to exist.\n        uint256 lo = 0;\n        uint256 hi = l2Outputs.length;\n        while (lo < hi) {\n            uint256 mid = (lo + hi) / 2;\n            if (l2Outputs[mid].l2BlockNumber < _l2BlockNumber) {\n                lo = mid + 1;\n            } else {\n                hi = mid;\n            }\n        }\n\n        return lo;\n    }\n\n    /// @notice Returns the L2 output proposal that checkpoints a given L2 block number.\n    ///         Uses a binary search to find the first output greater than or equal to the given\n    ///         block.\n    /// @param _l2BlockNumber L2 block number to find a checkpoint for.\n    /// @return First checkpoint that commits to the given L2 block number.\n    function getL2OutputAfter(uint256 _l2BlockNumber) external view returns (Types.OutputProposal memory) {\n        return l2Outputs[getL2OutputIndexAfter(_l2BlockNumber)];\n    }\n\n    /// @notice Returns the number of outputs that have been proposed.\n    ///         Will revert if no outputs have been proposed yet.\n    /// @return The number of outputs that have been proposed.\n    function latestOutputIndex() external view returns (uint256) {\n        return l2Outputs.length - 1;\n    }\n\n    /// @notice Returns the index of the next output to be proposed.\n    /// @return The index of the next output to be proposed.\n    function nextOutputIndex() public view returns (uint256) {\n        return l2Outputs.length;\n    }\n\n    /// @notice Returns the block number of the latest submitted L2 output proposal.\n    ///         If no proposals been submitted yet then this function will return the starting\n    ///         block number.\n    /// @return Latest submitted L2 block number.\n    function latestBlockNumber() public view returns (uint256) {\n        return l2Outputs.length == 0 ? startingBlockNumber : l2Outputs[l2Outputs.length - 1].l2BlockNumber;\n    }\n\n    /// @notice Computes the block number of the next L2 block that needs to be checkpointed.\n    /// @return Next L2 block number.\n    function nextBlockNumber() public view returns (uint256) {\n        return latestBlockNumber() + SUBMISSION_INTERVAL;\n    }\n\n    /// @notice Returns the L2 timestamp corresponding to a given L2 block number.\n    /// @param _l2BlockNumber The L2 block number of the target block.\n    /// @return L2 timestamp of the given block.\n    function computeL2Timestamp(uint256 _l2BlockNumber) public view returns (uint256) {\n        return startingTimestamp + ((_l2BlockNumber - startingBlockNumber) * L2_BLOCK_TIME);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/CountersUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n */\nlibrary CountersUpgradeable {\n    struct Counter {\n        // This variable should never be directly accessed by users of the library: interactions must be restricted to\n        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n        // this feature: see https://github.com/ethereum/solidity/issues/4637\n        uint256 _value; // default: 0\n    }\n\n    function current(Counter storage counter) internal view returns (uint256) {\n        return counter._value;\n    }\n\n    function increment(Counter storage counter) internal {\n        unchecked {\n            counter._value += 1;\n        }\n    }\n\n    function decrement(Counter storage counter) internal {\n        uint256 value = counter._value;\n        require(value > 0, \"Counter: decrement overflow\");\n        unchecked {\n            counter._value = value - 1;\n        }\n    }\n\n    function reset(Counter storage counter) internal {\n        counter._value = 0;\n    }\n}\n"},{"file_path":"src/libraries/Predeploys.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @title Predeploys\n/// @notice Contains constant addresses for contracts that are pre-deployed to the L2 system.\nlibrary Predeploys {\n    /// @notice Address of the L2ToL1MessagePasser predeploy.\n    address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000016;\n\n    /// @notice Address of the L2CrossDomainMessenger predeploy.\n    address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;\n\n    /// @notice Address of the L2StandardBridge predeploy.\n    address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;\n\n    /// @notice Address of the L2ERC721Bridge predeploy.\n    address internal constant L2_ERC721_BRIDGE = 0x4200000000000000000000000000000000000014;\n\n    //// @notice Address of the SequencerFeeWallet predeploy.\n    address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;\n\n    /// @notice Address of the OptimismMintableERC20Factory predeploy.\n    address internal constant OPTIMISM_MINTABLE_ERC20_FACTORY = 0x4200000000000000000000000000000000000012;\n\n    /// @notice Address of the OptimismMintableERC721Factory predeploy.\n    address internal constant OPTIMISM_MINTABLE_ERC721_FACTORY = 0x4200000000000000000000000000000000000017;\n\n    /// @notice Address of the L1Block predeploy.\n    address internal constant L1_BLOCK_ATTRIBUTES = 0x4200000000000000000000000000000000000015;\n\n    /// @notice Address of the GasPriceOracle predeploy. Includes fee information\n    ///         and helpers for computing the L1 portion of the transaction fee.\n    address internal constant GAS_PRICE_ORACLE = 0x420000000000000000000000000000000000000F;\n\n    /// @custom:legacy\n    /// @notice Address of the L1MessageSender predeploy. Deprecated. Use L2CrossDomainMessenger\n    ///         or access tx.origin (or msg.sender) in a L1 to L2 transaction instead.\n    address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;\n\n    /// @custom:legacy\n    /// @notice Address of the DeployerWhitelist predeploy. No longer active.\n    address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;\n\n    /// @custom:legacy\n    /// @notice Address of the LegacyERC20ETH predeploy. Deprecated. Balances are migrated to the\n    ///         state trie as of the Bedrock upgrade. Contract has been locked and write functions\n    ///         can no longer be accessed.\n    address internal constant LEGACY_ERC20_ETH = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;\n\n    /// @custom:legacy\n    /// @notice Address of the L1BlockNumber predeploy. Deprecated. Use the L1Block predeploy\n    ///         instead, which exposes more information about the L1 state.\n    address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013;\n\n    /// @custom:legacy\n    /// @notice Address of the LegacyMessagePasser predeploy. Deprecate. Use the updated\n    ///         L2ToL1MessagePasser contract instead.\n    address internal constant LEGACY_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;\n\n    /// @notice Address of the ProxyAdmin predeploy.\n    address internal constant PROXY_ADMIN = 0x4200000000000000000000000000000000000018;\n\n    /// @notice Address of the BaseFeeVault predeploy.\n    address internal constant BASE_FEE_VAULT = 0x4200000000000000000000000000000000000019;\n\n    /// @notice Address of the L1FeeVault predeploy.\n    address internal constant L1_FEE_VAULT = 0x420000000000000000000000000000000000001A;\n\n    /// @notice Address of the GovernanceToken predeploy.\n    address internal constant GOVERNANCE_TOKEN = 0x4200000000000000000000000000000000000042;\n\n    /// @notice Address of the SchemaRegistry predeploy.\n    address internal constant SCHEMA_REGISTRY = 0x4200000000000000000000000000000000000020;\n\n    /// @notice Address of the EAS predeploy.\n    address internal constant EAS = 0x4200000000000000000000000000000000000021;\n\n    /// @notice Address of the Shares predeploy.\n    address internal constant SHARES = 0x4300000000000000000000000000000000000000;\n\n    /// @notice Address of the Gas predeploy.\n    address internal constant GAS = 0x4300000000000000000000000000000000000001;\n\n    /// @notice Address of the Blast predeploy.\n    address internal constant BLAST = 0x4300000000000000000000000000000000000002;\n\n    /// @notice Address of the USDB predeploy.\n    address internal constant USDB = 0x4300000000000000000000000000000000000003;\n\n    /// @notice Address of the WETH predeploy.\n    address internal constant WETH_REBASING = 0x4300000000000000000000000000000000000004;\n\n    /// @notice Address of the L2BlastBridge predeploy.\n    address internal constant L2_BLAST_BRIDGE = 0x4300000000000000000000000000000000000005;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n *  Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.\n *  See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n *  In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        return _values(set._inner);\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"},{"file_path":"src/L2/Blast.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { GasMode, IGas } from \"src/L2/Gas.sol\";\n\nenum YieldMode {\n    AUTOMATIC,\n    VOID,\n    CLAIMABLE\n}\n\ninterface IYield {\n    function configure(address contractAddress, uint8 flags) external returns (uint256);\n    function claim(address contractAddress, address recipientOfYield, uint256 desiredAmount) external returns (uint256);\n    function getClaimableAmount(address contractAddress) external view returns (uint256);\n    function getConfiguration(address contractAddress) external view returns (uint8);\n}\n\ninterface IBlast{\n    // configure\n    function configureContract(address contractAddress, YieldMode _yield, GasMode gasMode, address governor) external;\n    function configure(YieldMode _yield, GasMode gasMode, address governor) external;\n\n    // base configuration options\n    function configureClaimableYield() external;\n    function configureClaimableYieldOnBehalf(address contractAddress) external;\n    function configureAutomaticYield() external;\n    function configureAutomaticYieldOnBehalf(address contractAddress) external;\n    function configureVoidYield() external;\n    function configureVoidYieldOnBehalf(address contractAddress) external;\n    function configureClaimableGas() external;\n    function configureClaimableGasOnBehalf(address contractAddress) external;\n    function configureVoidGas() external;\n    function configureVoidGasOnBehalf(address contractAddress) external;\n    function configureGovernor(address _governor) external;\n    function configureGovernorOnBehalf(address _newGovernor, address contractAddress) external;\n\n    // claim yield\n    function claimYield(address contractAddress, address recipientOfYield, uint256 amount) external returns (uint256);\n    function claimAllYield(address contractAddress, address recipientOfYield) external returns (uint256);\n\n    // claim gas\n    function claimAllGas(address contractAddress, address recipientOfGas) external returns (uint256);\n    // NOTE: can be off by 1 bip\n    function claimGasAtMinClaimRate(address contractAddress, address recipientOfGas, uint256 minClaimRateBips) external returns (uint256);\n    function claimMaxGas(address contractAddress, address recipientOfGas) external returns (uint256);\n    function claimGas(address contractAddress, address recipientOfGas, uint256 gasToClaim, uint256 gasSecondsToConsume) external returns (uint256);\n\n    // read functions\n    function readClaimableYield(address contractAddress) external view returns (uint256);\n    function readYieldConfiguration(address contractAddress) external view returns (uint8);\n    function readGasParams(address contractAddress) external view returns (uint256 etherSeconds, uint256 etherBalance, uint256 lastUpdated, GasMode);\n}\n\n/// @custom:predeploy 0x4300000000000000000000000000000000000002\n/// @title Blast\ncontract Blast is IBlast, Initializable, Semver {\n    address public immutable YIELD_CONTRACT;\n    address public immutable GAS_CONTRACT;\n\n    mapping(address => address) public governorMap;\n\n    constructor(address _gasContract, address _yieldContract) Semver(1, 0, 0) {\n        GAS_CONTRACT = _gasContract;\n        YIELD_CONTRACT = _yieldContract;\n        _disableInitializers();\n    }\n\n    function initialize() public initializer {}\n\n    /**\n     * @notice Checks if the caller is the governor of the contract\n     * @param contractAddress The address of the contract\n     * @return A boolean indicating if the caller is the governor\n     */\n    function isGovernor(address contractAddress) public view returns (bool) {\n        return msg.sender == governorMap[contractAddress];\n    }\n    /**\n     * @notice Checks if the governor is not set for the contract\n     * @param contractAddress The address of the contract\n     * @return boolean indicating if the governor is not set\n     */\n    function governorNotSet(address contractAddress) internal view returns (bool) {\n        return governorMap[contractAddress] == address(0);\n    }\n    /**\n     * @notice Checks if the caller is authorized\n     * @param contractAddress The address of the contract\n     * @return A boolean indicating if the caller is authorized\n     */\n    function isAuthorized(address contractAddress) public view returns (bool) {\n        return isGovernor(contractAddress) || (governorNotSet(contractAddress) && msg.sender == contractAddress);\n    }\n\n    /**\n     * @notice contract configures its yield and gas modes and sets the governor. called by contract\n     * @param _yieldMode The yield mode to be set\n     * @param _gasMode The gas mode to be set\n     * @param governor The address of the governor to be set\n     */\n    function configure(YieldMode _yieldMode, GasMode _gasMode, address governor) external {\n        // requires that no governor is set for contract\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        // set governor\n        governorMap[msg.sender] = governor;\n        // set gas mode\n        IGas(GAS_CONTRACT).setGasMode(msg.sender, _gasMode);\n        // set yield mode\n        IYield(YIELD_CONTRACT).configure(msg.sender, uint8(_yieldMode));\n    }\n\n    /**\n     * @notice Configures the yield and gas modes and sets the governor for a specific contract. called by authorized user\n     * @param contractAddress The address of the contract to be configured\n     * @param _yieldMode The yield mode to be set\n     * @param _gasMode The gas mode to be set\n     * @param _newGovernor The address of the new governor to be set\n     */\n    function configureContract(address contractAddress, YieldMode _yieldMode, GasMode _gasMode, address _newGovernor) external {\n        // only allow governor, or if no governor is set, the contract itself to configure\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        // set governor\n        governorMap[contractAddress] = _newGovernor;\n        // set gas mode\n        IGas(GAS_CONTRACT).setGasMode(contractAddress, _gasMode);\n        // set yield mode\n        IYield(YIELD_CONTRACT).configure(contractAddress, uint8(_yieldMode));\n    }\n\n    /**\n     * @notice Configures the yield mode to CLAIMABLE for the contract that calls this function\n     */\n    function configureClaimableYield() external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(msg.sender, uint8(YieldMode.CLAIMABLE));\n    }\n\n    /**\n     * @notice Configures the yield mode to CLAIMABLE for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureClaimableYieldOnBehalf(address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(contractAddress, uint8(YieldMode.CLAIMABLE));\n    }\n\n    /**\n     * @notice Configures the yield mode to AUTOMATIC for the contract that calls this function\n     */\n    function configureAutomaticYield() external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(msg.sender, uint8(YieldMode.AUTOMATIC));\n    }\n\n    /**\n     * @notice Configures the yield mode to AUTOMATIC for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureAutomaticYieldOnBehalf(address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(contractAddress, uint8(YieldMode.AUTOMATIC));\n    }\n\n    /**\n     * @notice Configures the yield mode to VOID for the contract that calls this function\n     */\n    function configureVoidYield() external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(msg.sender, uint8(YieldMode.VOID));\n    }\n\n    /**\n     * @notice Configures the yield mode to VOID for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureVoidYieldOnBehalf(address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        IYield(YIELD_CONTRACT).configure(contractAddress, uint8(YieldMode.VOID));\n    }\n\n    /**\n     * @notice Configures the gas mode to CLAIMABLE for the contract that calls this function\n     */\n    function configureClaimableGas() external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        IGas(GAS_CONTRACT).setGasMode(msg.sender, GasMode.CLAIMABLE);\n    }\n\n    /**\n     * @notice Configures the gas mode to CLAIMABLE for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureClaimableGasOnBehalf(address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        IGas(GAS_CONTRACT).setGasMode(contractAddress, GasMode.CLAIMABLE);\n    }\n\n    /**\n     * @notice Configures the gas mode to VOID for the contract that calls this function\n     */\n    function configureVoidGas() external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        IGas(GAS_CONTRACT).setGasMode(msg.sender, GasMode.VOID);\n    }\n\n    /**\n     * @notice Configures the gas mode to void for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureVoidGasOnBehalf(address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        IGas(GAS_CONTRACT).setGasMode(contractAddress, GasMode.VOID);\n    }\n\n    /**\n     * @notice Configures the governor for the contract that calls this function\n     */\n    function configureGovernor(address _governor) external {\n        require(isAuthorized(msg.sender), \"not authorized to configure contract\");\n        governorMap[msg.sender] = _governor;\n    }\n\n    /**\n     * @notice Configures the governor for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract to be configured\n     */\n    function configureGovernorOnBehalf(address _newGovernor, address contractAddress) external {\n        require(isAuthorized(contractAddress), \"not authorized to configure contract\");\n        governorMap[contractAddress] = _newGovernor;\n    }\n\n\n    // claim methods\n\n    /**\n     * @notice Claims yield for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract for which yield is to be claimed\n     * @param recipientOfYield The address of the recipient of the yield\n     * @param amount The amount of yield to be claimed\n     * @return The amount of yield that was claimed\n     */\n    function claimYield(address contractAddress, address recipientOfYield, uint256 amount) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not authorized to claim yield\");\n        return  IYield(YIELD_CONTRACT).claim(contractAddress, recipientOfYield, amount);\n    }\n    /**\n     * @notice Claims all yield for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract for which all yield is to be claimed\n     * @param recipientOfYield The address of the recipient of the yield\n     * @return The amount of yield that was claimed\n     */\n    function claimAllYield(address contractAddress, address recipientOfYield) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not authorized to claim yield\");\n        uint256 amount = IYield(YIELD_CONTRACT).getClaimableAmount(contractAddress);\n        return  IYield(YIELD_CONTRACT).claim(contractAddress, recipientOfYield, amount);\n    }\n\n    /**\n     * @notice Claims all gas for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract for which all gas is to be claimed\n     * @param recipientOfGas The address of the recipient of the gas\n     * @return The amount of gas that was claimed\n     */\n    function claimAllGas(address contractAddress, address recipientOfGas) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not allowed to claim all gas\");\n        return IGas(GAS_CONTRACT).claimAll(contractAddress, recipientOfGas);\n    }\n\n    /**\n     * @notice Claims gas at a minimum claim rate for a specific contract, with error rate '1'. Called by an authorized user\n     * @param contractAddress The address of the contract for which gas is to be claimed\n     * @param recipientOfGas The address of the recipient of the gas\n     * @param minClaimRateBips The minimum claim rate in basis points\n     * @return The amount of gas that was claimed\n     */\n    function claimGasAtMinClaimRate(address contractAddress, address recipientOfGas, uint256 minClaimRateBips) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not allowed to claim gas at min claim rate\");\n        return IGas(GAS_CONTRACT).claimGasAtMinClaimRate(contractAddress, recipientOfGas, minClaimRateBips);\n    }\n\n    /**\n     * @notice Claims gas available to be claimed at max claim rate for a specific contract. Called by an authorized user\n     * @param contractAddress The address of the contract for which maximum gas is to be claimed\n     * @param recipientOfGas The address of the recipient of the gas\n     * @return The amount of gas that was claimed\n     */\n    function claimMaxGas(address contractAddress, address recipientOfGas) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not allowed to claim max gas\");\n        return IGas(GAS_CONTRACT).claimMax(contractAddress, recipientOfGas);\n    }\n    /**\n     * @notice Claims a specific amount of gas for a specific contract. claim rate governed by integral of gas over time\n     * @param contractAddress The address of the contract for which gas is to be claimed\n     * @param recipientOfGas The address of the recipient of the gas\n     * @param gasToClaim The amount of gas to be claimed\n     * @param gasSecondsToConsume The amount of gas seconds to consume\n     * @return The amount of gas that was claimed\n     */\n    function claimGas(address contractAddress, address recipientOfGas, uint256 gasToClaim, uint256 gasSecondsToConsume) external returns (uint256) {\n        require(isAuthorized(contractAddress), \"Not allowed to claim gas\");\n        return IGas(GAS_CONTRACT).claim(contractAddress, recipientOfGas, gasToClaim, gasSecondsToConsume);\n    }\n\n    /**\n     * @notice Reads the claimable yield for a specific contract\n     * @param contractAddress The address of the contract for which the claimable yield is to be read\n     * @return claimable yield\n     */\n    function readClaimableYield(address contractAddress) public view returns (uint256) {\n        return IYield(YIELD_CONTRACT).getClaimableAmount(contractAddress);\n    }\n    /**\n     * @notice Reads the yield configuration for a specific contract\n     * @param contractAddress The address of the contract for which the yield configuration is to be read\n     * @return uint8 representing yield enum\n     */\n\n    function readYieldConfiguration(address contractAddress) public view returns (uint8) {\n        return IYield(YIELD_CONTRACT).getConfiguration(contractAddress);\n    }\n    /**\n     * @notice Reads the gas parameters for a specific contract\n     * @param contractAddress The address of the contract for which the gas parameters are to be read\n     * @return uint256 representing the accumulated ether seconds\n     * @return uint256 representing ether balance\n     * @return uint256 representing last update timestamp\n     * @return GasMode representing the gas mode (VOID, CLAIMABLE)\n     */\n    function readGasParams(address contractAddress) public view returns (uint256, uint256, uint256, GasMode) {\n        return IGas(GAS_CONTRACT).readGasParams(contractAddress);\n    }\n}\n"},{"file_path":"src/libraries/trie/MerkleTrie.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { Bytes } from \"../Bytes.sol\";\nimport { RLPReader } from \"../rlp/RLPReader.sol\";\n\n/// @title MerkleTrie\n/// @notice MerkleTrie is a small library for verifying standard Ethereum Merkle-Patricia trie\n///         inclusion proofs. By default, this library assumes a hexary trie. One can change the\n///         trie radix constant to support other trie radixes.\nlibrary MerkleTrie {\n    /// @notice Struct representing a node in the trie.\n    /// @custom:field encoded The RLP-encoded node.\n    /// @custom:field decoded The RLP-decoded node.\n    struct TrieNode {\n        bytes encoded;\n        RLPReader.RLPItem[] decoded;\n    }\n\n    /// @notice Determines the number of elements per branch node.\n    uint256 internal constant TREE_RADIX = 16;\n\n    /// @notice Branch nodes have TREE_RADIX elements and one value element.\n    uint256 internal constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;\n\n    /// @notice Leaf nodes and extension nodes have two elements, a `path` and a `value`.\n    uint256 internal constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;\n\n    /// @notice Prefix for even-nibbled extension node paths.\n    uint8 internal constant PREFIX_EXTENSION_EVEN = 0;\n\n    /// @notice Prefix for odd-nibbled extension node paths.\n    uint8 internal constant PREFIX_EXTENSION_ODD = 1;\n\n    /// @notice Prefix for even-nibbled leaf node paths.\n    uint8 internal constant PREFIX_LEAF_EVEN = 2;\n\n    /// @notice Prefix for odd-nibbled leaf node paths.\n    uint8 internal constant PREFIX_LEAF_ODD = 3;\n\n    /// @notice Verifies a proof that a given key/value pair is present in the trie.\n    /// @param _key   Key of the node to search for, as a hex string.\n    /// @param _value Value of the node to search for, as a hex string.\n    /// @param _proof Merkle trie inclusion proof for the desired node. Unlike traditional Merkle\n    ///               trees, this proof is executed top-down and consists of a list of RLP-encoded\n    ///               nodes that make a path down to the target node.\n    /// @param _root  Known root of the Merkle trie. Used to verify that the included proof is\n    ///               correctly constructed.\n    /// @return valid_ Whether or not the proof is valid.\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes[] memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (bool valid_)\n    {\n        valid_ = Bytes.equal(_value, get(_key, _proof, _root));\n    }\n\n    /// @notice Retrieves the value associated with a given key.\n    /// @param _key   Key to search for, as hex bytes.\n    /// @param _proof Merkle trie inclusion proof for the key.\n    /// @param _root  Known root of the Merkle trie.\n    /// @return value_ Value of the key if it exists.\n    function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {\n        require(_key.length > 0, \"MerkleTrie: empty key\");\n\n        TrieNode[] memory proof = _parseProof(_proof);\n        bytes memory key = Bytes.toNibbles(_key);\n        bytes memory currentNodeID = abi.encodePacked(_root);\n        uint256 currentKeyIndex = 0;\n\n        // Proof is top-down, so we start at the first element (root).\n        for (uint256 i = 0; i < proof.length; i++) {\n            TrieNode memory currentNode = proof[i];\n\n            // Key index should never exceed total key length or we'll be out of bounds.\n            require(currentKeyIndex <= key.length, \"MerkleTrie: key index exceeds total key length\");\n\n            if (currentKeyIndex == 0) {\n                // First proof element is always the root node.\n                require(\n                    Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),\n                    \"MerkleTrie: invalid root hash\"\n                );\n            } else if (currentNode.encoded.length >= 32) {\n                // Nodes 32 bytes or larger are hashed inside branch nodes.\n                require(\n                    Bytes.equal(abi.encodePacked(keccak256(currentNode.encoded)), currentNodeID),\n                    \"MerkleTrie: invalid large internal hash\"\n                );\n            } else {\n                // Nodes smaller than 32 bytes aren't hashed.\n                require(Bytes.equal(currentNode.encoded, currentNodeID), \"MerkleTrie: invalid internal node hash\");\n            }\n\n            if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {\n                if (currentKeyIndex == key.length) {\n                    // Value is the last element of the decoded list (for branch nodes). There's\n                    // some ambiguity in the Merkle trie specification because bytes(0) is a\n                    // valid value to place into the trie, but for branch nodes bytes(0) can exist\n                    // even when the value wasn't explicitly placed there. Geth treats a value of\n                    // bytes(0) as \"key does not exist\" and so we do the same.\n                    value_ = RLPReader.readBytes(currentNode.decoded[TREE_RADIX]);\n                    require(value_.length > 0, \"MerkleTrie: value length must be greater than zero (branch)\");\n\n                    // Extra proof elements are not allowed.\n                    require(i == proof.length - 1, \"MerkleTrie: value node must be last node in proof (branch)\");\n\n                    return value_;\n                } else {\n                    // We're not at the end of the key yet.\n                    // Figure out what the next node ID should be and continue.\n                    uint8 branchKey = uint8(key[currentKeyIndex]);\n                    RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];\n                    currentNodeID = _getNodeID(nextNode);\n                    currentKeyIndex += 1;\n                }\n            } else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {\n                bytes memory path = _getNodePath(currentNode);\n                uint8 prefix = uint8(path[0]);\n                uint8 offset = 2 - (prefix % 2);\n                bytes memory pathRemainder = Bytes.slice(path, offset);\n                bytes memory keyRemainder = Bytes.slice(key, currentKeyIndex);\n                uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);\n\n                // Whether this is a leaf node or an extension node, the path remainder MUST be a\n                // prefix of the key remainder (or be equal to the key remainder) or the proof is\n                // considered invalid.\n                require(\n                    pathRemainder.length == sharedNibbleLength,\n                    \"MerkleTrie: path remainder must share all nibbles with key\"\n                );\n\n                if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {\n                    // Prefix of 2 or 3 means this is a leaf node. For the leaf node to be valid,\n                    // the key remainder must be exactly equal to the path remainder. We already\n                    // did the necessary byte comparison, so it's more efficient here to check that\n                    // the key remainder length equals the shared nibble length, which implies\n                    // equality with the path remainder (since we already did the same check with\n                    // the path remainder and the shared nibble length).\n                    require(\n                        keyRemainder.length == sharedNibbleLength,\n                        \"MerkleTrie: key remainder must be identical to path remainder\"\n                    );\n\n                    // Our Merkle Trie is designed specifically for the purposes of the Ethereum\n                    // state trie. Empty values are not allowed in the state trie, so we can safely\n                    // say that if the value is empty, the key should not exist and the proof is\n                    // invalid.\n                    value_ = RLPReader.readBytes(currentNode.decoded[1]);\n                    require(value_.length > 0, \"MerkleTrie: value length must be greater than zero (leaf)\");\n\n                    // Extra proof elements are not allowed.\n                    require(i == proof.length - 1, \"MerkleTrie: value node must be last node in proof (leaf)\");\n\n                    return value_;\n                } else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {\n                    // Prefix of 0 or 1 means this is an extension node. We move onto the next node\n                    // in the proof and increment the key index by the length of the path remainder\n                    // which is equal to the shared nibble length.\n                    currentNodeID = _getNodeID(currentNode.decoded[1]);\n                    currentKeyIndex += sharedNibbleLength;\n                } else {\n                    revert(\"MerkleTrie: received a node with an unknown prefix\");\n                }\n            } else {\n                revert(\"MerkleTrie: received an unparseable node\");\n            }\n        }\n\n        revert(\"MerkleTrie: ran out of proof elements\");\n    }\n\n    /// @notice Parses an array of proof elements into a new array that contains both the original\n    ///         encoded element and the RLP-decoded element.\n    /// @param _proof Array of proof elements to parse.\n    /// @return proof_ Proof parsed into easily accessible structs.\n    function _parseProof(bytes[] memory _proof) private pure returns (TrieNode[] memory proof_) {\n        uint256 length = _proof.length;\n        proof_ = new TrieNode[](length);\n        for (uint256 i = 0; i < length;) {\n            proof_[i] = TrieNode({ encoded: _proof[i], decoded: RLPReader.readList(_proof[i]) });\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /// @notice Picks out the ID for a node. Node ID is referred to as the \"hash\" within the\n    ///         specification, but nodes < 32 bytes are not actually hashed.\n    /// @param _node Node to pull an ID for.\n    /// @return id_ ID for the node, depending on the size of its contents.\n    function _getNodeID(RLPReader.RLPItem memory _node) private pure returns (bytes memory id_) {\n        id_ = _node.length < 32 ? RLPReader.readRawBytes(_node) : RLPReader.readBytes(_node);\n    }\n\n    /// @notice Gets the path for a leaf or extension node.\n    /// @param _node Node to get a path for.\n    /// @return nibbles_ Node path, converted to an array of nibbles.\n    function _getNodePath(TrieNode memory _node) private pure returns (bytes memory nibbles_) {\n        nibbles_ = Bytes.toNibbles(RLPReader.readBytes(_node.decoded[0]));\n    }\n\n    /// @notice Utility; determines the number of nibbles shared between two nibble arrays.\n    /// @param _a First nibble array.\n    /// @param _b Second nibble array.\n    /// @return shared_ Number of shared nibbles.\n    function _getSharedNibbleLength(bytes memory _a, bytes memory _b) private pure returns (uint256 shared_) {\n        uint256 max = (_a.length < _b.length) ? _a.length : _b.length;\n        for (; shared_ < max && _a[shared_] == _b[shared_];) {\n            unchecked {\n                ++shared_;\n            }\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./OwnableUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {\n    function __Ownable2Step_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable2Step_init_unchained() internal onlyInitializing {\n    }\n    address private _pendingOwner;\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        return _pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        _pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        delete _pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n        _transferOwnership(sender);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"},{"file_path":"src/L1/SystemConfig.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { ISemver } from \"src/universal/ISemver.sol\";\nimport { ResourceMetering } from \"src/L1/ResourceMetering.sol\";\nimport { Storage } from \"src/libraries/Storage.sol\";\nimport { Constants } from \"src/libraries/Constants.sol\";\n\n/// @title SystemConfig\n/// @notice The SystemConfig contract is used to manage configuration of an Optimism network.\n///         All configuration is stored on L1 and picked up by L2 as part of the derviation of\n///         the L2 chain.\ncontract SystemConfig is OwnableUpgradeable, ISemver {\n    /// @notice Enum representing different types of updates.\n    /// @custom:value BATCHER              Represents an update to the batcher hash.\n    /// @custom:value GAS_CONFIG           Represents an update to txn fee config on L2.\n    /// @custom:value GAS_LIMIT            Represents an update to gas limit on L2.\n    /// @custom:value UNSAFE_BLOCK_SIGNER  Represents an update to the signer key for unsafe\n    ///                                    block distrubution.\n    enum UpdateType {\n        BATCHER,\n        GAS_CONFIG,\n        GAS_LIMIT,\n        UNSAFE_BLOCK_SIGNER\n    }\n\n    /// @notice Struct representing the addresses of L1 system contracts. These should be the\n    ///         proxies and will differ for each OP Stack chain.\n    struct Addresses {\n        address l1CrossDomainMessenger;\n        address l1ERC721Bridge;\n        address l1StandardBridge;\n        address l2OutputOracle;\n        address optimismPortal;\n        address optimismMintableERC20Factory;\n    }\n\n    /// @notice Version identifier, used for upgrades.\n    uint256 public constant VERSION = 0;\n\n    /// @notice Storage slot that the unsafe block signer is stored at.\n    ///         Storing it at this deterministic storage slot allows for decoupling the storage\n    ///         layout from the way that `solc` lays out storage. The `op-node` uses a storage\n    ///         proof to fetch this value.\n    /// @dev    NOTE: this value will be migrated to another storage slot in a future version.\n    ///         User input should not be placed in storage in this contract until this migration\n    ///         happens. It is unlikely that keccak second preimage resistance will be broken,\n    ///         but it is better to be safe than sorry.\n    bytes32 public constant UNSAFE_BLOCK_SIGNER_SLOT = keccak256(\"systemconfig.unsafeblocksigner\");\n\n    /// @notice Storage slot that the L1CrossDomainMessenger address is stored at.\n    bytes32 public constant L1_CROSS_DOMAIN_MESSENGER_SLOT =\n        bytes32(uint256(keccak256(\"systemconfig.l1crossdomainmessenger\")) - 1);\n\n    /// @notice Storage slot that the L1ERC721Bridge address is stored at.\n    bytes32 public constant L1_ERC_721_BRIDGE_SLOT = bytes32(uint256(keccak256(\"systemconfig.l1erc721bridge\")) - 1);\n\n    /// @notice Storage slot that the L1StandardBridge address is stored at.\n    bytes32 public constant L1_STANDARD_BRIDGE_SLOT = bytes32(uint256(keccak256(\"systemconfig.l1standardbridge\")) - 1);\n\n    /// @notice Storage slot that the L2OutputOracle address is stored at.\n    bytes32 public constant L2_OUTPUT_ORACLE_SLOT = bytes32(uint256(keccak256(\"systemconfig.l2outputoracle\")) - 1);\n\n    /// @notice Storage slot that the OptimismPortal address is stored at.\n    bytes32 public constant OPTIMISM_PORTAL_SLOT = bytes32(uint256(keccak256(\"systemconfig.optimismportal\")) - 1);\n\n    /// @notice Storage slot that the OptimismMintableERC20Factory address is stored at.\n    bytes32 public constant OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT =\n        bytes32(uint256(keccak256(\"systemconfig.optimismmintableerc20factory\")) - 1);\n\n    /// @notice Storage slot that the batch inbox address is stored at.\n    bytes32 public constant BATCH_INBOX_SLOT = bytes32(uint256(keccak256(\"systemconfig.batchinbox\")) - 1);\n\n    /// @notice Fixed L2 gas overhead. Used as part of the L2 fee calculation.\n    uint256 public overhead;\n\n    /// @notice Dynamic L2 gas overhead. Used as part of the L2 fee calculation.\n    uint256 public scalar;\n\n    /// @notice Identifier for the batcher.\n    ///         For version 1 of this configuration, this is represented as an address left-padded\n    ///         with zeros to 32 bytes.\n    bytes32 public batcherHash;\n\n    /// @notice L2 block gas limit.\n    uint64 public gasLimit;\n\n    /// @notice The configuration for the deposit fee market.\n    ///         Used by the OptimismPortal to meter the cost of buying L2 gas on L1.\n    ///         Set as internal with a getter so that the struct is returned instead of a tuple.\n    ResourceMetering.ResourceConfig internal _resourceConfig;\n\n    /// @notice Emitted when configuration is updated.\n    /// @param version    SystemConfig version.\n    /// @param updateType Type of update.\n    /// @param data       Encoded update data.\n    event ConfigUpdate(uint256 indexed version, UpdateType indexed updateType, bytes data);\n\n    /// @notice The block at which the op-node can start searching for logs from.\n    uint256 public startBlock;\n\n    /// @notice Semantic version.\n    /// @custom:semver 1.10.0\n    string public constant version = \"1.10.0\";\n\n    /// @notice Constructs the SystemConfig contract. Cannot set\n    ///         the owner to `address(0)` due to the Ownable contract's\n    ///         implementation, so set it to `address(0xdEaD)`\n    constructor() {\n        initialize({\n            _owner: address(0xdEaD),\n            _overhead: 0,\n            _scalar: 0,\n            _batcherHash: bytes32(0),\n            _gasLimit: 1,\n            _unsafeBlockSigner: address(0),\n            _config: ResourceMetering.ResourceConfig({\n                maxResourceLimit: 1,\n                elasticityMultiplier: 1,\n                baseFeeMaxChangeDenominator: 2,\n                minimumBaseFee: 0,\n                systemTxMaxGas: 0,\n                maximumBaseFee: 0\n            }),\n            _startBlock: type(uint256).max,\n            _batchInbox: address(0),\n            _addresses: SystemConfig.Addresses({\n                l1CrossDomainMessenger: address(0),\n                l1ERC721Bridge: address(0),\n                l1StandardBridge: address(0),\n                l2OutputOracle: address(0),\n                optimismPortal: address(0),\n                optimismMintableERC20Factory: address(0)\n            })\n        });\n    }\n\n    /// @notice Initializer.\n    ///         The resource config must be set before the require check.\n    /// @param _owner             Initial owner of the contract.\n    /// @param _overhead          Initial overhead value.\n    /// @param _scalar            Initial scalar value.\n    /// @param _batcherHash       Initial batcher hash.\n    /// @param _gasLimit          Initial gas limit.\n    /// @param _unsafeBlockSigner Initial unsafe block signer address.\n    /// @param _config            Initial ResourceConfig.\n    /// @param _startBlock        Starting block for the op-node to search for logs from.\n    ///                           Contracts that were deployed before this field existed\n    ///                           need to have this field set manually via an override.\n    ///                           Newly deployed contracts should set this value to uint256(0).\n    /// @param _batchInbox        Batch inbox address. An identifier for the op-node to find\n    ///                           canonical data.\n    /// @param _addresses         Set of L1 contract addresses. These should be the proxies.\n    function initialize(\n        address _owner,\n        uint256 _overhead,\n        uint256 _scalar,\n        bytes32 _batcherHash,\n        uint64 _gasLimit,\n        address _unsafeBlockSigner,\n        ResourceMetering.ResourceConfig memory _config,\n        uint256 _startBlock,\n        address _batchInbox,\n        SystemConfig.Addresses memory _addresses\n    )\n        public\n        reinitializer(Constants.INITIALIZER)\n    {\n        __Ownable_init();\n        transferOwnership(_owner);\n\n        // These are set in ascending order of their UpdateTypes.\n        _setBatcherHash(_batcherHash);\n        _setGasConfig({ _overhead: _overhead, _scalar: _scalar });\n        _setGasLimit(_gasLimit);\n        _setUnsafeBlockSigner(_unsafeBlockSigner);\n\n        Storage.setAddress(BATCH_INBOX_SLOT, _batchInbox);\n        Storage.setAddress(L1_CROSS_DOMAIN_MESSENGER_SLOT, _addresses.l1CrossDomainMessenger);\n        Storage.setAddress(L1_ERC_721_BRIDGE_SLOT, _addresses.l1ERC721Bridge);\n        Storage.setAddress(L1_STANDARD_BRIDGE_SLOT, _addresses.l1StandardBridge);\n        Storage.setAddress(L2_OUTPUT_ORACLE_SLOT, _addresses.l2OutputOracle);\n        Storage.setAddress(OPTIMISM_PORTAL_SLOT, _addresses.optimismPortal);\n        Storage.setAddress(OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT, _addresses.optimismMintableERC20Factory);\n\n        _setStartBlock(_startBlock);\n\n        _setResourceConfig(_config);\n        require(_gasLimit >= minimumGasLimit(), \"SystemConfig: gas limit too low\");\n    }\n\n    /// @notice Returns the minimum L2 gas limit that can be safely set for the system to\n    ///         operate. The L2 gas limit must be larger than or equal to the amount of\n    ///         gas that is allocated for deposits per block plus the amount of gas that\n    ///         is allocated for the system transaction.\n    ///         This function is used to determine if changes to parameters are safe.\n    /// @return uint64 Minimum gas limit.\n    function minimumGasLimit() public view returns (uint64) {\n        return uint64(_resourceConfig.maxResourceLimit) + uint64(_resourceConfig.systemTxMaxGas);\n    }\n\n    /// @notice High level getter for the unsafe block signer address.\n    ///         Unsafe blocks can be propagated across the p2p network if they are signed by the\n    ///         key corresponding to this address.\n    /// @return addr_ Address of the unsafe block signer.\n    // solhint-disable-next-line ordering\n    function unsafeBlockSigner() public view returns (address addr_) {\n        addr_ = Storage.getAddress(UNSAFE_BLOCK_SIGNER_SLOT);\n    }\n\n    /// @notice Getter for the L1CrossDomainMessenger address.\n    function l1CrossDomainMessenger() external view returns (address addr_) {\n        addr_ = Storage.getAddress(L1_CROSS_DOMAIN_MESSENGER_SLOT);\n    }\n\n    /// @notice Getter for the L1ERC721Bridge address.\n    function l1ERC721Bridge() external view returns (address addr_) {\n        addr_ = Storage.getAddress(L1_ERC_721_BRIDGE_SLOT);\n    }\n\n    /// @notice Getter for the L1StandardBridge address.\n    function l1StandardBridge() external view returns (address addr_) {\n        addr_ = Storage.getAddress(L1_STANDARD_BRIDGE_SLOT);\n    }\n\n    /// @notice Getter for the L2OutputOracle address.\n    function l2OutputOracle() external view returns (address addr_) {\n        addr_ = Storage.getAddress(L2_OUTPUT_ORACLE_SLOT);\n    }\n\n    /// @notice Getter for the OptimismPortal address.\n    function optimismPortal() external view returns (address addr_) {\n        addr_ = Storage.getAddress(OPTIMISM_PORTAL_SLOT);\n    }\n\n    /// @notice Getter for the OptimismMintableERC20Factory address.\n    function optimismMintableERC20Factory() external view returns (address addr_) {\n        addr_ = Storage.getAddress(OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT);\n    }\n\n    /// @notice Getter for the BatchInbox address.\n    function batchInbox() external view returns (address addr_) {\n        addr_ = Storage.getAddress(BATCH_INBOX_SLOT);\n    }\n\n    /// @notice Sets the start block in a backwards compatible way. Proxies\n    ///         that were initialized before the startBlock existed in storage\n    ///         can have their start block set by a user provided override.\n    ///         A start block of 0 indicates that there is no override and the\n    ///         start block will be set by `block.number`.\n    /// @dev    This logic is used to patch legacy deployments with new storage values.\n    ///         Use the override if it is provided as a non zero value and the value\n    ///         has not already been set in storage. Use `block.number` if the value\n    ///         has already been set in storage\n    /// @param  _startBlock The start block override to set in storage.\n    function _setStartBlock(uint256 _startBlock) internal {\n        if (_startBlock != 0 && startBlock == 0) {\n            // There is an override and it is not already set, this is for legacy chains.\n            startBlock = _startBlock;\n        } else if (startBlock == 0) {\n            // There is no override and it is not set in storage. Set it to the block number.\n            // This is for newly deployed chains.\n            startBlock = block.number;\n        }\n    }\n\n    /// @notice Updates the unsafe block signer address. Can only be called by the owner.\n    /// @param _unsafeBlockSigner New unsafe block signer address.\n    function setUnsafeBlockSigner(address _unsafeBlockSigner) external onlyOwner {\n        _setUnsafeBlockSigner(_unsafeBlockSigner);\n    }\n\n    /// @notice Updates the unsafe block signer address.\n    /// @param _unsafeBlockSigner New unsafe block signer address.\n    function _setUnsafeBlockSigner(address _unsafeBlockSigner) internal {\n        Storage.setAddress(UNSAFE_BLOCK_SIGNER_SLOT, _unsafeBlockSigner);\n\n        bytes memory data = abi.encode(_unsafeBlockSigner);\n        emit ConfigUpdate(VERSION, UpdateType.UNSAFE_BLOCK_SIGNER, data);\n    }\n\n    /// @notice Updates the batcher hash. Can only be called by the owner.\n    /// @param _batcherHash New batcher hash.\n    function setBatcherHash(bytes32 _batcherHash) external onlyOwner {\n        _setBatcherHash(_batcherHash);\n    }\n\n    /// @notice Internal function for updating the batcher hash.\n    /// @param _batcherHash New batcher hash.\n    function _setBatcherHash(bytes32 _batcherHash) internal {\n        batcherHash = _batcherHash;\n\n        bytes memory data = abi.encode(_batcherHash);\n        emit ConfigUpdate(VERSION, UpdateType.BATCHER, data);\n    }\n\n    /// @notice Updates gas config. Can only be called by the owner.\n    /// @param _overhead New overhead value.\n    /// @param _scalar   New scalar value.\n    function setGasConfig(uint256 _overhead, uint256 _scalar) external onlyOwner {\n        _setGasConfig(_overhead, _scalar);\n    }\n\n    /// @notice Internal function for updating the gas config.\n    /// @param _overhead New overhead value.\n    /// @param _scalar   New scalar value.\n    function _setGasConfig(uint256 _overhead, uint256 _scalar) internal {\n        overhead = _overhead;\n        scalar = _scalar;\n\n        bytes memory data = abi.encode(_overhead, _scalar);\n        emit ConfigUpdate(VERSION, UpdateType.GAS_CONFIG, data);\n    }\n\n    /// @notice Updates the L2 gas limit. Can only be called by the owner.\n    /// @param _gasLimit New gas limit.\n    function setGasLimit(uint64 _gasLimit) external onlyOwner {\n        _setGasLimit(_gasLimit);\n    }\n\n    /// @notice Internal function for updating the L2 gas limit.\n    /// @param _gasLimit New gas limit.\n    function _setGasLimit(uint64 _gasLimit) internal {\n        require(_gasLimit >= minimumGasLimit(), \"SystemConfig: gas limit too low\");\n        gasLimit = _gasLimit;\n\n        bytes memory data = abi.encode(_gasLimit);\n        emit ConfigUpdate(VERSION, UpdateType.GAS_LIMIT, data);\n    }\n\n    /// @notice A getter for the resource config.\n    ///         Ensures that the struct is returned instead of a tuple.\n    /// @return ResourceConfig\n    function resourceConfig() external view returns (ResourceMetering.ResourceConfig memory) {\n        return _resourceConfig;\n    }\n\n    /// @notice An external setter for the resource config.\n    ///         In the future, this method may emit an event that the `op-node` picks up\n    ///         for when the resource config is changed.\n    /// @param _config The new resource config values.\n    function setResourceConfig(ResourceMetering.ResourceConfig memory _config) external onlyOwner {\n        _setResourceConfig(_config);\n    }\n\n    /// @notice An internal setter for the resource config.\n    ///         Ensures that the config is sane before storing it by checking for invariants.\n    /// @param _config The new resource config.\n    function _setResourceConfig(ResourceMetering.ResourceConfig memory _config) internal {\n        // Min base fee must be less than or equal to max base fee.\n        require(\n            _config.minimumBaseFee <= _config.maximumBaseFee, \"SystemConfig: min base fee must be less than max base\"\n        );\n        // Base fee change denominator must be greater than 1.\n        require(_config.baseFeeMaxChangeDenominator > 1, \"SystemConfig: denominator must be larger than 1\");\n        // Max resource limit plus system tx gas must be less than or equal to the L2 gas limit.\n        // The gas limit must be increased before these values can be increased.\n        require(_config.maxResourceLimit + _config.systemTxMaxGas <= gasLimit, \"SystemConfig: gas limit too low\");\n        // Elasticity multiplier must be greater than 0.\n        require(_config.elasticityMultiplier > 0, \"SystemConfig: elasticity multiplier cannot be 0\");\n        // No precision loss when computing target resource limit.\n        require(\n            ((_config.maxResourceLimit / _config.elasticityMultiplier) * _config.elasticityMultiplier)\n                == _config.maxResourceLimit,\n            \"SystemConfig: precision loss with target resource limit\"\n        );\n\n        _resourceConfig = _config;\n    }\n}\n"},{"file_path":"src/libraries/Constants.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { ResourceMetering } from \"../L1/ResourceMetering.sol\";\n\n/// @title Constants\n/// @notice Constants is a library for storing constants. Simple! Don't put everything in here, just\n///         the stuff used in multiple contracts. Constants that only apply to a single contract\n///         should be defined in that contract instead.\nlibrary Constants {\n    /// @notice Special address to be used as the tx origin for gas estimation calls in the\n    ///         OptimismPortal and CrossDomainMessenger calls. You only need to use this address if\n    ///         the minimum gas limit specified by the user is not actually enough to execute the\n    ///         given message and you're attempting to estimate the actual necessary gas limit. We\n    ///         use address(1) because it's the ecrecover precompile and therefore guaranteed to\n    ///         never have any code on any EVM chain.\n    address internal constant ESTIMATION_ADDRESS = address(1);\n\n    /// @notice Value used for the L2 sender storage slot in both the OptimismPortal and the\n    ///         CrossDomainMessenger contracts before an actual sender is set. This value is\n    ///         non-zero to reduce the gas cost of message passing transactions.\n    address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD;\n\n    /// @notice The storage slot that holds the address of a proxy implementation.\n    /// @dev `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`\n    bytes32 internal constant PROXY_IMPLEMENTATION_ADDRESS =\n        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /// @notice The storage slot that holds the address of the owner.\n    /// @dev `bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)`\n    bytes32 internal constant PROXY_OWNER_ADDRESS = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /// @notice Returns the default values for the ResourceConfig. These are the recommended values\n    ///         for a production network.\n    function DEFAULT_RESOURCE_CONFIG() internal pure returns (ResourceMetering.ResourceConfig memory) {\n        ResourceMetering.ResourceConfig memory config = ResourceMetering.ResourceConfig({\n            maxResourceLimit: 20_000_000,\n            elasticityMultiplier: 10,\n            baseFeeMaxChangeDenominator: 8,\n            minimumBaseFee: 1 gwei,\n            systemTxMaxGas: 1_000_000,\n            maximumBaseFee: type(uint128).max\n        });\n        return config;\n    }\n\n    /// @notice The `reinitailizer` input for upgradable contracts. This value must be updated\n    ///         each time that the contracts are deployed.\n    uint8 internal constant INITIALIZER = 1;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Strings.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n            value /= 10;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        if (value == 0) {\n            return \"0x00\";\n        }\n        uint256 temp = value;\n        uint256 length = 0;\n        while (temp != 0) {\n            length++;\n            temp >>= 8;\n        }\n        return toHexString(value, length);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _HEX_SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n}\n"},{"file_path":"src/libraries/trie/SecureMerkleTrie.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { MerkleTrie } from \"./MerkleTrie.sol\";\n\n/// @title SecureMerkleTrie\n/// @notice SecureMerkleTrie is a thin wrapper around the MerkleTrie library that hashes the input\n///         keys. Ethereum's state trie hashes input keys before storing them.\nlibrary SecureMerkleTrie {\n    /// @notice Verifies a proof that a given key/value pair is present in the Merkle trie.\n    /// @param _key   Key of the node to search for, as a hex string.\n    /// @param _value Value of the node to search for, as a hex string.\n    /// @param _proof Merkle trie inclusion proof for the desired node. Unlike traditional Merkle\n    ///               trees, this proof is executed top-down and consists of a list of RLP-encoded\n    ///               nodes that make a path down to the target node.\n    /// @param _root  Known root of the Merkle trie. Used to verify that the included proof is\n    ///               correctly constructed.\n    /// @return valid_ Whether or not the proof is valid.\n    function verifyInclusionProof(\n        bytes memory _key,\n        bytes memory _value,\n        bytes[] memory _proof,\n        bytes32 _root\n    )\n        internal\n        pure\n        returns (bool valid_)\n    {\n        bytes memory key = _getSecureKey(_key);\n        valid_ = MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);\n    }\n\n    /// @notice Retrieves the value associated with a given key.\n    /// @param _key   Key to search for, as hex bytes.\n    /// @param _proof Merkle trie inclusion proof for the key.\n    /// @param _root  Known root of the Merkle trie.\n    /// @return value_ Value of the key if it exists.\n    function get(bytes memory _key, bytes[] memory _proof, bytes32 _root) internal pure returns (bytes memory value_) {\n        bytes memory key = _getSecureKey(_key);\n        value_ = MerkleTrie.get(key, _proof, _root);\n    }\n\n    /// @notice Computes the hashed version of the input key.\n    /// @param _key Key to hash.\n    /// @return hash_ Hashed version of the key.\n    function _getSecureKey(bytes memory _key) private pure returns (bytes memory hash_) {\n        hash_ = abi.encodePacked(keccak256(_key));\n    }\n}\n"},{"file_path":"src/universal/IOptimismMintableERC20.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { IERC165 } from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/// @title IOptimismMintableERC20\n/// @notice This interface is available on the OptimismMintableERC20 contract.\n///         We declare it as a separate interface so that it can be used in\n///         custom implementations of OptimismMintableERC20.\ninterface IOptimismMintableERC20 is IERC165 {\n    function remoteToken() external view returns (address);\n\n    function bridge() external returns (address);\n\n    function mint(address _to, uint256 _amount) external;\n\n    function burn(address _from, uint256 _amount) external;\n}\n\n/// @custom:legacy\n/// @title ILegacyMintableERC20\n/// @notice This interface was available on the legacy L2StandardERC20 contract.\n///         It remains available on the OptimismMintableERC20 contract for\n///         backwards compatibility.\ninterface ILegacyMintableERC20 is IERC165 {\n    function l1Token() external view returns (address);\n\n    function mint(address _to, uint256 _amount) external;\n\n    function burn(address _from, uint256 _amount) external;\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * The default value of {decimals} is 18. To select a different value for\n     * {decimals} you should overload it.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless this function is\n     * overridden;\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n        }\n        _balances[to] += amount;\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        _balances[account] += amount;\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n        }\n        _totalSupply -= amount;\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n}\n"},{"file_path":"src/mainnet-bridge/withdrawal-queue/WithdrawalQueue.sol","source_code":"// SPDX-FileCopyrightText: 2023 Lido <info@lido.fi>\n// SPDX-License-Identifier: GPL-3.0\n\npragma solidity 0.8.15;\n\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\n\n/// @title WithdrawalQueue\n/// @notice Queue for storing and managing withdrawal requests.\n///         This contract is based on Lido's WithdrawalQueue and has been\n///         modified to support Blast specific logic such as withdrawal discounts.\ncontract WithdrawalQueue is Initializable {\n    using EnumerableSet for EnumerableSet.UintSet;\n    using SafeERC20 for IERC20;\n\n    /// @notice The L1 gas limit set when sending eth to the YieldManager.\n    uint256 internal constant SEND_DEFAULT_GAS_LIMIT = 100_000;\n\n    /// @notice precision base for share rate\n    uint256 internal constant E27_PRECISION_BASE = 1e27;\n\n    /// @notice return value for the `find...` methods in case of no result\n    uint256 internal constant NOT_FOUND = 0;\n\n    address public immutable TOKEN;\n\n    WithdrawalRequest[] private _requests;\n    mapping(address => EnumerableSet.UintSet) private _requestsByOwner;\n    Checkpoint[] private _checkpoints;\n    uint256 private lastRequestId;\n    uint256 private lastFinalizedRequestId;\n    uint256 private lastCheckpointId;\n    uint256 private lockedBalance;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    ///         A gap size of 42 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[42] private __gap;\n\n    /// @notice structure representing a request for withdrawal\n    struct WithdrawalRequest {\n        /// @notice sum of the all tokens submitted for withdrawals including this request (nominal amount)\n        uint128 cumulativeAmount;\n        /// @notice address that can claim the request and receives the funds\n        address recipient;\n        /// @notice block.timestamp when the request was created\n        uint40 timestamp;\n        /// @notice flag if the request was claimed\n        bool claimed;\n    }\n\n    /// @notice output format struct for `_getWithdrawalStatus()` method\n    struct WithdrawalRequestStatus {\n        /// @notice nominal token amount that was locked on withdrawal queue for this request\n        uint256 amount;\n        /// @notice address that can claim or transfer this request\n        address recipient;\n        /// @notice timestamp of when the request was created, in seconds\n        uint256 timestamp;\n        /// @notice true, if request is finalized\n        bool isFinalized;\n        /// @notice true, if request is claimed. Request is claimable if (isFinalized && !isClaimed)\n        bool isClaimed;\n    }\n\n    /// @notice structure to store discounts for requests that are affected by negative rebase\n    /// All requests covered by the checkpoint are affected by the same discount rate `sharePrice`.\n    struct Checkpoint {\n        uint256 fromRequestId;\n        uint256 sharePrice;\n    }\n\n    /// @dev amount represents the nominal amount of tokens that were withdrawn (burned) on L2.\n    event WithdrawalRequested(\n        uint256 indexed requestId,\n        address indexed requestor,\n        address indexed recipient,\n        uint256 amount\n    );\n\n    /// @dev amountOfETHLocked represents the real amount of ETH that was locked in the queue and will be\n    ///      transferred to the recipient on claim.\n    event WithdrawalsFinalized(\n        uint256 indexed from,\n        uint256 indexed to,\n        uint256 indexed checkpointId,\n        uint256 amountOfETHLocked,\n        uint256 timestamp,\n        uint256 sharePrice\n    );\n\n    /// @dev amount represents the real amount of ETH that was transferred to the recipient.\n    event WithdrawalClaimed(\n        uint256 indexed requestId, address indexed recipient, uint256 amountOfETH\n    );\n\n    error InvalidRequestId(uint256 _requestId);\n    error InvalidRequestIdRange(uint256 startId, uint256 endId);\n    error InvalidSharePrice();\n    error RequestNotFoundOrNotFinalized(uint256 _requestId);\n    error RequestAlreadyClaimed(uint256 _requestId);\n    error InvalidHint(uint256 _hint);\n    error RequestIdsNotSorted();\n    error CallerIsNotRecipient();\n    error WithdrawalTransferFailed();\n    error InsufficientBalance();\n\n    constructor(address _token) {\n        TOKEN = _token;\n    }\n\n    /// @notice initialize the contract with the dummy request and checkpoint\n    ///         as the zero elements of the corresponding arrays so that\n    ///         the first element of the array has index 1\n    function __WithdrawalQueue_init() internal onlyInitializing {\n        _requests.push(WithdrawalRequest(0, address(0), uint40(block.timestamp), true));\n        _checkpoints.push(Checkpoint(0, 0));\n    }\n\n    function getWithdrawalStatus(uint256[] calldata _requestIds)\n        external\n        view\n        returns (WithdrawalRequestStatus[] memory statuses)\n    {\n        statuses = new WithdrawalRequestStatus[](_requestIds.length);\n        for (uint256 i = 0; i < _requestIds.length; ++i) {\n            statuses[i] = _getStatus(_requestIds[i]);\n        }\n    }\n\n    function getWithdrawalRequests(address _owner) external view returns (uint256[] memory requestIds) {\n        return _requestsByOwner[_owner].values();\n    }\n\n    function getClaimableEther(uint256[] calldata _requestIds, uint256[] calldata _hintIds)\n        external\n        view\n        returns (uint256[] memory claimableEthValues)\n    {\n        claimableEthValues = new uint256[](_requestIds.length);\n        for (uint256 i = 0; i < _requestIds.length; ++i) {\n            claimableEthValues[i] = _getClaimableEther(_requestIds[i], _hintIds[i]);\n        }\n    }\n\n    function _getClaimableEther(uint256 _requestId, uint256 _hintId) internal view returns (uint256) {\n        if (_requestId == 0 || _requestId > lastRequestId) revert InvalidRequestId(_requestId);\n\n        if (_requestId > lastFinalizedRequestId) return 0;\n\n        WithdrawalRequest storage request = _requests[_requestId];\n        if (request.claimed) return 0;\n\n        return _calculateClaimableEther(_requestId, _hintId);\n    }\n\n    /// @notice id of the last request\n    ///  NB! requests are indexed from 1, so it returns 0 if there is no requests in the queue\n    function getLastRequestId() external view returns (uint256) {\n        return lastRequestId;\n    }\n\n    /// @notice id of the last finalized request\n    ///  NB! requests are indexed from 1, so it returns 0 if there is no finalized requests in the queue\n    function getLastFinalizedRequestId() external view returns (uint256) {\n        return lastFinalizedRequestId;\n    }\n\n    /// @notice amount of ETH on this contract balance that is locked for withdrawal and available to claim\n    ///  NB! this is the real amount of ETH (i.e. sum of (nominal amount of ETH burned on L2 * sharePrice))\n    function getLockedBalance() public view returns (uint256) {\n        return lockedBalance;\n    }\n\n    /// @notice return the last checkpoint id in the queue\n    function getLastCheckpointId() external view returns (uint256) {\n        return lastCheckpointId;\n    }\n\n    /// @notice return the number of unfinalized requests in the queue\n    function unfinalizedRequestNumber() public view returns (uint256) {\n        return lastRequestId - lastFinalizedRequestId;\n    }\n\n    /// @notice Returns the amount of ETH in the queue yet to be finalized\n    ///  NB! this is the nominal amount of ETH burned on L2\n    function unfinalizedAmount() internal view returns (uint256) {\n        return\n            _requests[lastRequestId].cumulativeAmount - _requests[lastFinalizedRequestId].cumulativeAmount;\n    }\n\n    /// @dev Finalize requests in the queue\n    /// @notice sharePrice has 1e27 precision\n    ///  Emits WithdrawalsFinalized event.\n    function _finalize(\n        uint256 _lastRequestIdToBeFinalized,\n        uint256 availableBalance,\n        uint256 sharePrice\n    ) internal returns (uint256 nominalAmountToFinalize, uint256 realAmountToFinalize, uint256 checkpointId) {\n        // share price cannot be larger than 1e27\n        if (sharePrice > E27_PRECISION_BASE) {\n            revert InvalidSharePrice();\n        }\n\n        if (_lastRequestIdToBeFinalized != 0) {\n            if (_lastRequestIdToBeFinalized > lastRequestId) revert InvalidRequestId(_lastRequestIdToBeFinalized);\n            uint256 _lastFinalizedRequestId = lastFinalizedRequestId;\n            if (_lastRequestIdToBeFinalized <= _lastFinalizedRequestId) revert InvalidRequestId(_lastRequestIdToBeFinalized);\n\n            WithdrawalRequest memory lastFinalizedRequest = _requests[_lastFinalizedRequestId];\n            WithdrawalRequest memory requestToFinalize = _requests[_lastRequestIdToBeFinalized];\n\n            nominalAmountToFinalize = requestToFinalize.cumulativeAmount - lastFinalizedRequest.cumulativeAmount;\n            realAmountToFinalize = (nominalAmountToFinalize * sharePrice) / E27_PRECISION_BASE;\n            if (realAmountToFinalize > availableBalance) {\n                revert InsufficientBalance();\n            }\n\n            uint256 firstRequestIdToFinalize = _lastFinalizedRequestId + 1;\n\n            lockedBalance += realAmountToFinalize;\n            lastFinalizedRequestId = _lastRequestIdToBeFinalized;\n\n            checkpointId = _createCheckpoint(firstRequestIdToFinalize, sharePrice);\n\n            emit WithdrawalsFinalized(\n                firstRequestIdToFinalize,\n                _lastRequestIdToBeFinalized,\n                checkpointId,\n                realAmountToFinalize,\n                block.timestamp,\n                sharePrice\n            );\n        }\n    }\n\n    /// @notice Finds the list of hints for the given `_requestIds` searching among the checkpoints with indices\n    ///  in the range  `[_firstIndex, _lastIndex]`.\n    ///  NB! Array of request ids should be sorted\n    ///  NB! `_firstIndex` should be greater than 0, because checkpoint list is 1-based array\n    ///  Usage: findCheckpointHints(_requestIds, 1, getLastCheckpointIndex())\n    /// @param _requestIds ids of the requests sorted in the ascending order to get hints for\n    /// @param _firstIndex left boundary of the search range. Should be greater than 0\n    /// @param _lastIndex right boundary of the search range. Should be less than or equal to getLastCheckpointIndex()\n    /// @return hintIds array of hints used to find required checkpoint for the request\n    function findCheckpointHints(uint256[] calldata _requestIds, uint256 _firstIndex, uint256 _lastIndex)\n        external\n        view\n        returns (uint256[] memory hintIds)\n    {\n        hintIds = new uint256[](_requestIds.length);\n        uint256 prevRequestId = 0;\n        for (uint256 i = 0; i < _requestIds.length; ++i) {\n            if (_requestIds[i] < prevRequestId) {\n                revert RequestIdsNotSorted();\n            }\n            hintIds[i] = findCheckpointHint(_requestIds[i], _firstIndex, _lastIndex);\n            _firstIndex = hintIds[i];\n            prevRequestId = _requestIds[i];\n        }\n    }\n\n    /// @dev View function to find a checkpoint hint to use in `claimWithdrawal()` and `getClaimableEther()`\n    ///  Search will be performed in the range of `[_firstIndex, _lastIndex]`\n    ///\n    /// @param _requestId request id to search the checkpoint for\n    /// @param _start index of the left boundary of the search range, should be greater than 0\n    /// @param _end index of the right boundary of the search range, should be less than or equal\n    ///  to queue.lastCheckpointId\n    ///\n    /// @return hint for later use in other methods or 0 if hint not found in the range\n    function findCheckpointHint(uint256 _requestId, uint256 _start, uint256 _end) public view returns (uint256) {\n        if (_requestId == 0 || _requestId > lastRequestId) {\n            revert InvalidRequestId(_requestId);\n        }\n\n        uint256 lastCheckpointIndex = lastCheckpointId;\n        if (_start == 0 || _end > lastCheckpointIndex) {\n            revert InvalidRequestIdRange(_start, _end);\n        }\n\n        if (lastCheckpointIndex == 0 || _requestId > lastFinalizedRequestId || _start > _end) {\n            return NOT_FOUND;\n        }\n\n        // Right boundary\n        if (_requestId >= _checkpoints[_end].fromRequestId) {\n            // it's the last checkpoint, so it's valid\n            if (_end == lastCheckpointIndex) {\n                return _end;\n            }\n            // it fits right before the next checkpoint\n            if (_requestId < _checkpoints[_end + 1].fromRequestId) {\n                return _end;\n            }\n\n            return NOT_FOUND;\n        }\n        // Left boundary\n        if (_requestId < _checkpoints[_start].fromRequestId) {\n            return NOT_FOUND;\n        }\n\n        // Binary search\n        uint256 min = _start;\n        uint256 max = _end - 1;\n\n        while (max > min) {\n            uint256 mid = (max + min + 1) / 2;\n            if (_checkpoints[mid].fromRequestId <= _requestId) {\n                min = mid;\n            } else {\n                max = mid - 1;\n            }\n        }\n        return min;\n    }\n\n    /// @dev Returns the status of the withdrawal request with `_requestId` id\n    function _getStatus(uint256 _requestId) internal view returns (WithdrawalRequestStatus memory status) {\n        if (_requestId == 0 || _requestId > lastRequestId) revert InvalidRequestId(_requestId);\n\n        WithdrawalRequest memory request = _requests[_requestId];\n        WithdrawalRequest memory previousRequest = _requests[_requestId - 1];\n\n        status = WithdrawalRequestStatus(\n            request.cumulativeAmount - previousRequest.cumulativeAmount,\n            request.recipient,\n            request.timestamp,\n            _requestId <= lastFinalizedRequestId,\n            request.claimed\n        );\n    }\n\n    /// @dev creates a new `WithdrawalRequest` in the queue\n    ///  Emits WithdrawalRequested event\n    function _requestWithdrawal(address recipient, uint256 amount)\n        internal\n        returns (uint256 requestId)\n    {\n        uint256 _lastRequestId = lastRequestId;\n        WithdrawalRequest memory lastRequest = _requests[_lastRequestId];\n\n        uint128 cumulativeAmount = lastRequest.cumulativeAmount + SafeCast.toUint128(amount);\n\n        requestId = _lastRequestId + 1;\n\n        lastRequestId = requestId;\n\n        WithdrawalRequest memory newRequest = WithdrawalRequest(\n            cumulativeAmount,\n            recipient,\n            uint40(block.timestamp),\n            false\n        );\n        _requests.push(newRequest);\n        _requestsByOwner[recipient].add(requestId);\n\n        emit WithdrawalRequested(requestId, msg.sender, recipient, amount);\n    }\n\n    /// @dev assumes firstRequestIdToFinalize > _lastFinalizedRequestId && sharePrice <= 1e27\n    function _createCheckpoint(uint256 firstRequestIdToFinalize, uint256 sharePrice) internal returns (uint256) {\n        _checkpoints.push(Checkpoint(firstRequestIdToFinalize, sharePrice));\n        lastCheckpointId += 1;\n        return lastCheckpointId;\n    }\n\n    /// @dev can only be called by request.recipient (YieldManager)\n    function claimWithdrawal(uint256 _requestId, uint256 _hintId) external returns (bool success) {\n        if (_requestId == 0) revert InvalidRequestId(_requestId);\n        if (_requestId > lastFinalizedRequestId) revert RequestNotFoundOrNotFinalized(_requestId);\n\n        WithdrawalRequest storage request = _requests[_requestId];\n\n        if (request.claimed) revert RequestAlreadyClaimed(_requestId);\n        request.claimed = true;\n\n        address recipient = request.recipient;\n        if (msg.sender != recipient) {\n            revert CallerIsNotRecipient();\n        }\n\n        uint256 realAmount = _calculateClaimableEther(_requestId, _hintId);\n        lockedBalance -= realAmount;\n\n        if (TOKEN == address(0)) {\n            (success) = SafeCall.send(recipient, SEND_DEFAULT_GAS_LIMIT, realAmount);\n        } else {\n            IERC20(TOKEN).safeTransfer(recipient, realAmount);\n            success = true;\n        }\n\n        if (!success) {\n            revert WithdrawalTransferFailed();\n        }\n\n        emit WithdrawalClaimed(_requestId, recipient, realAmount);\n    }\n\n    /// @dev Calculate the amount of ETH that can be claimed for the withdrawal request with `_requestId`.\n    ///  NB! This function returns the real amount of ETH that can be claimed by the recipient, not the nominal amount\n    ///  that was burned on L2. The real amount is calculated as nominal amount * share price, which can be found\n    ///  in the checkpoint with `_hintId`.\n    function _calculateClaimableEther(uint256 _requestId, uint256 _hintId)\n        internal\n        view\n        returns (uint256)\n    {\n        if (_hintId == 0) {\n            revert InvalidHint(_hintId);\n        }\n\n        uint256 lastCheckpointIndex = lastCheckpointId;\n        if (_hintId > lastCheckpointIndex) {\n            revert InvalidHint(_hintId);\n        }\n\n        Checkpoint memory checkpoint = _checkpoints[_hintId];\n        if (_requestId < checkpoint.fromRequestId) {\n            revert InvalidHint(_hintId);\n        }\n        if (_hintId < lastCheckpointIndex) {\n            Checkpoint memory nextCheckpoint = _checkpoints[_hintId + 1];\n            if (_requestId >= nextCheckpoint.fromRequestId) {\n                revert InvalidHint(_hintId);\n            }\n        }\n\n        WithdrawalRequest storage prevRequest = _requests[_requestId - 1];\n        WithdrawalRequest storage request = _requests[_requestId];\n\n        uint256 nominalAmount = request.cumulativeAmount - prevRequest.cumulativeAmount;\n        return (nominalAmount * checkpoint.sharePrice) / E27_PRECISION_BASE;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/ECDSAUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS,\n        InvalidSignatureV // Deprecated in v4.8\n    }\n\n    function _throwError(RecoverError error) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert(\"ECDSA: invalid signature\");\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert(\"ECDSA: invalid signature length\");\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert(\"ECDSA: invalid signature 's' value\");\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature` or error string. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            /// @solidity memory-safe-assembly\n            assembly {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength);\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, signature);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n        uint8 v = uint8((uint256(vs) >> 255) + 27);\n        return tryRecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     *\n     * _Available since v4.2._\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature);\n        }\n\n        return (signer, RecoverError.NoError);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n            mstore(0x1c, hash)\n            message := keccak256(0x00, 0x3c)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from `s`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", StringsUpgradeable.toString(s.length), s));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Typed Data, created from a\n     * `domainSeparator` and a `structHash`. This produces hash corresponding\n     * to the one signed with the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n     * JSON-RPC method as part of EIP-712.\n     *\n     * See {recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(ptr, \"\\x19\\x01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            data := keccak256(ptr, 0x42)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Data with intended validator, created from a\n     * `validator` and `data` according to the version 0 of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n    }\n}\n"},{"file_path":"src/L2/Gas.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { SafeTransferLib } from \"solmate/utils/SafeTransferLib.sol\";\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport { Semver } from \"src/universal/Semver.sol\";\n\nenum GasMode {\n    VOID,\n    CLAIMABLE\n}\n\ninterface IGas {\n    function readGasParams(address contractAddress) external view returns (uint256, uint256, uint256, GasMode);\n    function setGasMode(address contractAddress, GasMode mode) external;\n    function claimGasAtMinClaimRate(address contractAddress, address recipient, uint256 minClaimRateBips) external returns (uint256);\n    function claimAll(address contractAddress, address recipient) external returns (uint256);\n    function claimMax(address contractAddress, address recipient) external returns (uint256);\n    function claim(address contractAddress, address recipient, uint256 gasToClaim, uint256 gasSecondsToConsume) external returns (uint256);\n}\n\n/// @custom:predeploy 0x4300000000000000000000000000000000000001\n/// @title Gas\ncontract Gas is IGas, Initializable, Semver {\n    address public immutable admin;\n\n    // Blast.sol --> controls all dAPP accesses to Gas.sol\n    address public immutable blastConfigurationContract;\n\n    // BaseFeeVault.sol -> fees from gas claims directed here\n    address public immutable blastFeeVault;\n\n    // zero claim rate in bps -> percent of gas user is able to claim\n    // without consuming any gas seconds\n    uint256 public zeroClaimRate; // bps\n\n    // base claim rate in bps -> percent of gas user is able to claim\n    // by consuming base gas seconds\n    uint256 public baseGasSeconds;\n    uint256 public baseClaimRate; // bps\n\n    // ceil claim rate in bps -> percent of gas user is able to claim\n    // by consuming ceil gas seconds or more\n    uint256 public ceilGasSeconds;\n    uint256 public ceilClaimRate; // bps\n\n    /**\n     * @notice Constructs the blast gas contract.\n     * @param _admin The address of the admin.\n     * @param _blastConfigurationContract The address of the Blast configuration contract.\n     * @param _blastFeeVault The address of the Blast fee vault.\n    */\n    constructor (\n        address _admin,\n        address _blastConfigurationContract,\n        address _blastFeeVault\n    ) Semver(1, 0, 0) {\n        admin =  _admin;\n        blastConfigurationContract = _blastConfigurationContract;\n        blastFeeVault = _blastFeeVault;\n        _disableInitializers();\n    }\n\n    /**\n     * @notice Initializer.\n     * @param _zeroClaimRate The zero claim rate.\n     * @param _baseGasSeconds The base gas seconds.\n     * @param _baseClaimRate The base claim rate.\n     * @param _ceilGasSeconds The ceiling gas seconds.\n     * @param _ceilClaimRate The ceiling claim rate.\n     */\n    function initialize(\n        uint256 _zeroClaimRate,\n        uint256 _baseGasSeconds,\n        uint256 _baseClaimRate,\n        uint256 _ceilGasSeconds,\n        uint256 _ceilClaimRate\n    ) public initializer {\n        require(_zeroClaimRate < _baseClaimRate, \"zero claim rate must be < base claim rate\");\n        require(_baseClaimRate < _ceilClaimRate, \"base claim rate must be < ceil claim rate\");\n        require(_baseGasSeconds < _ceilGasSeconds, \"base gas seconds must be < ceil gas seconds\");\n        require(_baseGasSeconds > 0, \"base gas seconds must be > 0\");\n        require(_ceilClaimRate <= 10000, \"ceil claim rate must be less than or equal to 10_000 bips\");\n        // admin vars\n        zeroClaimRate = _zeroClaimRate;\n        baseGasSeconds = _baseGasSeconds;\n        baseClaimRate = _baseClaimRate;\n        ceilGasSeconds = _ceilGasSeconds;\n        ceilClaimRate = _ceilClaimRate;\n    }\n\n    /**\n     * @notice Allows only the admin to call a function\n     */\n    modifier onlyAdmin() {\n        require(msg.sender == admin, \"Caller is not the admin\");\n        _;\n    }\n    /**\n     * @notice Allows only the Blast Configuration Contract to call a function\n     */\n    modifier onlyBlastConfigurationContract() {\n        require(msg.sender == blastConfigurationContract, \"Caller must be blast configuration contract\");\n        _;\n    }\n\n    /**\n     * @notice Allows the admin to update the parameters\n     * @param _zeroClaimRate The new zero claim rate\n     * @param _baseGasSeconds The new base gas seconds\n     * @param _baseClaimRate The new base claim rate\n     * @param _ceilGasSeconds The new ceiling gas seconds\n     * @param _ceilClaimRate The new ceiling claim rate\n     */\n    function updateAdminParameters(\n        uint256 _zeroClaimRate,\n        uint256 _baseGasSeconds,\n        uint256 _baseClaimRate,\n        uint256 _ceilGasSeconds,\n        uint256 _ceilClaimRate\n    ) external onlyAdmin {\n        require(_zeroClaimRate < _baseClaimRate, \"zero claim rate must be < base claim rate\");\n        require(_baseClaimRate < _ceilClaimRate, \"base claim rate must be < ceil claim rate\");\n        require(_baseGasSeconds < _ceilGasSeconds, \"base gas seconds must be < ceil gas seconds\");\n        require(_baseGasSeconds > 0, \"base gas seconds must be > 0\");\n        require(_ceilClaimRate <= 10000, \"ceil claim rate must be less than or equal to 10_000 bips\");\n\n        zeroClaimRate = _zeroClaimRate;\n        baseGasSeconds = _baseGasSeconds;\n        baseClaimRate = _baseClaimRate;\n        ceilGasSeconds = _ceilGasSeconds;\n        ceilClaimRate = _ceilClaimRate;\n    }\n\n    /**\n     * @notice Allows the admin to claim the gas of any address\n     * @param contractAddress The address of the contract\n     * @return The amount of ether balance claimed\n     */\n    function adminClaimGas(address contractAddress) external onlyAdmin returns (uint256) {\n        (, uint256 etherBalance,,) = readGasParams(contractAddress);\n        _updateGasParams(contractAddress, 0, 0, GasMode.VOID);\n        SafeTransferLib.safeTransferETH(blastFeeVault, etherBalance);\n        return etherBalance;\n    }\n    /**\n     * @notice Allows an authorized user to set the gas mode for a contract via the BlastConfigurationContract\n     * @param contractAddress The address of the contract\n     * @param mode The new gas mode for the contract\n     */\n    function setGasMode(address contractAddress, GasMode mode) external onlyBlastConfigurationContract {\n        // retrieve gas params\n        (uint256 etherSeconds, uint256 etherBalance,,) = readGasParams(contractAddress);\n        _updateGasParams(contractAddress, etherSeconds, etherBalance, mode);\n    }\n\n    /**\n     * @notice Allows a user to claim gas at a minimum claim rate (error = 1 bip)\n     * @param contractAddress The address of the contract\n     * @param recipientOfGas The address of the recipient of the gas\n     * @param minClaimRateBips The minimum claim rate in basis points\n     * @return The amount of gas claimed\n     */\n    function claimGasAtMinClaimRate(address contractAddress, address recipientOfGas, uint256 minClaimRateBips) public returns (uint256) {\n        require(minClaimRateBips <= ceilClaimRate, \"desired claim rate exceeds maximum\");\n\n        (uint256 etherSeconds, uint256 etherBalance,,) = readGasParams(contractAddress);\n        if (minClaimRateBips <= zeroClaimRate) {\n            return claimAll(contractAddress, recipientOfGas);\n        }\n\n        // set minClaimRate to baseClaimRate in this case\n        if (minClaimRateBips < baseClaimRate) {\n            minClaimRateBips = baseClaimRate;\n        }\n\n        uint256 bipsDiff = minClaimRateBips - baseClaimRate;\n        uint256 secondsDiff = ceilGasSeconds - baseGasSeconds;\n        uint256 rateDiff = ceilClaimRate - baseClaimRate;\n        uint256 minSecondsStaked = baseGasSeconds + Math.ceilDiv(bipsDiff * secondsDiff, rateDiff);\n        uint256 maxEtherClaimable = etherSeconds / minSecondsStaked;\n        if (maxEtherClaimable > etherBalance)  {\n            maxEtherClaimable = etherBalance;\n        }\n        uint256 secondsToConsume = maxEtherClaimable * minSecondsStaked;\n        return claim(contractAddress, recipientOfGas, maxEtherClaimable, secondsToConsume);\n    }\n\n    /**\n     * @notice Allows a contract to claim all gas\n     * @param contractAddress The address of the contract\n     * @param recipientOfGas The address of the recipient of the gas\n     * @return The amount of gas claimed\n     */\n    function claimAll(address contractAddress, address recipientOfGas) public returns (uint256) {\n        (uint256 etherSeconds, uint256 etherBalance,,) = readGasParams(contractAddress);\n        return claim(contractAddress, recipientOfGas, etherBalance, etherSeconds);\n    }\n\n    /**\n     * @notice Allows a contract to claim all gas at the highest possible claim rate\n     * @param contractAddress The address of the contract\n     * @param recipientOfGas The address of the recipient of the gas\n     * @return The amount of gas claimed\n     */\n    function claimMax(address contractAddress, address recipientOfGas) public returns (uint256) {\n        return claimGasAtMinClaimRate(contractAddress, recipientOfGas, ceilClaimRate);\n    }\n    /**\n     * @notice Allows a contract to claim a specified amount of gas, at a claim rate set by the number of gas seconds\n     * @param contractAddress The address of the contract\n     * @param recipientOfGas The address of the recipient of the gas\n     * @param gasToClaim The amount of gas to claim\n     * @param gasSecondsToConsume The amount of gas seconds to consume\n     * @return The amount of gas claimed (gasToClaim - penalty)\n     */\n\n    function claim(address contractAddress, address recipientOfGas, uint256 gasToClaim, uint256 gasSecondsToConsume) public onlyBlastConfigurationContract() returns (uint256)  {\n        // retrieve gas params\n        (uint256 etherSeconds, uint256 etherBalance,, GasMode mode) = readGasParams(contractAddress);\n\n        // check validity requirements\n        require(gasToClaim > 0, \"must withdraw non-zero amount\");\n        require(gasToClaim <= etherBalance, \"too much to withdraw\");\n        require(gasSecondsToConsume <= etherSeconds, \"not enough gas seconds\");\n\n        // get claim rate\n        (uint256 claimRate, uint256 gasSecondsToConsumeNormalized) = getClaimRateBps(gasSecondsToConsume, gasToClaim);\n\n        // calculate tax\n        uint256 userEther = gasToClaim * claimRate / 10_000;\n        uint256 penalty = gasToClaim - userEther;\n\n        _updateGasParams(contractAddress, etherSeconds - gasSecondsToConsumeNormalized, etherBalance - gasToClaim, mode);\n\n        SafeTransferLib.safeTransferETH(recipientOfGas, userEther);\n        if (penalty > 0) {\n            SafeTransferLib.safeTransferETH(blastFeeVault, penalty);\n        }\n\n        return userEther;\n    }\n    /**\n     * @notice Calculates the claim rate in basis points based on gasSeconds, gasToClaim\n     * @param gasSecondsToConsume The amount of gas seconds to consume\n     * @param gasToClaim The amount of gas to claim\n     * @return claimRate The calculated claim rate in basis points\n     * @return gasSecondsToConsume The normalized gas seconds to consume (<= gasSecondsToConsume)\n     */\n    function getClaimRateBps(uint256 gasSecondsToConsume, uint256 gasToClaim) public view returns (uint256, uint256) {\n        uint256 secondsStaked = gasSecondsToConsume / gasToClaim;\n        if (secondsStaked < baseGasSeconds) {\n            return (zeroClaimRate, 0);\n        }\n        if (secondsStaked >= ceilGasSeconds) {\n            uint256 gasToConsumeNormalized = gasToClaim * ceilGasSeconds;\n            return (ceilClaimRate, gasToConsumeNormalized);\n        }\n\n        uint256 rateDiff = ceilClaimRate - baseClaimRate;\n        uint256 secondsDiff = ceilGasSeconds - baseGasSeconds;\n        uint256 secondsStakedDiff = secondsStaked - baseGasSeconds;\n        uint256 additionalClaimRate = rateDiff * secondsStakedDiff / secondsDiff;\n        uint256 claimRate = baseClaimRate + additionalClaimRate;\n        return (claimRate, gasSecondsToConsume);\n    }\n\n    /**\n     * @notice Reads the gas parameters for a given user\n     * @param user The address of the user\n     * @return etherSeconds The integral of ether over time (ether * seconds vested)\n     * @return etherBalance The total ether balance for the user\n     * @return lastUpdated The last updated timestamp for the user's gas parameters\n     * @return mode The current gas mode for the user\n     */\n     function readGasParams(address user) public view returns (uint256 etherSeconds, uint256 etherBalance, uint256 lastUpdated, GasMode mode) {\n        bytes32 paramsHash = keccak256(abi.encodePacked(user, \"parameters\"));\n        bytes32 packedParams;\n        // read params\n        assembly {\n            packedParams := sload(paramsHash)\n        }\n\n        // unpack params\n        // - The first byte (most significant byte) represents the mode\n        // - The next 12 bytes represent the etherBalance\n        // - The following 15 bytes represent the etherSeconds\n        // - The last 4 bytes (least significant bytes) represent the lastUpdated timestamp\n        mode         = GasMode(uint8(packedParams[0]));\n        etherBalance = uint256((packedParams << (1             * 8)) >> ((32 - 12) * 8));\n        etherSeconds = uint256((packedParams << ((1 + 12)      * 8)) >> ((32 - 15) * 8));\n        lastUpdated  = uint256((packedParams << ((1 + 12 + 15) * 8)) >> ((32 -  4) * 8));\n\n        // update ether seconds\n        etherSeconds = etherSeconds + etherBalance * (block.timestamp - lastUpdated);\n    }\n\n    /**\n     * @notice Updates the gas parameters for a given contract address\n     * @param contractAddress The address of the contract\n     * @param etherSeconds The integral of ether over time (ether * seconds vested)\n     * @param etherBalance The total ether balance for the contract\n     */\n    function _updateGasParams(address contractAddress, uint256 etherSeconds, uint256 etherBalance, GasMode mode) internal {\n        if (\n            etherBalance >= 1 << (12 * 8) ||\n            etherSeconds >= 1 << (15 * 8)\n        ) {\n            revert(\"Unexpected packing issue due to overflow\");\n        }\n\n        uint256 updatedTimestamp = block.timestamp; // Known to fit in 4 bytes\n\n        bytes32 paramsHash = keccak256(abi.encodePacked(contractAddress, \"parameters\"));\n        bytes32 packedParams;\n        packedParams = (\n            (bytes32(uint256(mode)) << ((12 + 15 + 4) * 8)) | // Shift mode to the most significant byte\n            (bytes32(etherBalance)  << ((15 + 4) * 8))      | // Shift etherBalance to start after 1 byte of mode\n            (bytes32(etherSeconds)  << (4 * 8))             | // Shift etherSeconds to start after mode and etherBalance\n            bytes32(updatedTimestamp)                         // Keep updatedTimestamp in the least significant bytes\n        );\n\n        assembly {\n            sstore(paramsHash, packedParams)\n        }\n    }\n}\n"},{"file_path":"lib/solmate/src/utils/FixedPointMathLib.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)\nlibrary FixedPointMathLib {\n    /*//////////////////////////////////////////////////////////////\n                    SIMPLIFIED FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n    }\n\n    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n    }\n\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n    }\n\n    function powWad(int256 x, int256 y) internal pure returns (int256) {\n        // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)\n        return expWad((lnWad(x) * y) / int256(WAD)); // Using ln(x) means x must be greater than 0.\n    }\n\n    function expWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            // When the result is < 0.5 we return zero. This happens when\n            // x <= floor(log(0.5e18) * 1e18) ~ -42e18\n            if (x <= -42139678854452767551) return 0;\n\n            // When the result is > (2**255 - 1) / 1e18 we can not represent it as an\n            // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.\n            if (x >= 135305999368893231589) revert(\"EXP_OVERFLOW\");\n\n            // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96\n            // for more intermediate precision and a binary basis. This base conversion\n            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.\n            x = (x << 78) / 5**18;\n\n            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers\n            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.\n            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).\n            int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;\n            x = x - k * 54916777467707473351141471128;\n\n            // k is in the range [-61, 195].\n\n            // Evaluate using a (6, 7)-term rational approximation.\n            // p is made monic, we'll multiply by a scale factor later.\n            int256 y = x + 1346386616545796478920950773328;\n            y = ((y * x) >> 96) + 57155421227552351082224309758442;\n            int256 p = y + x - 94201549194550492254356042504812;\n            p = ((p * y) >> 96) + 28719021644029726153956944680412240;\n            p = p * x + (4385272521454847904659076985693276 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            int256 q = x - 2855989394907223263936484059900;\n            q = ((q * x) >> 96) + 50020603652535783019961831881945;\n            q = ((q * x) >> 96) - 533845033583426703283633433725380;\n            q = ((q * x) >> 96) + 3604857256930695427073651918091429;\n            q = ((q * x) >> 96) - 14423608567350463180887372962807573;\n            q = ((q * x) >> 96) + 26449188498355588339934803723976023;\n\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial won't have zeros in the domain as all its roots are complex.\n                // No scaling is necessary because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r should be in the range (0.09, 0.25) * 2**96.\n\n            // We now need to multiply r by:\n            // * the scale factor s = ~6.031367120.\n            // * the 2**k factor from the range reduction.\n            // * the 1e18 / 2**96 factor for base conversion.\n            // We do this all at once, with an intermediate result in 2**213\n            // basis, so the final right shift is always by a positive amount.\n            r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));\n        }\n    }\n\n    function lnWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            require(x > 0, \"UNDEFINED\");\n\n            // We want to convert x from 10**18 fixed point to 2**96 fixed point.\n            // We do this by multiplying by 2**96 / 10**18. But since\n            // ln(x * C) = ln(x) + ln(C), we can simply do nothing here\n            // and add ln(2**96 / 10**18) at the end.\n\n            // Reduce range of x to (1, 2) * 2**96\n            // ln(2^k * x) = k * ln(2) + ln(x)\n            int256 k = int256(log2(uint256(x))) - 96;\n            x <<= uint256(159 - k);\n            x = int256(uint256(x) >> 159);\n\n            // Evaluate using a (8, 8)-term rational approximation.\n            // p is made monic, we will multiply by a scale factor later.\n            int256 p = x + 3273285459638523848632254066296;\n            p = ((p * x) >> 96) + 24828157081833163892658089445524;\n            p = ((p * x) >> 96) + 43456485725739037958740375743393;\n            p = ((p * x) >> 96) - 11111509109440967052023855526967;\n            p = ((p * x) >> 96) - 45023709667254063763336534515857;\n            p = ((p * x) >> 96) - 14706773417378608786704636184526;\n            p = p * x - (795164235651350426258249787498 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            // q is monic by convention.\n            int256 q = x + 5573035233440673466300451813936;\n            q = ((q * x) >> 96) + 71694874799317883764090561454958;\n            q = ((q * x) >> 96) + 283447036172924575727196451306956;\n            q = ((q * x) >> 96) + 401686690394027663651624208769553;\n            q = ((q * x) >> 96) + 204048457590392012362485061816622;\n            q = ((q * x) >> 96) + 31853899698501571402653359427138;\n            q = ((q * x) >> 96) + 909429971244387300277376558375;\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial is known not to have zeros in the domain.\n                // No scaling required because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r is in the range (0, 0.125) * 2**96\n\n            // Finalization, we need to:\n            // * multiply by the scale factor s = 5.549…\n            // * add ln(2**96 / 10**18)\n            // * add k * ln(2)\n            // * multiply by 10**18 / 2**96 = 5**18 >> 78\n\n            // mul s * 5e18 * 2**96, base is now 5**18 * 2**192\n            r *= 1677202110996718588342820967067443963516166;\n            // add ln(2) * k * 5e18 * 2**192\n            r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;\n            // add ln(2**96 / 10**18) * 5e18 * 2**192\n            r += 600920179829731861736702779321621459595472258049074101567377883020018308;\n            // base conversion: mul 2**18 / 2**192\n            r >>= 174;\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    LOW LEVEL FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function mulDivDown(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        assembly {\n            // Store x * y in z for now.\n            z := mul(x, y)\n\n            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n                revert(0, 0)\n            }\n\n            // Divide z by the denominator.\n            z := div(z, denominator)\n        }\n    }\n\n    function mulDivUp(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        assembly {\n            // Store x * y in z for now.\n            z := mul(x, y)\n\n            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n                revert(0, 0)\n            }\n\n            // First, divide z - 1 by the denominator and add 1.\n            // We allow z - 1 to underflow if z is 0, because we multiply the\n            // end result by 0 if z is zero, ensuring we return 0 if z is zero.\n            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\n        }\n    }\n\n    function rpow(\n        uint256 x,\n        uint256 n,\n        uint256 scalar\n    ) internal pure returns (uint256 z) {\n        assembly {\n            switch x\n            case 0 {\n                switch n\n                case 0 {\n                    // 0 ** 0 = 1\n                    z := scalar\n                }\n                default {\n                    // 0 ** n = 0\n                    z := 0\n                }\n            }\n            default {\n                switch mod(n, 2)\n                case 0 {\n                    // If n is even, store scalar in z for now.\n                    z := scalar\n                }\n                default {\n                    // If n is odd, store x in z for now.\n                    z := x\n                }\n\n                // Shifting right by 1 is like dividing by 2.\n                let half := shr(1, scalar)\n\n                for {\n                    // Shift n right by 1 before looping to halve it.\n                    n := shr(1, n)\n                } n {\n                    // Shift n right by 1 each iteration to halve it.\n                    n := shr(1, n)\n                } {\n                    // Revert immediately if x ** 2 would overflow.\n                    // Equivalent to iszero(eq(div(xx, x), x)) here.\n                    if shr(128, x) {\n                        revert(0, 0)\n                    }\n\n                    // Store x squared.\n                    let xx := mul(x, x)\n\n                    // Round to the nearest number.\n                    let xxRound := add(xx, half)\n\n                    // Revert if xx + half overflowed.\n                    if lt(xxRound, xx) {\n                        revert(0, 0)\n                    }\n\n                    // Set x to scaled xxRound.\n                    x := div(xxRound, scalar)\n\n                    // If n is even:\n                    if mod(n, 2) {\n                        // Compute z * x.\n                        let zx := mul(z, x)\n\n                        // If z * x overflowed:\n                        if iszero(eq(div(zx, x), z)) {\n                            // Revert if x is non-zero.\n                            if iszero(iszero(x)) {\n                                revert(0, 0)\n                            }\n                        }\n\n                        // Round to the nearest number.\n                        let zxRound := add(zx, half)\n\n                        // Revert if zx + half overflowed.\n                        if lt(zxRound, zx) {\n                            revert(0, 0)\n                        }\n\n                        // Return properly scaled zxRound.\n                        z := div(zxRound, scalar)\n                    }\n                }\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        GENERAL NUMBER UTILITIES\n    //////////////////////////////////////////////////////////////*/\n\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        require(x > 0, \"UNDEFINED\");\n\n        assembly {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            r := or(r, shl(2, lt(0xf, shr(r, x))))\n            r := or(r, shl(1, lt(0x3, shr(r, x))))\n            r := or(r, lt(0x1, shr(r, x)))\n        }\n    }\n}\n"},{"file_path":"src/mainnet-bridge/L2BlastBridge.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\nimport { StandardBridge } from \"src/universal/StandardBridge.sol\";\nimport { CrossDomainMessenger } from \"src/universal/CrossDomainMessenger.sol\";\nimport { ISemver } from \"src/universal/ISemver.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { AddressAliasHelper } from \"src/vendor/AddressAliasHelper.sol\";\nimport { Blast, YieldMode, GasMode } from \"src/L2/Blast.sol\";\n\n/// @custom:proxied\n/// @custom:predeploy 0x4300000000000000000000000000000000000005\n/// @title L2BlastBridge\n/// @notice The L2BlastBridge is responsible for transfering ETH and USDB tokens between L1 and\n///         L2. In the case that an ERC20 token is native to L2, it will be escrowed within this\n///         contract.\ncontract L2BlastBridge is StandardBridge, ISemver {\n    /// @custom:semver 1.0.0\n    string public constant version = \"1.0.0\";\n\n    /// @notice Constructs the L2BlastBridge contract.\n    /// @param _otherBridge Address of the L1BlastBridge.\n    constructor(StandardBridge _otherBridge) StandardBridge(_otherBridge) {\n        _disableInitializers();\n    }\n\n    /// @notice Initializer\n    function initialize() public initializer {\n        __StandardBridge_init({ _messenger: CrossDomainMessenger(Predeploys.L2_CROSS_DOMAIN_MESSENGER) });\n        Blast(Predeploys.BLAST).configureContract(\n            address(this),\n            YieldMode.VOID,\n            GasMode.VOID,\n            address(0xdead) /// don't set a governor\n        );\n    }\n\n    /// @notice Allows EOAs to bridge ETH by sending directly to the bridge.\n    receive() external payable override onlyEOA {\n        _initiateBridgeETH(msg.sender, msg.sender, msg.value, RECEIVE_DEFAULT_GAS_LIMIT, hex\"\");\n    }\n\n    /// @notice Modified StandardBridge.finalizeBridgeETH function to allow calls directly from\n    ///         the L1BlastBridge without going through a messenger.\n    /// @notice See { StandardBridge-finalizeBridgeETH }\n    function finalizeBridgeETHDirect(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _extraData\n    )\n        public\n        payable\n    {\n        require(AddressAliasHelper.undoL1ToL2Alias(msg.sender) == address(OTHER_BRIDGE), \"L2BlastBridge: function can only be called from the other bridge\");\n        require(msg.value == _amount, \"L2BlastBridge: amount sent does not match amount required\");\n        require(_to != address(this), \"L2BlastBridge: cannot send to self\");\n        require(_to != address(messenger), \"L2BlastBridge: cannot send to messenger\");\n\n        // Emit the correct events. By default this will be _amount, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitETHBridgeFinalized(_from, _to, _amount, _extraData);\n\n        bool success = SafeCall.call(_to, gasleft(), _amount, hex\"\");\n        require(success, \"L2BlastBridge: ETH transfer failed\");\n    }\n\n    /// @notice Wrapper to only accept USDB withdrawals.\n    /// @notice See { StandardBridge-_initiateBridgeERC20 }\n    function _initiateBridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes memory _extraData\n    )\n        internal\n        override\n    {\n        require(_localToken == Predeploys.USDB, \"L2BlastBridge: only USDB can be withdrawn from this bridge.\");\n        require(_isCorrectTokenPair(Predeploys.USDB, _remoteToken), \"L2BlastBridge: wrong remote token for USDB.\");\n        super._initiateBridgeERC20(_localToken, _remoteToken, _from, _to, _amount, _minGasLimit, _extraData);\n    }\n}\n"},{"file_path":"src/universal/StandardBridge.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { ERC165Checker } from \"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol\";\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { SafeCall } from \"src/libraries/SafeCall.sol\";\nimport { IOptimismMintableERC20, ILegacyMintableERC20 } from \"src/universal/IOptimismMintableERC20.sol\";\nimport { CrossDomainMessenger } from \"src/universal/CrossDomainMessenger.sol\";\nimport { OptimismMintableERC20 } from \"src/universal/OptimismMintableERC20.sol\";\nimport { Initializable } from \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/// @custom:upgradeable\n/// @title StandardBridge\n/// @notice StandardBridge is a base contract for the L1 and L2 standard ERC20 bridges. It handles\n///         the core bridging logic, including escrowing tokens that are native to the local chain\n///         and minting/burning tokens that are native to the remote chain.\nabstract contract StandardBridge is Initializable {\n    using SafeERC20 for IERC20;\n\n    /// @notice The L2 gas limit set when eth is depoisited using the receive() function.\n    uint32 internal constant RECEIVE_DEFAULT_GAS_LIMIT = 200_000;\n\n    /// @notice Corresponding bridge on the other domain. This public getter is deprecated\n    ///         and will be removed in the future. Please use `otherBridge` instead.\n    ///         This can safely be an immutable because for the L1StandardBridge, it will\n    ///         be set to the L2StandardBridge address, which is the same for all OP Stack\n    ///         chains. For the L2StandardBridge, there are not multiple proxies using the\n    ///         same implementation.\n    /// @custom:legacy\n    /// @custom:network-specific\n    StandardBridge public immutable OTHER_BRIDGE;\n\n    /// @custom:legacy\n    /// @custom:spacer messenger\n    /// @notice Spacer for backwards compatibility.\n    address private spacer_0_2_20;\n\n    /// @custom:legacy\n    /// @custom:spacer l2TokenBridge\n    /// @notice Spacer for backwards compatibility.\n    address private spacer_1_0_20;\n\n    /// @notice Mapping that stores deposits for a given pair of local and remote tokens.\n    mapping(address => mapping(address => uint256)) public deposits;\n\n    /// @notice Messenger contract on this domain. This public getter is deprecated\n    ///         and will be removed in the future. Please use `messenger` instead.\n    /// @custom:network-specific\n    CrossDomainMessenger public messenger;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    ///         A gap size of 46 was chosen here, so that the first slot used in a child contract\n    ///         would be a multiple of 50.\n    uint256[46] private __gap;\n\n    /// @notice Emitted when an ETH bridge is initiated to the other chain.\n    /// @param from      Address of the sender.\n    /// @param to        Address of the receiver.\n    /// @param amount    Amount of ETH sent.\n    /// @param extraData Extra data sent with the transaction.\n    event ETHBridgeInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData);\n\n    /// @notice Emitted when an ETH bridge is finalized on this chain.\n    /// @param from      Address of the sender.\n    /// @param to        Address of the receiver.\n    /// @param amount    Amount of ETH sent.\n    /// @param extraData Extra data sent with the transaction.\n    event ETHBridgeFinalized(address indexed from, address indexed to, uint256 amount, bytes extraData);\n\n    /// @notice Emitted when an ERC20 bridge is initiated to the other chain.\n    /// @param localToken  Address of the ERC20 on this chain.\n    /// @param remoteToken Address of the ERC20 on the remote chain.\n    /// @param from        Address of the sender.\n    /// @param to          Address of the receiver.\n    /// @param amount      Amount of the ERC20 sent.\n    /// @param extraData   Extra data sent with the transaction.\n    event ERC20BridgeInitiated(\n        address indexed localToken,\n        address indexed remoteToken,\n        address indexed from,\n        address to,\n        uint256 amount,\n        bytes extraData\n    );\n\n    /// @notice Emitted when an ERC20 bridge is finalized on this chain.\n    /// @param localToken  Address of the ERC20 on this chain.\n    /// @param remoteToken Address of the ERC20 on the remote chain.\n    /// @param from        Address of the sender.\n    /// @param to          Address of the receiver.\n    /// @param amount      Amount of the ERC20 sent.\n    /// @param extraData   Extra data sent with the transaction.\n    event ERC20BridgeFinalized(\n        address indexed localToken,\n        address indexed remoteToken,\n        address indexed from,\n        address to,\n        uint256 amount,\n        bytes extraData\n    );\n\n    /// @notice Only allow EOAs to call the functions. Note that this is not safe against contracts\n    ///         calling code within their constructors, but also doesn't really matter since we're\n    ///         just trying to prevent users accidentally depositing with smart contract wallets.\n    modifier onlyEOA() {\n        require(!Address.isContract(msg.sender), \"StandardBridge: function can only be called from an EOA\");\n        _;\n    }\n\n    /// @notice Ensures that the caller is a cross-chain message from the other bridge.\n    modifier onlyOtherBridge() {\n        require(\n            msg.sender == address(messenger) && messenger.xDomainMessageSender() == address(OTHER_BRIDGE),\n            \"StandardBridge: function can only be called from the other bridge\"\n        );\n        _;\n    }\n\n    /// @param _otherBridge Address of the other StandardBridge contract.\n    constructor(StandardBridge _otherBridge) {\n        OTHER_BRIDGE = _otherBridge;\n    }\n\n    /// @notice Initializer.\n    /// @param _messenger   Address of CrossDomainMessenger on this network.\n    // solhint-disable-next-line func-name-mixedcase\n    function __StandardBridge_init(CrossDomainMessenger _messenger) internal onlyInitializing {\n        messenger = _messenger;\n    }\n\n    /// @notice Allows EOAs to bridge ETH by sending directly to the bridge.\n    ///         Must be implemented by contracts that inherit.\n    receive() external payable virtual;\n\n    /// @notice Getter for messenger contract.\n    /// @custom:legacy\n    /// @return Messenger contract on this domain.\n    function MESSENGER() external view returns (CrossDomainMessenger) {\n        return messenger;\n    }\n\n    /// @notice Getter for the remote domain bridge contract.\n    function otherBridge() external view returns (StandardBridge) {\n        return OTHER_BRIDGE;\n    }\n\n    /// @notice Sends ETH to the sender's address on the other chain.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function bridgeETH(uint32 _minGasLimit, bytes calldata _extraData) public payable onlyEOA {\n        _initiateBridgeETH(msg.sender, msg.sender, msg.value, _minGasLimit, _extraData);\n    }\n\n    /// @notice Sends ETH to a receiver's address on the other chain. Note that if ETH is sent to a\n    ///         smart contract and the call fails, the ETH will be temporarily locked in the\n    ///         StandardBridge on the other chain until the call is replayed. If the call cannot be\n    ///         replayed with any amount of gas (call always reverts), then the ETH will be\n    ///         permanently locked in the StandardBridge on the other chain. ETH will also\n    ///         be locked if the receiver is the other bridge, because finalizeBridgeETH will revert\n    ///         in that case.\n    /// @param _to          Address of the receiver.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function bridgeETHTo(address _to, uint32 _minGasLimit, bytes calldata _extraData) public payable {\n        _initiateBridgeETH(msg.sender, _to, msg.value, _minGasLimit, _extraData);\n    }\n\n    /// @notice Sends ERC20 tokens to the sender's address on the other chain. Note that if the\n    ///         ERC20 token on the other chain does not recognize the local token as the correct\n    ///         pair token, the ERC20 bridge will fail and the tokens will be returned to sender on\n    ///         this chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _amount      Amount of local tokens to deposit.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function bridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes calldata _extraData\n    )\n        public\n        virtual\n        onlyEOA\n    {\n        _initiateBridgeERC20(_localToken, _remoteToken, msg.sender, msg.sender, _amount, _minGasLimit, _extraData);\n    }\n\n    /// @notice Sends ERC20 tokens to a receiver's address on the other chain. Note that if the\n    ///         ERC20 token on the other chain does not recognize the local token as the correct\n    ///         pair token, the ERC20 bridge will fail and the tokens will be returned to sender on\n    ///         this chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of local tokens to deposit.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function bridgeERC20To(\n        address _localToken,\n        address _remoteToken,\n        address _to,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes calldata _extraData\n    )\n        public\n        virtual\n    {\n        _initiateBridgeERC20(_localToken, _remoteToken, msg.sender, _to, _amount, _minGasLimit, _extraData);\n    }\n\n    /// @notice Finalizes an ETH bridge on this chain. Can only be triggered by the other\n    ///         StandardBridge contract on the remote chain.\n    /// @param _from      Address of the sender.\n    /// @param _to        Address of the receiver.\n    /// @param _amount    Amount of ETH being bridged.\n    /// @param _extraData Extra data to be sent with the transaction. Note that the recipient will\n    ///                   not be triggered with this data, but it will be emitted and can be used\n    ///                   to identify the transaction.\n    function finalizeBridgeETH(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _extraData\n    )\n        public\n        payable\n        virtual\n        onlyOtherBridge\n    {\n        require(msg.value == _amount, \"StandardBridge: amount sent does not match amount required\");\n        require(_to != address(this), \"StandardBridge: cannot send to self\");\n        require(_to != address(messenger), \"StandardBridge: cannot send to messenger\");\n\n        // Emit the correct events. By default this will be _amount, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitETHBridgeFinalized(_from, _to, _amount, _extraData);\n\n        bool success = SafeCall.call(_to, gasleft(), _amount, hex\"\");\n        require(success, \"StandardBridge: ETH transfer failed\");\n    }\n\n    /// @notice Finalizes an ERC20 bridge on this chain. Can only be triggered by the other\n    ///         StandardBridge contract on the remote chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _from        Address of the sender.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of the ERC20 being bridged.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function finalizeBridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes calldata _extraData\n    )\n        public\n        virtual\n        onlyOtherBridge\n    {\n        if (_isOptimismMintableERC20(_localToken)) {\n            require(\n                _isCorrectTokenPair(_localToken, _remoteToken),\n                \"StandardBridge: wrong remote token for Optimism Mintable ERC20 local token\"\n            );\n\n            OptimismMintableERC20(_localToken).mint(_to, _amount);\n        } else {\n            deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] - _amount;\n            IERC20(_localToken).safeTransfer(_to, _amount);\n        }\n\n        // Emit the correct events. By default this will be ERC20BridgeFinalized, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);\n    }\n\n    /// @notice Initiates a bridge of ETH through the CrossDomainMessenger.\n    /// @param _from        Address of the sender.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of ETH being bridged.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function _initiateBridgeETH(\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes memory _extraData\n    )\n        internal\n    {\n        require(msg.value == _amount, \"StandardBridge: bridging ETH must include sufficient ETH value\");\n\n        // Emit the correct events. By default this will be _amount, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitETHBridgeInitiated(_from, _to, _amount, _extraData);\n\n        messenger.sendMessage{ value: _amount }(\n            address(OTHER_BRIDGE),\n            abi.encodeWithSelector(this.finalizeBridgeETH.selector, _from, _to, _amount, _extraData),\n            _minGasLimit\n        );\n    }\n\n    /// @notice Sends ERC20 tokens to a receiver's address on the other chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the corresponding token on the remote chain.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of local tokens to deposit.\n    /// @param _minGasLimit Minimum amount of gas that the bridge can be relayed with.\n    /// @param _extraData   Extra data to be sent with the transaction. Note that the recipient will\n    ///                     not be triggered with this data, but it will be emitted and can be used\n    ///                     to identify the transaction.\n    function _initiateBridgeERC20(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        uint32 _minGasLimit,\n        bytes memory _extraData\n    )\n        internal\n        virtual\n    {\n        if (_isOptimismMintableERC20(_localToken)) {\n            require(\n                _isCorrectTokenPair(_localToken, _remoteToken),\n                \"StandardBridge: wrong remote token for Optimism Mintable ERC20 local token\"\n            );\n\n            OptimismMintableERC20(_localToken).burn(_from, _amount);\n        } else {\n            IERC20(_localToken).safeTransferFrom(_from, address(this), _amount);\n            deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] + _amount;\n        }\n\n        // Emit the correct events. By default this will be ERC20BridgeInitiated, but child\n        // contracts may override this function in order to emit legacy events as well.\n        _emitERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData);\n\n        messenger.sendMessage(\n            address(OTHER_BRIDGE),\n            abi.encodeWithSelector(\n                this.finalizeBridgeERC20.selector,\n                // Because this call will be executed on the remote chain, we reverse the order of\n                // the remote and local token addresses relative to their order in the\n                // finalizeBridgeERC20 function.\n                _remoteToken,\n                _localToken,\n                _from,\n                _to,\n                _amount,\n                _extraData\n            ),\n            _minGasLimit\n        );\n    }\n\n    /// @notice Checks if a given address is an OptimismMintableERC20. Not perfect, but good enough.\n    ///         Just the way we like it.\n    /// @param _token Address of the token to check.\n    /// @return True if the token is an OptimismMintableERC20.\n    function _isOptimismMintableERC20(address _token) internal view returns (bool) {\n        return ERC165Checker.supportsInterface(_token, type(ILegacyMintableERC20).interfaceId)\n            || ERC165Checker.supportsInterface(_token, type(IOptimismMintableERC20).interfaceId);\n    }\n\n    /// @notice Checks if the \"other token\" is the correct pair token for the OptimismMintableERC20.\n    ///         Calls can be saved in the future by combining this logic with\n    ///         `_isOptimismMintableERC20`.\n    /// @param _mintableToken OptimismMintableERC20 to check against.\n    /// @param _otherToken    Pair token to check.\n    /// @return True if the other token is the correct pair token for the OptimismMintableERC20.\n    function _isCorrectTokenPair(address _mintableToken, address _otherToken) internal view returns (bool) {\n        if (ERC165Checker.supportsInterface(_mintableToken, type(ILegacyMintableERC20).interfaceId)) {\n            return _otherToken == ILegacyMintableERC20(_mintableToken).l1Token();\n        } else {\n            return _otherToken == IOptimismMintableERC20(_mintableToken).remoteToken();\n        }\n    }\n\n    /// @notice Emits the ETHBridgeInitiated event and if necessary the appropriate legacy event\n    ///         when an ETH bridge is finalized on this chain.\n    /// @param _from      Address of the sender.\n    /// @param _to        Address of the receiver.\n    /// @param _amount    Amount of ETH sent.\n    /// @param _extraData Extra data sent with the transaction.\n    function _emitETHBridgeInitiated(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes memory _extraData\n    )\n        internal\n        virtual\n    {\n        emit ETHBridgeInitiated(_from, _to, _amount, _extraData);\n    }\n\n    /// @notice Emits the ETHBridgeFinalized and if necessary the appropriate legacy event when an\n    ///         ETH bridge is finalized on this chain.\n    /// @param _from      Address of the sender.\n    /// @param _to        Address of the receiver.\n    /// @param _amount    Amount of ETH sent.\n    /// @param _extraData Extra data sent with the transaction.\n    function _emitETHBridgeFinalized(\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes memory _extraData\n    )\n        internal\n        virtual\n    {\n        emit ETHBridgeFinalized(_from, _to, _amount, _extraData);\n    }\n\n    /// @notice Emits the ERC20BridgeInitiated event and if necessary the appropriate legacy\n    ///         event when an ERC20 bridge is initiated to the other chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the ERC20 on the remote chain.\n    /// @param _from        Address of the sender.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of the ERC20 sent.\n    /// @param _extraData   Extra data sent with the transaction.\n    function _emitERC20BridgeInitiated(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes memory _extraData\n    )\n        internal\n        virtual\n    {\n        emit ERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _extraData);\n    }\n\n    /// @notice Emits the ERC20BridgeFinalized event and if necessary the appropriate legacy\n    ///         event when an ERC20 bridge is initiated to the other chain.\n    /// @param _localToken  Address of the ERC20 on this chain.\n    /// @param _remoteToken Address of the ERC20 on the remote chain.\n    /// @param _from        Address of the sender.\n    /// @param _to          Address of the receiver.\n    /// @param _amount      Amount of the ERC20 sent.\n    /// @param _extraData   Extra data sent with the transaction.\n    function _emitERC20BridgeFinalized(\n        address _localToken,\n        address _remoteToken,\n        address _from,\n        address _to,\n        uint256 _amount,\n        bytes memory _extraData\n    )\n        internal\n        virtual\n    {\n        emit ERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _extraData);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a >= b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/interfaces/IERC5267Upgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)\n\npragma solidity ^0.8.0;\n\ninterface IERC5267Upgradeable {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"},{"file_path":"src/libraries/Bytes.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @title Bytes\n/// @notice Bytes is a library for manipulating byte arrays.\nlibrary Bytes {\n    /// @custom:attribution https://github.com/GNSPS/solidity-bytes-utils\n    /// @notice Slices a byte array with a given starting index and length. Returns a new byte array\n    ///         as opposed to a pointer to the original array. Will throw if trying to slice more\n    ///         bytes than exist in the array.\n    /// @param _bytes Byte array to slice.\n    /// @param _start Starting index of the slice.\n    /// @param _length Length of the slice.\n    /// @return Slice of the input byte array.\n    function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {\n        unchecked {\n            require(_length + 31 >= _length, \"slice_overflow\");\n            require(_start + _length >= _start, \"slice_overflow\");\n            require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n        }\n\n        bytes memory tempBytes;\n\n        assembly {\n            switch iszero(_length)\n            case 0 {\n                // Get a location of some free memory and store it in tempBytes as\n                // Solidity does for memory variables.\n                tempBytes := mload(0x40)\n\n                // The first word of the slice result is potentially a partial\n                // word read from the original array. To read it, we calculate\n                // the length of that partial word and start copying that many\n                // bytes into the array. The first word we copy will start with\n                // data we don't care about, but the last `lengthmod` bytes will\n                // land at the beginning of the contents of the new array. When\n                // we're done copying, we overwrite the full first word with\n                // the actual length of the slice.\n                let lengthmod := and(_length, 31)\n\n                // The multiplication in the next line is necessary\n                // because when slicing multiples of 32 bytes (lengthmod == 0)\n                // the following copy loop was copying the origin's length\n                // and then ending prematurely not copying everything it should.\n                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n                let end := add(mc, _length)\n\n                for {\n                    // The multiplication in the next line has the same exact purpose\n                    // as the one above.\n                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n                } lt(mc, end) {\n                    mc := add(mc, 0x20)\n                    cc := add(cc, 0x20)\n                } { mstore(mc, mload(cc)) }\n\n                mstore(tempBytes, _length)\n\n                //update free-memory pointer\n                //allocating the array padded to 32 bytes like the compiler does now\n                mstore(0x40, and(add(mc, 31), not(31)))\n            }\n            //if we want a zero-length slice let's just return a zero-length array\n            default {\n                tempBytes := mload(0x40)\n\n                //zero out the 32 bytes slice we are about to return\n                //we need to do it because Solidity does not garbage collect\n                mstore(tempBytes, 0)\n\n                mstore(0x40, add(tempBytes, 0x20))\n            }\n        }\n\n        return tempBytes;\n    }\n\n    /// @notice Slices a byte array with a given starting index up to the end of the original byte\n    ///         array. Returns a new array rathern than a pointer to the original.\n    /// @param _bytes Byte array to slice.\n    /// @param _start Starting index of the slice.\n    /// @return Slice of the input byte array.\n    function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {\n        if (_start >= _bytes.length) {\n            return bytes(\"\");\n        }\n        return slice(_bytes, _start, _bytes.length - _start);\n    }\n\n    /// @notice Converts a byte array into a nibble array by splitting each byte into two nibbles.\n    ///         Resulting nibble array will be exactly twice as long as the input byte array.\n    /// @param _bytes Input byte array to convert.\n    /// @return Resulting nibble array.\n    function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {\n        bytes memory _nibbles;\n        assembly {\n            // Grab a free memory offset for the new array\n            _nibbles := mload(0x40)\n\n            // Load the length of the passed bytes array from memory\n            let bytesLength := mload(_bytes)\n\n            // Calculate the length of the new nibble array\n            // This is the length of the input array times 2\n            let nibblesLength := shl(0x01, bytesLength)\n\n            // Update the free memory pointer to allocate memory for the new array.\n            // To do this, we add the length of the new array + 32 bytes for the array length\n            // rounded up to the nearest 32 byte boundary to the current free memory pointer.\n            mstore(0x40, add(_nibbles, and(not(0x1F), add(nibblesLength, 0x3F))))\n\n            // Store the length of the new array in memory\n            mstore(_nibbles, nibblesLength)\n\n            // Store the memory offset of the _bytes array's contents on the stack\n            let bytesStart := add(_bytes, 0x20)\n\n            // Store the memory offset of the nibbles array's contents on the stack\n            let nibblesStart := add(_nibbles, 0x20)\n\n            // Loop through each byte in the input array\n            for { let i := 0x00 } lt(i, bytesLength) { i := add(i, 0x01) } {\n                // Get the starting offset of the next 2 bytes in the nibbles array\n                let offset := add(nibblesStart, shl(0x01, i))\n                // Load the byte at the current index within the `_bytes` array\n                let b := byte(0x00, mload(add(bytesStart, i)))\n\n                // Pull out the first nibble and store it in the new array\n                mstore8(offset, shr(0x04, b))\n                // Pull out the second nibble and store it in the new array\n                mstore8(add(offset, 0x01), and(b, 0x0F))\n            }\n        }\n        return _nibbles;\n    }\n\n    /// @notice Compares two byte arrays by comparing their keccak256 hashes.\n    /// @param _bytes First byte array to compare.\n    /// @param _other Second byte array to compare.\n    /// @return True if the two byte arrays are equal, false otherwise.\n    function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {\n        return keccak256(_bytes) == keccak256(_other);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Context.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"},{"file_path":"src/libraries/Encoding.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { Types } from \"./Types.sol\";\nimport { Hashing } from \"./Hashing.sol\";\nimport { RLPWriter } from \"./rlp/RLPWriter.sol\";\n\n/// @title Encoding\n/// @notice Encoding handles Optimism's various different encoding schemes.\nlibrary Encoding {\n    /// @notice RLP encodes the L2 transaction that would be generated when a given deposit is sent\n    ///         to the L2 system. Useful for searching for a deposit in the L2 system. The\n    ///         transaction is prefixed with 0x7e to identify its EIP-2718 type.\n    /// @param _tx User deposit transaction to encode.\n    /// @return RLP encoded L2 deposit transaction.\n    function encodeDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes memory) {\n        bytes32 source = Hashing.hashDepositSource(_tx.l1BlockHash, _tx.logIndex);\n        bytes[] memory raw = new bytes[](8);\n        raw[0] = RLPWriter.writeBytes(abi.encodePacked(source));\n        raw[1] = RLPWriter.writeAddress(_tx.from);\n        raw[2] = _tx.isCreation ? RLPWriter.writeBytes(\"\") : RLPWriter.writeAddress(_tx.to);\n        raw[3] = RLPWriter.writeUint(_tx.mint);\n        raw[4] = RLPWriter.writeUint(_tx.value);\n        raw[5] = RLPWriter.writeUint(uint256(_tx.gasLimit));\n        raw[6] = RLPWriter.writeBool(false);\n        raw[7] = RLPWriter.writeBytes(_tx.data);\n        return abi.encodePacked(uint8(0x7e), RLPWriter.writeList(raw));\n    }\n\n    /// @notice Encodes the cross domain message based on the version that is encoded into the\n    ///         message nonce.\n    /// @param _nonce    Message nonce with version encoded into the first two bytes.\n    /// @param _sender   Address of the sender of the message.\n    /// @param _target   Address of the target of the message.\n    /// @param _value    ETH value to send to the target.\n    /// @param _gasLimit Gas limit to use for the message.\n    /// @param _data     Data to send with the message.\n    /// @return Encoded cross domain message.\n    function encodeCrossDomainMessage(\n        uint256 _nonce,\n        address _sender,\n        address _target,\n        uint256 _value,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        (, uint16 version) = decodeVersionedNonce(_nonce);\n        if (version == 0) {\n            return encodeCrossDomainMessageV0(_target, _sender, _data, _nonce);\n        } else if (version == 1) {\n            return encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);\n        } else {\n            revert(\"Encoding: unknown cross domain message version\");\n        }\n    }\n\n    /// @notice Encodes a cross domain message based on the V0 (legacy) encoding.\n    /// @param _target Address of the target of the message.\n    /// @param _sender Address of the sender of the message.\n    /// @param _data   Data to send with the message.\n    /// @param _nonce  Message nonce.\n    /// @return Encoded cross domain message.\n    function encodeCrossDomainMessageV0(\n        address _target,\n        address _sender,\n        bytes memory _data,\n        uint256 _nonce\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        return abi.encodeWithSignature(\"relayMessage(address,address,bytes,uint256)\", _target, _sender, _data, _nonce);\n    }\n\n    /// @notice Encodes a cross domain message based on the V1 (current) encoding.\n    /// @param _nonce    Message nonce.\n    /// @param _sender   Address of the sender of the message.\n    /// @param _target   Address of the target of the message.\n    /// @param _value    ETH value to send to the target.\n    /// @param _gasLimit Gas limit to use for the message.\n    /// @param _data     Data to send with the message.\n    /// @return Encoded cross domain message.\n    function encodeCrossDomainMessageV1(\n        uint256 _nonce,\n        address _sender,\n        address _target,\n        uint256 _value,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        internal\n        pure\n        returns (bytes memory)\n    {\n        return abi.encodeWithSignature(\n            \"relayMessage(uint256,address,address,uint256,uint256,bytes)\",\n            _nonce,\n            _sender,\n            _target,\n            _value,\n            _gasLimit,\n            _data\n        );\n    }\n\n    /// @notice Adds a version number into the first two bytes of a message nonce.\n    /// @param _nonce   Message nonce to encode into.\n    /// @param _version Version number to encode into the message nonce.\n    /// @return Message nonce with version encoded into the first two bytes.\n    function encodeVersionedNonce(uint240 _nonce, uint16 _version) internal pure returns (uint256) {\n        uint256 nonce;\n        assembly {\n            nonce := or(shl(240, _version), _nonce)\n        }\n        return nonce;\n    }\n\n    /// @notice Pulls the version out of a version-encoded nonce.\n    /// @param _nonce Message nonce with version encoded into the first two bytes.\n    /// @return Nonce without encoded version.\n    /// @return Version of the message.\n    function decodeVersionedNonce(uint256 _nonce) internal pure returns (uint240, uint16) {\n        uint240 nonce;\n        uint16 version;\n        assembly {\n            nonce := and(_nonce, 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\n            version := shr(240, _nonce)\n        }\n        return (nonce, version);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.2._\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v2.5._\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     *\n     * _Available since v3.0._\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt248(int256 value) internal pure returns (int248) {\n        require(value >= type(int248).min && value <= type(int248).max, \"SafeCast: value doesn't fit in 248 bits\");\n        return int248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240) {\n        require(value >= type(int240).min && value <= type(int240).max, \"SafeCast: value doesn't fit in 240 bits\");\n        return int240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232) {\n        require(value >= type(int232).min && value <= type(int232).max, \"SafeCast: value doesn't fit in 232 bits\");\n        return int232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224) {\n        require(value >= type(int224).min && value <= type(int224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return int224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216) {\n        require(value >= type(int216).min && value <= type(int216).max, \"SafeCast: value doesn't fit in 216 bits\");\n        return int216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208) {\n        require(value >= type(int208).min && value <= type(int208).max, \"SafeCast: value doesn't fit in 208 bits\");\n        return int208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200) {\n        require(value >= type(int200).min && value <= type(int200).max, \"SafeCast: value doesn't fit in 200 bits\");\n        return int200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192) {\n        require(value >= type(int192).min && value <= type(int192).max, \"SafeCast: value doesn't fit in 192 bits\");\n        return int192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184) {\n        require(value >= type(int184).min && value <= type(int184).max, \"SafeCast: value doesn't fit in 184 bits\");\n        return int184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176) {\n        require(value >= type(int176).min && value <= type(int176).max, \"SafeCast: value doesn't fit in 176 bits\");\n        return int176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168) {\n        require(value >= type(int168).min && value <= type(int168).max, \"SafeCast: value doesn't fit in 168 bits\");\n        return int168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160) {\n        require(value >= type(int160).min && value <= type(int160).max, \"SafeCast: value doesn't fit in 160 bits\");\n        return int160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152) {\n        require(value >= type(int152).min && value <= type(int152).max, \"SafeCast: value doesn't fit in 152 bits\");\n        return int152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144) {\n        require(value >= type(int144).min && value <= type(int144).max, \"SafeCast: value doesn't fit in 144 bits\");\n        return int144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136) {\n        require(value >= type(int136).min && value <= type(int136).max, \"SafeCast: value doesn't fit in 136 bits\");\n        return int136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128) {\n        require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return int128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120) {\n        require(value >= type(int120).min && value <= type(int120).max, \"SafeCast: value doesn't fit in 120 bits\");\n        return int120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112) {\n        require(value >= type(int112).min && value <= type(int112).max, \"SafeCast: value doesn't fit in 112 bits\");\n        return int112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104) {\n        require(value >= type(int104).min && value <= type(int104).max, \"SafeCast: value doesn't fit in 104 bits\");\n        return int104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96) {\n        require(value >= type(int96).min && value <= type(int96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return int96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88) {\n        require(value >= type(int88).min && value <= type(int88).max, \"SafeCast: value doesn't fit in 88 bits\");\n        return int88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80) {\n        require(value >= type(int80).min && value <= type(int80).max, \"SafeCast: value doesn't fit in 80 bits\");\n        return int80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72) {\n        require(value >= type(int72).min && value <= type(int72).max, \"SafeCast: value doesn't fit in 72 bits\");\n        return int72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64) {\n        require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return int64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56) {\n        require(value >= type(int56).min && value <= type(int56).max, \"SafeCast: value doesn't fit in 56 bits\");\n        return int56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48) {\n        require(value >= type(int48).min && value <= type(int48).max, \"SafeCast: value doesn't fit in 48 bits\");\n        return int48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40) {\n        require(value >= type(int40).min && value <= type(int40).max, \"SafeCast: value doesn't fit in 40 bits\");\n        return int40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32) {\n        require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return int32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24) {\n        require(value >= type(int24).min && value <= type(int24).max, \"SafeCast: value doesn't fit in 24 bits\");\n        return int24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16) {\n        require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return int16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8) {\n        require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return int8(value);\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"},{"file_path":"src/universal/Semver.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { Strings } from \"@openzeppelin/contracts/utils/Strings.sol\";\n\n/// @title Semver\n/// @notice Semver is a simple contract for managing contract versions.\ncontract Semver {\n    /// @notice Contract version number (major).\n    uint256 private immutable MAJOR_VERSION;\n\n    /// @notice Contract version number (minor).\n    uint256 private immutable MINOR_VERSION;\n\n    /// @notice Contract version number (patch).\n    uint256 private immutable PATCH_VERSION;\n\n    /// @param _major Version number (major).\n    /// @param _minor Version number (minor).\n    /// @param _patch Version number (patch).\n    constructor(uint256 _major, uint256 _minor, uint256 _patch) {\n        MAJOR_VERSION = _major;\n        MINOR_VERSION = _minor;\n        PATCH_VERSION = _patch;\n    }\n\n    /// @notice Returns the full semver contract version.\n    /// @return Semver contract version as a string.\n    function version() public view returns (string memory) {\n        return string(\n            abi.encodePacked(\n                Strings.toString(MAJOR_VERSION),\n                \".\",\n                Strings.toString(MINOR_VERSION),\n                \".\",\n                Strings.toString(PATCH_VERSION)\n            )\n        );\n    }\n}\n"},{"file_path":"src/libraries/Hashing.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\nimport { Types } from \"./Types.sol\";\nimport { Encoding } from \"./Encoding.sol\";\n\n/// @title Hashing\n/// @notice Hashing handles Optimism's various different hashing schemes.\nlibrary Hashing {\n    /// @notice Computes the hash of the RLP encoded L2 transaction that would be generated when a\n    ///         given deposit is sent to the L2 system. Useful for searching for a deposit in the L2\n    ///         system.\n    /// @param _tx User deposit transaction to hash.\n    /// @return Hash of the RLP encoded L2 deposit transaction.\n    function hashDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes32) {\n        return keccak256(Encoding.encodeDepositTransaction(_tx));\n    }\n\n    /// @notice Computes the deposit transaction's \"source hash\", a value that guarantees the hash\n    ///         of the L2 transaction that corresponds to a deposit is unique and is\n    ///         deterministically generated from L1 transaction data.\n    /// @param _l1BlockHash Hash of the L1 block where the deposit was included.\n    /// @param _logIndex    The index of the log that created the deposit transaction.\n    /// @return Hash of the deposit transaction's \"source hash\".\n    function hashDepositSource(bytes32 _l1BlockHash, uint256 _logIndex) internal pure returns (bytes32) {\n        bytes32 depositId = keccak256(abi.encode(_l1BlockHash, _logIndex));\n        return keccak256(abi.encode(bytes32(0), depositId));\n    }\n\n    /// @notice Hashes the cross domain message based on the version that is encoded into the\n    ///         message nonce.\n    /// @param _nonce    Message nonce with version encoded into the first two bytes.\n    /// @param _sender   Address of the sender of the message.\n    /// @param _target   Address of the target of the message.\n    /// @param _value    ETH value to send to the target.\n    /// @param _gasLimit Gas limit to use for the message.\n    /// @param _data     Data to send with the message.\n    /// @return Hashed cross domain message.\n    function hashCrossDomainMessage(\n        uint256 _nonce,\n        address _sender,\n        address _target,\n        uint256 _value,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        internal\n        pure\n        returns (bytes32)\n    {\n        (, uint16 version) = Encoding.decodeVersionedNonce(_nonce);\n        if (version == 0) {\n            return hashCrossDomainMessageV0(_target, _sender, _data, _nonce);\n        } else if (version == 1) {\n            return hashCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);\n        } else {\n            revert(\"Hashing: unknown cross domain message version\");\n        }\n    }\n\n    /// @notice Hashes a cross domain message based on the V0 (legacy) encoding.\n    /// @param _target Address of the target of the message.\n    /// @param _sender Address of the sender of the message.\n    /// @param _data   Data to send with the message.\n    /// @param _nonce  Message nonce.\n    /// @return Hashed cross domain message.\n    function hashCrossDomainMessageV0(\n        address _target,\n        address _sender,\n        bytes memory _data,\n        uint256 _nonce\n    )\n        internal\n        pure\n        returns (bytes32)\n    {\n        return keccak256(Encoding.encodeCrossDomainMessageV0(_target, _sender, _data, _nonce));\n    }\n\n    /// @notice Hashes a cross domain message based on the V1 (current) encoding.\n    /// @param _nonce    Message nonce.\n    /// @param _sender   Address of the sender of the message.\n    /// @param _target   Address of the target of the message.\n    /// @param _value    ETH value to send to the target.\n    /// @param _gasLimit Gas limit to use for the message.\n    /// @param _data     Data to send with the message.\n    /// @return Hashed cross domain message.\n    function hashCrossDomainMessageV1(\n        uint256 _nonce,\n        address _sender,\n        address _target,\n        uint256 _value,\n        uint256 _gasLimit,\n        bytes memory _data\n    )\n        internal\n        pure\n        returns (bytes32)\n    {\n        return keccak256(Encoding.encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data));\n    }\n\n    /// @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract\n    /// @param _tx Withdrawal transaction to hash.\n    /// @return Hashed withdrawal transaction.\n    function hashWithdrawal(Types.WithdrawalTransaction memory _tx) internal pure returns (bytes32) {\n        return keccak256(abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data));\n    }\n\n    /// @notice Hashes the various elements of an output root proof into an output root hash which\n    ///         can be used to check if the proof is valid.\n    /// @param _outputRootProof Output root proof which should hash to an output root.\n    /// @return Hashed output root proof.\n    function hashOutputRootProof(Types.OutputRootProof memory _outputRootProof) internal pure returns (bytes32) {\n        return keccak256(\n            abi.encode(\n                _outputRootProof.version,\n                _outputRootProof.stateRoot,\n                _outputRootProof.messagePasserStorageRoot,\n                _outputRootProof.latestBlockhash\n            )\n        );\n    }\n}\n"},{"file_path":"src/universal/OptimismMintableERC20.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { ERC20 } from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport { IERC165 } from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport { ILegacyMintableERC20, IOptimismMintableERC20 } from \"src/universal/IOptimismMintableERC20.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\n\n/// @title OptimismMintableERC20\n/// @notice OptimismMintableERC20 is a standard extension of the base ERC20 token contract designed\n///         to allow the StandardBridge contracts to mint and burn tokens. This makes it possible to\n///         use an OptimismMintablERC20 as the L2 representation of an L1 token, or vice-versa.\n///         Designed to be backwards compatible with the older StandardL2ERC20 token which was only\n///         meant for use on L2.\ncontract OptimismMintableERC20 is IOptimismMintableERC20, ILegacyMintableERC20, ERC20, Semver {\n    /// @notice Address of the corresponding version of this token on the remote chain.\n    address public immutable REMOTE_TOKEN;\n\n    /// @notice Address of the StandardBridge on this network.\n    address public immutable BRIDGE;\n\n    /// @notice Decimals of the token\n    uint8 private immutable DECIMALS;\n\n    /// @notice Emitted whenever tokens are minted for an account.\n    /// @param account Address of the account tokens are being minted for.\n    /// @param amount  Amount of tokens minted.\n    event Mint(address indexed account, uint256 amount);\n\n    /// @notice Emitted whenever tokens are burned from an account.\n    /// @param account Address of the account tokens are being burned from.\n    /// @param amount  Amount of tokens burned.\n    event Burn(address indexed account, uint256 amount);\n\n    /// @notice A modifier that only allows the bridge to call\n    modifier onlyBridge() {\n        require(msg.sender == BRIDGE, \"OptimismMintableERC20: only bridge can mint and burn\");\n        _;\n    }\n\n    /// @custom:semver 1.2.1\n    /// @param _bridge      Address of the L2 standard bridge.\n    /// @param _remoteToken Address of the corresponding L1 token.\n    /// @param _name        ERC20 name.\n    /// @param _symbol      ERC20 symbol.\n    constructor(\n        address _bridge,\n        address _remoteToken,\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    )\n        ERC20(_name, _symbol)\n        Semver(1, 2, 1)\n    {\n        REMOTE_TOKEN = _remoteToken;\n        BRIDGE = _bridge;\n        DECIMALS = _decimals;\n    }\n\n    /// @notice Allows the StandardBridge on this network to mint tokens.\n    /// @param _to     Address to mint tokens to.\n    /// @param _amount Amount of tokens to mint.\n    function mint(\n        address _to,\n        uint256 _amount\n    )\n        external\n        virtual\n        override(IOptimismMintableERC20, ILegacyMintableERC20)\n        onlyBridge\n    {\n        _mint(_to, _amount);\n        emit Mint(_to, _amount);\n    }\n\n    /// @notice Allows the StandardBridge on this network to burn tokens.\n    /// @param _from   Address to burn tokens from.\n    /// @param _amount Amount of tokens to burn.\n    function burn(\n        address _from,\n        uint256 _amount\n    )\n        external\n        virtual\n        override(IOptimismMintableERC20, ILegacyMintableERC20)\n        onlyBridge\n    {\n        _burn(_from, _amount);\n        emit Burn(_from, _amount);\n    }\n\n    /// @notice ERC165 interface check function.\n    /// @param _interfaceId Interface ID to check.\n    /// @return Whether or not the interface is supported by this contract.\n    function supportsInterface(bytes4 _interfaceId) external pure virtual returns (bool) {\n        bytes4 iface1 = type(IERC165).interfaceId;\n        // Interface corresponding to the legacy L2StandardERC20.\n        bytes4 iface2 = type(ILegacyMintableERC20).interfaceId;\n        // Interface corresponding to the updated OptimismMintableERC20 (this contract).\n        bytes4 iface3 = type(IOptimismMintableERC20).interfaceId;\n        return _interfaceId == iface1 || _interfaceId == iface2 || _interfaceId == iface3;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for the remote token. Use REMOTE_TOKEN going forward.\n    function l1Token() public view returns (address) {\n        return REMOTE_TOKEN;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for the bridge. Use BRIDGE going forward.\n    function l2Bridge() public view returns (address) {\n        return BRIDGE;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for REMOTE_TOKEN.\n    function remoteToken() public view returns (address) {\n        return REMOTE_TOKEN;\n    }\n\n    /// @custom:legacy\n    /// @notice Legacy getter for BRIDGE.\n    function bridge() public view returns (address) {\n        return BRIDGE;\n    }\n\n    /// @dev Returns the number of decimals used to get its user representation.\n    /// For example, if `decimals` equals `2`, a balance of `505` tokens should\n    /// be displayed to a user as `5.05` (`505 / 10 ** 2`).\n    /// NOTE: This information is only used for _display_ purposes: it in\n    /// no way affects any of the arithmetic of the contract, including\n    /// {IERC20-balanceOf} and {IERC20-transfer}.\n    function decimals() public view override returns (uint8) {\n        return DECIMALS;\n    }\n}\n"},{"file_path":"lib/solmate/src/utils/SafeTransferLib.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Caution! This library won't check that a token has code, responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n    /*//////////////////////////////////////////////////////////////\n                             ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool success;\n\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            success := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        assembly {\n            // We'll write our calldata to this slot below, but restore it later.\n            let memPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(0, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n            mstore(4, from) // Append the \"from\" argument.\n            mstore(36, to) // Append the \"to\" argument.\n            mstore(68, amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 100 because that's the total length of our calldata (4 + 32 * 3)\n                // Counterintuitively, this call() must be positioned after the or() in the\n                // surrounding and() because and() evaluates its arguments from right to left.\n                call(gas(), token, 0, 0, 100, 0, 32)\n            )\n\n            mstore(0x60, 0) // Restore the zero slot to zero.\n            mstore(0x40, memPointer) // Restore the memPointer.\n        }\n\n        require(success, \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        assembly {\n            // We'll write our calldata to this slot below, but restore it later.\n            let memPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(0, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n            mstore(4, to) // Append the \"to\" argument.\n            mstore(36, amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because that's the total length of our calldata (4 + 32 * 2)\n                // Counterintuitively, this call() must be positioned after the or() in the\n                // surrounding and() because and() evaluates its arguments from right to left.\n                call(gas(), token, 0, 0, 68, 0, 32)\n            )\n\n            mstore(0x60, 0) // Restore the zero slot to zero.\n            mstore(0x40, memPointer) // Restore the memPointer.\n        }\n\n        require(success, \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        assembly {\n            // We'll write our calldata to this slot below, but restore it later.\n            let memPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(0, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n            mstore(4, to) // Append the \"to\" argument.\n            mstore(36, amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because that's the total length of our calldata (4 + 32 * 2)\n                // Counterintuitively, this call() must be positioned after the or() in the\n                // surrounding and() because and() evaluates its arguments from right to left.\n                call(gas(), token, 0, 0, 68, 0, 32)\n            )\n\n            mstore(0x60, 0) // Restore the zero slot to zero.\n            mstore(0x40, memPointer) // Restore the memPointer.\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"},{"file_path":"src/mainnet-bridge/ETHYieldManager.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { YieldManager } from \"src/mainnet-bridge/YieldManager.sol\";\nimport { OptimismPortal } from \"src/L1/OptimismPortal.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\n\n/// @custom:proxied\n/// @title ETHYieldManager\n/// @notice Coordinates the accounting, asset management and\n///         yield reporting from ETH yield providers.\ncontract ETHYieldManager is YieldManager, Semver {\n    error CallerIsNotPortal();\n\n    constructor() YieldManager(address(0)) Semver(1, 0, 0) {\n        initialize(OptimismPortal(payable(address(0))), address(0));\n    }\n\n    receive() external payable {}\n\n    /// @notice initializer\n    /// @param _portal Address of the OptimismPortal.\n    /// @param _owner  Address of the YieldManager owner.\n    function initialize(OptimismPortal _portal, address _owner) public initializer {\n        __YieldManager_init(_portal, _owner);\n    }\n\n    /// @inheritdoc YieldManager\n    function tokenBalance() public view override returns (uint256) {\n        return address(this).balance;\n    }\n\n    /// @notice Wrapper for WithdrawalQueue._requestWithdrawal\n    function requestWithdrawal(uint256 amount)\n        external\n        returns (uint256)\n    {\n        if (msg.sender != address(portal)) {\n            revert CallerIsNotPortal();\n        }\n        return _requestWithdrawal(address(portal), amount);\n    }\n\n    /// @notice Sends the yield report to the Shares contract.\n    /// @param data Calldata to send in the message.\n    function _reportYield(bytes memory data) internal override {\n        portal.depositTransaction(Predeploys.SHARES, 0, REPORT_YIELD_DEFAULT_GAS_LIMIT, false, data);\n    }\n}\n"},{"file_path":"src/universal/ISemver.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @title ISemver\n/// @notice ISemver is a simple contract for ensuring that contracts are\n///         versioned using semantic versioning.\ninterface ISemver {\n    /// @notice Getter for the semantic version of the contract. This is not\n    ///         meant to be used onchain but instead meant to be used by offchain\n    ///         tooling.\n    /// @return Semver contract version as a string.\n    function version() external view returns (string memory);\n}\n"},{"file_path":"src/L1/ResourceMetering.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { Initializable } from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport { Burn } from \"src/libraries/Burn.sol\";\nimport { Arithmetic } from \"src/libraries/Arithmetic.sol\";\n\n/// @custom:upgradeable\n/// @title ResourceMetering\n/// @notice ResourceMetering implements an EIP-1559 style resource metering system where pricing\n///         updates automatically based on current demand.\nabstract contract ResourceMetering is Initializable {\n    /// @notice Represents the various parameters that control the way in which resources are\n    ///         metered. Corresponds to the EIP-1559 resource metering system.\n    /// @custom:field prevBaseFee   Base fee from the previous block(s).\n    /// @custom:field prevBoughtGas Amount of gas bought so far in the current block.\n    /// @custom:field prevBlockNum  Last block number that the base fee was updated.\n    struct ResourceParams {\n        uint128 prevBaseFee;\n        uint64 prevBoughtGas;\n        uint64 prevBlockNum;\n    }\n\n    /// @notice Represents the configuration for the EIP-1559 based curve for the deposit gas\n    ///         market. These values should be set with care as it is possible to set them in\n    ///         a way that breaks the deposit gas market. The target resource limit is defined as\n    ///         maxResourceLimit / elasticityMultiplier. This struct was designed to fit within a\n    ///         single word. There is additional space for additions in the future.\n    /// @custom:field maxResourceLimit             Represents the maximum amount of deposit gas that\n    ///                                            can be purchased per block.\n    /// @custom:field elasticityMultiplier         Determines the target resource limit along with\n    ///                                            the resource limit.\n    /// @custom:field baseFeeMaxChangeDenominator  Determines max change on fee per block.\n    /// @custom:field minimumBaseFee               The min deposit base fee, it is clamped to this\n    ///                                            value.\n    /// @custom:field systemTxMaxGas               The amount of gas supplied to the system\n    ///                                            transaction. This should be set to the same\n    ///                                            number that the op-node sets as the gas limit\n    ///                                            for the system transaction.\n    /// @custom:field maximumBaseFee               The max deposit base fee, it is clamped to this\n    ///                                            value.\n    struct ResourceConfig {\n        uint32 maxResourceLimit;\n        uint8 elasticityMultiplier;\n        uint8 baseFeeMaxChangeDenominator;\n        uint32 minimumBaseFee;\n        uint32 systemTxMaxGas;\n        uint128 maximumBaseFee;\n    }\n\n    /// @notice EIP-1559 style gas parameters.\n    ResourceParams public params;\n\n    /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.\n    uint256[48] private __gap;\n\n    /// @notice Meters access to a function based an amount of a requested resource.\n    /// @param _amount Amount of the resource requested.\n    modifier metered(uint64 _amount) {\n        // Record initial gas amount so we can refund for it later.\n        uint256 initialGas = gasleft();\n\n        // Run the underlying function.\n        _;\n\n        // Run the metering function.\n        _metered(_amount, initialGas);\n    }\n\n    /// @notice An internal function that holds all of the logic for metering a resource.\n    /// @param _amount     Amount of the resource requested.\n    /// @param _initialGas The amount of gas before any modifier execution.\n    function _metered(uint64 _amount, uint256 _initialGas) internal {\n        // Update block number and base fee if necessary.\n        uint256 blockDiff = block.number - params.prevBlockNum;\n\n        ResourceConfig memory config = _resourceConfig();\n        int256 targetResourceLimit =\n            int256(uint256(config.maxResourceLimit)) / int256(uint256(config.elasticityMultiplier));\n\n        if (blockDiff > 0) {\n            // Handle updating EIP-1559 style gas parameters. We use EIP-1559 to restrict the rate\n            // at which deposits can be created and therefore limit the potential for deposits to\n            // spam the L2 system. Fee scheme is very similar to EIP-1559 with minor changes.\n            int256 gasUsedDelta = int256(uint256(params.prevBoughtGas)) - targetResourceLimit;\n            int256 baseFeeDelta = (int256(uint256(params.prevBaseFee)) * gasUsedDelta)\n                / (targetResourceLimit * int256(uint256(config.baseFeeMaxChangeDenominator)));\n\n            // Update base fee by adding the base fee delta and clamp the resulting value between\n            // min and max.\n            int256 newBaseFee = Arithmetic.clamp({\n                _value: int256(uint256(params.prevBaseFee)) + baseFeeDelta,\n                _min: int256(uint256(config.minimumBaseFee)),\n                _max: int256(uint256(config.maximumBaseFee))\n            });\n\n            // If we skipped more than one block, we also need to account for every empty block.\n            // Empty block means there was no demand for deposits in that block, so we should\n            // reflect this lack of demand in the fee.\n            if (blockDiff > 1) {\n                // Update the base fee by repeatedly applying the exponent 1-(1/change_denominator)\n                // blockDiff - 1 times. Simulates multiple empty blocks. Clamp the resulting value\n                // between min and max.\n                newBaseFee = Arithmetic.clamp({\n                    _value: Arithmetic.cdexp({\n                        _coefficient: newBaseFee,\n                        _denominator: int256(uint256(config.baseFeeMaxChangeDenominator)),\n                        _exponent: int256(blockDiff - 1)\n                    }),\n                    _min: int256(uint256(config.minimumBaseFee)),\n                    _max: int256(uint256(config.maximumBaseFee))\n                });\n            }\n\n            // Update new base fee, reset bought gas, and update block number.\n            params.prevBaseFee = uint128(uint256(newBaseFee));\n            params.prevBoughtGas = 0;\n            params.prevBlockNum = uint64(block.number);\n        }\n\n        // Make sure we can actually buy the resource amount requested by the user.\n        params.prevBoughtGas += _amount;\n        require(\n            int256(uint256(params.prevBoughtGas)) <= int256(uint256(config.maxResourceLimit)),\n            \"ResourceMetering: cannot buy more gas than available gas limit\"\n        );\n\n        // Determine the amount of ETH to be paid.\n        uint256 resourceCost = uint256(_amount) * uint256(params.prevBaseFee);\n\n        // We currently charge for this ETH amount as an L1 gas burn, so we convert the ETH amount\n        // into gas by dividing by the L1 base fee. We assume a minimum base fee of 1 gwei to avoid\n        // division by zero for L1s that don't support 1559 or to avoid excessive gas burns during\n        // periods of extremely low L1 demand. One-day average gas fee hasn't dipped below 1 gwei\n        // during any 1 day period in the last 5 years, so should be fine.\n        uint256 gasCost = resourceCost / Math.max(block.basefee, 1 gwei);\n\n        // Give the user a refund based on the amount of gas they used to do all of the work up to\n        // this point. Since we're at the end of the modifier, this should be pretty accurate. Acts\n        // effectively like a dynamic stipend (with a minimum value).\n        uint256 usedGas = _initialGas - gasleft();\n        if (gasCost > usedGas) {\n            Burn.gas(gasCost - usedGas);\n        }\n    }\n\n    /// @notice Virtual function that returns the resource config.\n    ///         Contracts that inherit this contract must implement this function.\n    /// @return ResourceConfig\n    function _resourceConfig() internal virtual returns (ResourceConfig memory);\n\n    /// @notice Sets initial resource parameter values.\n    ///         This function must either be called by the initializer function of an upgradeable\n    ///         child contract.\n    // solhint-disable-next-line func-name-mixedcase\n    function __ResourceMetering_init() internal onlyInitializing {\n        if (params.prevBlockNum == 0) {\n            params = ResourceParams({ prevBaseFee: 1 gwei, prevBoughtGas: 0, prevBlockNum: uint64(block.number) });\n        }\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SignedMathUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMathUpgradeable {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"},{"file_path":"src/mainnet-bridge/USDYieldManager.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { IERC20 } from \"@openzeppelin/contracts/interfaces/IERC20.sol\";\n\nimport { YieldManager } from \"src/mainnet-bridge/YieldManager.sol\";\nimport { OptimismPortal } from \"src/L1/OptimismPortal.sol\";\nimport { USDConversions } from \"src/mainnet-bridge/USDConversions.sol\";\nimport { Semver } from \"src/universal/Semver.sol\";\nimport { Predeploys } from \"src/libraries/Predeploys.sol\";\n\n/// @custom:proxied\n/// @title USDYieldManager\n/// @notice Coordinates the accounting, asset management and\n///         yield reporting from USD yield providers.\ncontract USDYieldManager is YieldManager, Semver {\n    /// @param _token Address of withdrawal token. It is assumed that the token\n    ///               has 18 decimals.\n    constructor(address _token) YieldManager(_token) Semver(1, 0, 0) {\n        _disableInitializers();\n    }\n\n    /// @notice initializer\n    /// @param _portal Address of the OptimismPortal.\n    /// @param _owner  Address of the YieldManager owner.\n    function initialize(OptimismPortal _portal, address _owner) public initializer {\n        __YieldManager_init(_portal, _owner);\n        if (TOKEN == address(USDConversions.DAI)) {\n            USDConversions._init();\n        }\n    }\n\n    /// @inheritdoc YieldManager\n    function tokenBalance() public view override returns (uint256) {\n        return IERC20(TOKEN).balanceOf(address(this));\n    }\n\n    /// @notice Wrapper for WithdrawalQueue._requestWithdrawal\n    function requestWithdrawal(address recipient, uint256 amount)\n        external\n        onlyBlastBridge\n        returns (uint256)\n    {\n        return _requestWithdrawal(address(recipient), amount);\n    }\n\n    /// @notice Wrapper for USDConversions._convertTo\n    function convert(\n        address inputTokenAddress,\n        uint256 inputAmountWad,\n        bytes memory _extraData\n    ) external onlyBlastBridge returns (uint256) {\n        return USDConversions._convertTo(\n            inputTokenAddress,\n            TOKEN,\n            inputAmountWad,\n            _extraData\n        );\n    }\n\n    /// @notice Sends the yield report to the USDB contract.\n    /// @param data Calldata to send in the message.\n    function _reportYield(bytes memory data) internal override {\n        portal.depositTransaction(Predeploys.USDB, 0, REPORT_YIELD_DEFAULT_GAS_LIMIT, false, data);\n    }\n}\n"},{"file_path":"src/libraries/Arithmetic.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity 0.8.15;\n\nimport { SignedMath } from \"@openzeppelin/contracts/utils/math/SignedMath.sol\";\nimport { FixedPointMathLib } from \"@rari-capital/solmate/src/utils/FixedPointMathLib.sol\";\n\n/// @title Arithmetic\n/// @notice Even more math than before.\nlibrary Arithmetic {\n    /// @notice Clamps a value between a minimum and maximum.\n    /// @param _value The value to clamp.\n    /// @param _min   The minimum value.\n    /// @param _max   The maximum value.\n    /// @return The clamped value.\n    function clamp(int256 _value, int256 _min, int256 _max) internal pure returns (int256) {\n        return SignedMath.min(SignedMath.max(_value, _min), _max);\n    }\n\n    /// @notice (c)oefficient (d)enominator (exp)onentiation function.\n    ///         Returns the result of: c * (1 - 1/d)^exp.\n    /// @param _coefficient Coefficient of the function.\n    /// @param _denominator Fractional denominator.\n    /// @param _exponent    Power function exponent.\n    /// @return Result of c * (1 - 1/d)^exp.\n    function cdexp(int256 _coefficient, int256 _denominator, int256 _exponent) internal pure returns (int256) {\n        return (_coefficient * (FixedPointMathLib.powWad(1e18 - (1e18 / _denominator), _exponent * 1e18))) / 1e18;\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\nimport \"./math/SignedMathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n    bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = MathUpgradeable.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMathUpgradeable.abs(value))));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, MathUpgradeable.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized != type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"},{"file_path":"src/libraries/rlp/RLPWriter.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @custom:attribution https://github.com/bakaoh/solidity-rlp-encode\n/// @title RLPWriter\n/// @author RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh's\n///         RLPEncode library (https://github.com/bakaoh/solidity-rlp-encode) with minor\n///         modifications to improve legibility.\nlibrary RLPWriter {\n    /// @notice RLP encodes a byte string.\n    /// @param _in The byte string to encode.\n    /// @return out_ The RLP encoded string in bytes.\n    function writeBytes(bytes memory _in) internal pure returns (bytes memory out_) {\n        if (_in.length == 1 && uint8(_in[0]) < 128) {\n            out_ = _in;\n        } else {\n            out_ = abi.encodePacked(_writeLength(_in.length, 128), _in);\n        }\n    }\n\n    /// @notice RLP encodes a list of RLP encoded byte byte strings.\n    /// @param _in The list of RLP encoded byte strings.\n    /// @return list_ The RLP encoded list of items in bytes.\n    function writeList(bytes[] memory _in) internal pure returns (bytes memory list_) {\n        list_ = _flatten(_in);\n        list_ = abi.encodePacked(_writeLength(list_.length, 192), list_);\n    }\n\n    /// @notice RLP encodes a string.\n    /// @param _in The string to encode.\n    /// @return out_ The RLP encoded string in bytes.\n    function writeString(string memory _in) internal pure returns (bytes memory out_) {\n        out_ = writeBytes(bytes(_in));\n    }\n\n    /// @notice RLP encodes an address.\n    /// @param _in The address to encode.\n    /// @return out_ The RLP encoded address in bytes.\n    function writeAddress(address _in) internal pure returns (bytes memory out_) {\n        out_ = writeBytes(abi.encodePacked(_in));\n    }\n\n    /// @notice RLP encodes a uint.\n    /// @param _in The uint256 to encode.\n    /// @return out_ The RLP encoded uint256 in bytes.\n    function writeUint(uint256 _in) internal pure returns (bytes memory out_) {\n        out_ = writeBytes(_toBinary(_in));\n    }\n\n    /// @notice RLP encodes a bool.\n    /// @param _in The bool to encode.\n    /// @return out_ The RLP encoded bool in bytes.\n    function writeBool(bool _in) internal pure returns (bytes memory out_) {\n        out_ = new bytes(1);\n        out_[0] = (_in ? bytes1(0x01) : bytes1(0x80));\n    }\n\n    /// @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.\n    /// @param _len    The length of the string or the payload.\n    /// @param _offset 128 if item is string, 192 if item is list.\n    /// @return out_ RLP encoded bytes.\n    function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory out_) {\n        if (_len < 56) {\n            out_ = new bytes(1);\n            out_[0] = bytes1(uint8(_len) + uint8(_offset));\n        } else {\n            uint256 lenLen;\n            uint256 i = 1;\n            while (_len / i != 0) {\n                lenLen++;\n                i *= 256;\n            }\n\n            out_ = new bytes(lenLen + 1);\n            out_[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);\n            for (i = 1; i <= lenLen; i++) {\n                out_[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));\n            }\n        }\n    }\n\n    /// @notice Encode integer in big endian binary form with no leading zeroes.\n    /// @param _x The integer to encode.\n    /// @return out_ RLP encoded bytes.\n    function _toBinary(uint256 _x) private pure returns (bytes memory out_) {\n        bytes memory b = abi.encodePacked(_x);\n\n        uint256 i = 0;\n        for (; i < 32; i++) {\n            if (b[i] != 0) {\n                break;\n            }\n        }\n\n        out_ = new bytes(32 - i);\n        for (uint256 j = 0; j < out_.length; j++) {\n            out_[j] = b[i++];\n        }\n    }\n\n    /// @custom:attribution https://github.com/Arachnid/solidity-stringutils\n    /// @notice Copies a piece of memory to another location.\n    /// @param _dest Destination location.\n    /// @param _src  Source location.\n    /// @param _len  Length of memory to copy.\n    function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {\n        uint256 dest = _dest;\n        uint256 src = _src;\n        uint256 len = _len;\n\n        for (; len >= 32; len -= 32) {\n            assembly {\n                mstore(dest, mload(src))\n            }\n            dest += 32;\n            src += 32;\n        }\n\n        uint256 mask;\n        unchecked {\n            mask = 256 ** (32 - len) - 1;\n        }\n        assembly {\n            let srcpart := and(mload(src), not(mask))\n            let destpart := and(mload(dest), mask)\n            mstore(dest, or(destpart, srcpart))\n        }\n    }\n\n    /// @custom:attribution https://github.com/sammayo/solidity-rlp-encoder\n    /// @notice Flattens a list of byte strings into one byte string.\n    /// @param _list List of byte strings to flatten.\n    /// @return out_ The flattened byte string.\n    function _flatten(bytes[] memory _list) private pure returns (bytes memory out_) {\n        if (_list.length == 0) {\n            return new bytes(0);\n        }\n\n        uint256 len;\n        uint256 i = 0;\n        for (; i < _list.length; i++) {\n            len += _list[i].length;\n        }\n\n        out_ = new bytes(len);\n        uint256 flattenedPtr;\n        assembly {\n            flattenedPtr := add(out_, 0x20)\n        }\n\n        for (i = 0; i < _list.length; i++) {\n            bytes memory item = _list[i];\n\n            uint256 listPtr;\n            assembly {\n                listPtr := add(item, 0x20)\n            }\n\n            _memcpy(flattenedPtr, listPtr, item.length);\n            flattenedPtr += _list[i].length;\n        }\n    }\n}\n"},{"file_path":"lib/solmate/src/tokens/ERC20.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                            METADATA STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    string public name;\n\n    string public symbol;\n\n    uint8 public immutable decimals;\n\n    /*//////////////////////////////////////////////////////////////\n                              ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 public totalSupply;\n\n    mapping(address => uint256) public balanceOf;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*//////////////////////////////////////////////////////////////\n                            EIP-2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal immutable INITIAL_CHAIN_ID;\n\n    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n    mapping(address => uint256) public nonces;\n\n    /*//////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    ) {\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n\n        INITIAL_CHAIN_ID = block.chainid;\n        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        allowance[msg.sender][spender] = amount;\n\n        emit Approval(msg.sender, spender, amount);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        balanceOf[msg.sender] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(msg.sender, to, amount);\n\n        return true;\n    }\n\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n        balanceOf[from] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        return true;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             EIP-2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            address recoveredAddress = ecrecover(\n                keccak256(\n                    abi.encodePacked(\n                        \"\\x19\\x01\",\n                        DOMAIN_SEPARATOR(),\n                        keccak256(\n                            abi.encode(\n                                keccak256(\n                                    \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n                                ),\n                                owner,\n                                spender,\n                                value,\n                                nonces[owner]++,\n                                deadline\n                            )\n                        )\n                    )\n                ),\n                v,\n                r,\n                s\n            );\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n    }\n\n    function computeDomainSeparator() internal view virtual returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(bytes(name)),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function _mint(address to, uint256 amount) internal virtual {\n        totalSupply += amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(address(0), to, amount);\n    }\n\n    function _burn(address from, uint256 amount) internal virtual {\n        balanceOf[from] -= amount;\n\n        // Cannot underflow because a user's balance\n        // will never be larger than the total supply.\n        unchecked {\n            totalSupply -= amount;\n        }\n\n        emit Transfer(from, address(0), amount);\n    }\n}\n"},{"file_path":"lib/openzeppelin-contracts/contracts/utils/Address.sol","source_code":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n                /// @solidity memory-safe-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"},{"file_path":"src/L2/ERC20PermitUpgradeable.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 51\n */\nabstract contract ERC20PermitUpgradeable is Initializable, IERC20PermitUpgradeable, EIP712Upgradeable {\n    using CountersUpgradeable for CountersUpgradeable.Counter;\n\n    mapping(address => CountersUpgradeable.Counter) private _nonces;\n\n    // solhint-disable-next-line var-name-mixedcase\n    bytes32 public constant PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n    /**\n     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.\n     * However, to ensure consistency with the upgradeable transpiler, we will continue\n     * to reserve a slot.\n     * @custom:oz-renamed-from _PERMIT_TYPEHASH\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;\n\n    /**\n     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n     *\n     * It's a good idea to use the same `name` that is defined as the ERC20 token name.\n     */\n    function __ERC20Permit_init(string memory name) internal onlyInitializing {\n        __EIP712_init_unchained(name, \"1\");\n    }\n\n    function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}\n\n    /**\n     * @dev See {IERC20Permit-permit}.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual override {\n        require(block.timestamp <= deadline, \"ERC20Permit: expired deadline\");\n\n        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        address signer = ECDSAUpgradeable.recover(hash, v, r, s);\n        require(signer == owner, \"ERC20Permit: invalid signature\");\n\n        _approve(owner, spender, value);\n    }\n\n    /**\n     * @dev See {IERC20Permit-nonces}.\n     */\n    function nonces(address owner) public view virtual override returns (uint256) {\n        return _nonces[owner].current();\n    }\n\n    /**\n     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view override returns (bytes32) {\n        return _domainSeparatorV4();\n    }\n\n    /**\n     * @dev \"Consume a nonce\": return the current value and increment.\n     *\n     * _Available since v4.1._\n     */\n    function _useNonce(address owner) internal virtual returns (uint256 current) {\n        CountersUpgradeable.Counter storage nonce = _nonces[owner];\n        current = nonce.current();\n        nonce.increment();\n    }\n\n    /**\n     * @dev See {ERC20-_approve}.\n     */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual;\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"},{"file_path":"src/libraries/Types.sol","source_code":"// SPDX-License-Identifier: BSL 1.1 - Copyright 2024 MetaLayer Labs Ltd.\npragma solidity ^0.8.0;\n\n/// @title Types\n/// @notice Contains various types used throughout the Optimism contract system.\nlibrary Types {\n    /// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1\n    ///         timestamp that the output root is posted. This timestamp is used to verify that the\n    ///         finalization period has passed since the output root was submitted.\n    /// @custom:field outputRoot    Hash of the L2 output.\n    /// @custom:field timestamp     Timestamp of the L1 block that the output root was submitted in.\n    /// @custom:field l2BlockNumber L2 block number that the output corresponds to.\n    struct OutputProposal {\n        bytes32 outputRoot;\n        uint128 timestamp;\n        uint128 l2BlockNumber;\n    }\n\n    /// @notice Struct representing the elements that are hashed together to generate an output root\n    ///         which itself represents a snapshot of the L2 state.\n    /// @custom:field version                  Version of the output root.\n    /// @custom:field stateRoot                Root of the state trie at the block of this output.\n    /// @custom:field messagePasserStorageRoot Root of the message passer storage trie.\n    /// @custom:field latestBlockhash          Hash of the block this output was generated from.\n    struct OutputRootProof {\n        bytes32 version;\n        bytes32 stateRoot;\n        bytes32 messagePasserStorageRoot;\n        bytes32 latestBlockhash;\n    }\n\n    /// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end\n    ///         user (as opposed to a system deposit transaction generated by the system).\n    /// @custom:field from        Address of the sender of the transaction.\n    /// @custom:field to          Address of the recipient of the transaction.\n    /// @custom:field isCreation  True if the transaction is a contract creation.\n    /// @custom:field value       Value to send to the recipient.\n    /// @custom:field mint        Amount of ETH to mint.\n    /// @custom:field gasLimit    Gas limit of the transaction.\n    /// @custom:field data        Data of the transaction.\n    /// @custom:field l1BlockHash Hash of the block the transaction was submitted in.\n    /// @custom:field logIndex    Index of the log in the block the transaction was submitted in.\n    struct UserDepositTransaction {\n        address from;\n        address to;\n        bool isCreation;\n        uint256 value;\n        uint256 mint;\n        uint64 gasLimit;\n        bytes data;\n        bytes32 l1BlockHash;\n        uint256 logIndex;\n    }\n\n    /// @notice Struct representing a withdrawal transaction.\n    /// @custom:field nonce    Nonce of the withdrawal transaction\n    /// @custom:field sender   Address of the sender of the transaction.\n    /// @custom:field target   Address of the recipient of the transaction.\n    /// @custom:field value    Value to send to the recipient.\n    /// @custom:field gasLimit Gas limit of the transaction.\n    /// @custom:field data     Data of the transaction.\n    struct WithdrawalTransaction {\n        uint256 nonce;\n        address sender;\n        address target;\n        uint256 value;\n        uint256 gasLimit;\n        bytes data;\n    }\n}\n"}],"certified":false,"conflicting_implementations":null,"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"localToken","type":"address"},{"indexed":true,"internalType":"address","name":"remoteToken","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"ERC20BridgeFinalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"localToken","type":"address"},{"indexed":true,"internalType":"address","name":"remoteToken","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"ERC20BridgeInitiated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"ETHBridgeFinalized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"ETHBridgeInitiated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"inputs":[],"name":"MESSENGER","outputs":[{"internalType":"contract CrossDomainMessenger","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OTHER_BRIDGE","outputs":[{"internalType":"contract StandardBridge","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"_minGasLimit","type":"uint32"}],"name":"baseGas","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"_localToken","type":"address"},{"internalType":"address","name":"_remoteToken","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_minGasLimit","type":"uint32"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"bridgeERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_localToken","type":"address"},{"internalType":"address","name":"_remoteToken","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint32","name":"_minGasLimit","type":"uint32"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"bridgeERC20To","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_minGasLimit","type":"uint32"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"bridgeETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint32","name":"_minGasLimit","type":"uint32"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"bridgeETHTo","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ethYieldManager","outputs":[{"internalType":"contract ETHYieldManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"ethYieldTokens","outputs":[{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"address","name":"provider","type":"address"},{"internalType":"bool","name":"reportStakedBalance","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_localToken","type":"address"},{"internalType":"address","name":"_remoteToken","type":"address"},{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"finalizeBridgeERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_from","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"finalizeBridgeETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"contract OptimismPortal","name":"_portal","type":"address"},{"internalType":"contract CrossDomainMessenger","name":"_messenger","type":"address"},{"internalType":"contract USDYieldManager","name":"_usdYieldManager","type":"address"},{"internalType":"contract ETHYieldManager","name":"_ethYieldManager","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"messenger","outputs":[{"internalType":"contract CrossDomainMessenger","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"otherBridge","outputs":[{"internalType":"contract StandardBridge","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"portal","outputs":[{"internalType":"contract OptimismPortal","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"address","name":"provider","type":"address"},{"internalType":"bool","name":"reportStakedBalance","type":"bool"}],"name":"setETHYieldToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"address","name":"provider","type":"address"},{"internalType":"bool","name":"reportStakedBalance","type":"bool"}],"name":"setUSDYieldToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"usdYieldManager","outputs":[{"internalType":"contract USDYieldManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"usdYieldTokens","outputs":[{"internalType":"bool","name":"approved","type":"bool"},{"internalType":"uint8","name":"decimals","type":"uint8"},{"internalType":"address","name":"provider","type":"address"},{"internalType":"bool","name":"reportStakedBalance","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}],"is_changed_bytecode":false,"is_partially_verified":true,"constructor_args":null}