ETH Price: $2,572.00 (+2.41%)

Transaction Decoder

Block:
22854031 at Jul-05-2025 03:52:35 PM +UTC
Transaction Fee:
0.000184886834312148 ETH $0.48
Gas Used:
123,639 Gas / 1.495376332 Gwei

Account State Difference:

  Address   Before After State Difference Code
(Titan Builder)
19.021853915854236584 Eth19.021977554854236584 Eth0.000123639
0x4A04b835...370E78279
0x79237628...1e879b7f5
3.573289162487499056 Eth
Nonce: 5366
3.573104275653186908 Eth
Nonce: 5367
0.000184886834312148
0x846d9469...72B68CB09

Execution Trace

PermissionedDisputeGame.resolveClaim( _claimIndex=0, _numToResolve=512 )
  • PermissionedDisputeGame.resolveClaim( _claimIndex=0, _numToResolve=512 )
    • Proxy.7eee288d( )
      • DelayedWETH.unlock( _guy=0x0D8a607F3d2de86adD04Df00f06794cB339A40de, _wad=0 )
        File 1 of 4: PermissionedDisputeGame
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        // Contracts
        import { FaultDisputeGame } from "src/dispute/FaultDisputeGame.sol";
        // Libraries
        import { GameType, Claim, Duration } from "src/dispute/lib/Types.sol";
        import { BadAuth } from "src/dispute/lib/Errors.sol";
        // Interfaces
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        import { IBigStepper } from "src/dispute/interfaces/IBigStepper.sol";
        /// @title PermissionedDisputeGame
        /// @notice PermissionedDisputeGame is a contract that inherits from `FaultDisputeGame`, and contains two roles:
        ///         - The `challenger` role, which is allowed to challenge a dispute.
        ///         - The `proposer` role, which is allowed to create proposals and participate in their game.
        ///         This contract exists as a way for networks to support the fault proof iteration of the OptimismPortal
        ///         contract without needing to support a fully permissionless system. Permissionless systems can introduce
        ///         costs that certain networks may not wish to support. This contract can also be used as a fallback mechanism
        ///         in case of a failure in the permissionless fault proof system in the stage one release.
        contract PermissionedDisputeGame is FaultDisputeGame {
            /// @notice The proposer role is allowed to create proposals and participate in the dispute game.
            address internal immutable PROPOSER;
            /// @notice The challenger role is allowed to participate in the dispute game.
            address internal immutable CHALLENGER;
            /// @notice Modifier that gates access to the `challenger` and `proposer` roles.
            modifier onlyAuthorized() {
                if (!(msg.sender == PROPOSER || msg.sender == CHALLENGER)) {
                    revert BadAuth();
                }
                _;
            }
            /// @param _gameType The type ID of the game.
            /// @param _absolutePrestate The absolute prestate of the instruction trace.
            /// @param _maxGameDepth The maximum depth of bisection.
            /// @param _splitDepth The final depth of the output bisection portion of the game.
            /// @param _clockExtension The clock extension to perform when the remaining duration is less than the extension.
            /// @param _maxClockDuration The maximum amount of time that may accumulate on a team's chess clock.
            /// @param _vm An onchain VM that performs single instruction steps on an FPP trace.
            /// @param _weth WETH contract for holding ETH.
            /// @param _anchorStateRegistry The contract that stores the anchor state for each game type.
            /// @param _l2ChainId Chain ID of the L2 network this contract argues about.
            /// @param _proposer Address that is allowed to create instances of this contract.
            /// @param _challenger Address that is allowed to challenge instances of this contract.
            constructor(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId,
                address _proposer,
                address _challenger
            )
                FaultDisputeGame(
                    _gameType,
                    _absolutePrestate,
                    _maxGameDepth,
                    _splitDepth,
                    _clockExtension,
                    _maxClockDuration,
                    _vm,
                    _weth,
                    _anchorStateRegistry,
                    _l2ChainId
                )
            {
                PROPOSER = _proposer;
                CHALLENGER = _challenger;
            }
            /// @inheritdoc FaultDisputeGame
            function step(
                uint256 _claimIndex,
                bool _isAttack,
                bytes calldata _stateData,
                bytes calldata _proof
            )
                public
                override
                onlyAuthorized
            {
                super.step(_claimIndex, _isAttack, _stateData, _proof);
            }
            /// @notice Generic move function, used for both `attack` and `defend` moves.
            /// @notice _disputed The disputed `Claim`.
            /// @param _challengeIndex The index of the claim being moved against. This must match the `_disputed` claim.
            /// @param _claim The claim at the next logical position in the game.
            /// @param _isAttack Whether or not the move is an attack or defense.
            function move(
                Claim _disputed,
                uint256 _challengeIndex,
                Claim _claim,
                bool _isAttack
            )
                public
                payable
                override
                onlyAuthorized
            {
                super.move(_disputed, _challengeIndex, _claim, _isAttack);
            }
            /// @notice Initializes the contract.
            function initialize() public payable override {
                // The creator of the dispute game must be the proposer EOA.
                if (tx.origin != PROPOSER) revert BadAuth();
                // Fallthrough initialization.
                super.initialize();
            }
            ////////////////////////////////////////////////////////////////
            //                     IMMUTABLE GETTERS                      //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the proposer address.
            function proposer() external view returns (address proposer_) {
                proposer_ = PROPOSER;
            }
            /// @notice Returns the challenger address.
            function challenger() external view returns (address challenger_) {
                challenger_ = CHALLENGER;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        // Libraries
        import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
        import { FixedPointMathLib } from "@solady/utils/FixedPointMathLib.sol";
        import { Clone } from "@solady/utils/Clone.sol";
        import { Types } from "src/libraries/Types.sol";
        import { Hashing } from "src/libraries/Hashing.sol";
        import { RLPReader } from "src/libraries/rlp/RLPReader.sol";
        import {
            GameStatus,
            GameType,
            Claim,
            Position,
            Clock,
            Duration,
            Timestamp,
            Hash,
            OutputRoot,
            LibPosition,
            LibClock,
            LocalPreimageKey,
            VMStatuses
        } from "src/dispute/lib/Types.sol";
        import {
            InvalidParent,
            ClaimAlreadyExists,
            ClaimAlreadyResolved,
            OutOfOrderResolution,
            InvalidChallengePeriod,
            InvalidSplitDepth,
            InvalidClockExtension,
            MaxDepthTooLarge,
            AnchorRootNotFound,
            AlreadyInitialized,
            UnexpectedRootClaim,
            GameNotInProgress,
            InvalidPrestate,
            ValidStep,
            GameDepthExceeded,
            L2BlockNumberChallenged,
            InvalidDisputedClaimIndex,
            ClockTimeExceeded,
            DuplicateStep,
            CannotDefendRootClaim,
            IncorrectBondAmount,
            InvalidLocalIdent,
            BlockNumberMatches,
            InvalidHeaderRLP,
            ClockNotExpired,
            BondTransferFailed,
            NoCreditToClaim,
            InvalidOutputRootProof,
            ClaimAboveSplit
        } from "src/dispute/lib/Errors.sol";
        // Interfaces
        import { ISemver } from "src/universal/interfaces/ISemver.sol";
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IBigStepper, IPreimageOracle } from "src/dispute/interfaces/IBigStepper.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        /// @title FaultDisputeGame
        /// @notice An implementation of the `IFaultDisputeGame` interface.
        contract FaultDisputeGame is Clone, ISemver {
            ////////////////////////////////////////////////////////////////
            //                         Structs                            //
            ////////////////////////////////////////////////////////////////
            /// @notice The `ClaimData` struct represents the data associated with a Claim.
            struct ClaimData {
                uint32 parentIndex;
                address counteredBy;
                address claimant;
                uint128 bond;
                Claim claim;
                Position position;
                Clock clock;
            }
            /// @notice The `ResolutionCheckpoint` struct represents the data associated with an in-progress claim resolution.
            struct ResolutionCheckpoint {
                bool initialCheckpointComplete;
                uint32 subgameIndex;
                Position leftmostPosition;
                address counteredBy;
            }
            ////////////////////////////////////////////////////////////////
            //                         Events                             //
            ////////////////////////////////////////////////////////////////
            /// @notice Emitted when the game is resolved.
            /// @param status The status of the game after resolution.
            event Resolved(GameStatus indexed status);
            /// @notice Emitted when a new claim is added to the DAG by `claimant`
            /// @param parentIndex The index within the `claimData` array of the parent claim
            /// @param claim The claim being added
            /// @param claimant The address of the claimant
            event Move(uint256 indexed parentIndex, Claim indexed claim, address indexed claimant);
            ////////////////////////////////////////////////////////////////
            //                         State Vars                         //
            ////////////////////////////////////////////////////////////////
            /// @notice The absolute prestate of the instruction trace. This is a constant that is defined
            ///         by the program that is being used to execute the trace.
            Claim internal immutable ABSOLUTE_PRESTATE;
            /// @notice The max depth of the game.
            uint256 internal immutable MAX_GAME_DEPTH;
            /// @notice The max depth of the output bisection portion of the position tree. Immediately beneath
            ///         this depth, execution trace bisection begins.
            uint256 internal immutable SPLIT_DEPTH;
            /// @notice The maximum duration that may accumulate on a team's chess clock before they may no longer respond.
            Duration internal immutable MAX_CLOCK_DURATION;
            /// @notice An onchain VM that performs single instruction steps on a fault proof program trace.
            IBigStepper internal immutable VM;
            /// @notice The game type ID.
            GameType internal immutable GAME_TYPE;
            /// @notice WETH contract for holding ETH.
            IDelayedWETH internal immutable WETH;
            /// @notice The anchor state registry.
            IAnchorStateRegistry internal immutable ANCHOR_STATE_REGISTRY;
            /// @notice The chain ID of the L2 network this contract argues about.
            uint256 internal immutable L2_CHAIN_ID;
            /// @notice The duration of the clock extension. Will be doubled if the grandchild is the root claim of an execution
            ///         trace bisection subgame.
            Duration internal immutable CLOCK_EXTENSION;
            /// @notice The global root claim's position is always at gindex 1.
            Position internal constant ROOT_POSITION = Position.wrap(1);
            /// @notice The index of the block number in the RLP-encoded block header.
            /// @dev Consensus encoding reference:
            /// https://github.com/paradigmxyz/reth/blob/5f82993c23164ce8ccdc7bf3ae5085205383a5c8/crates/primitives/src/header.rs#L368
            uint256 internal constant HEADER_BLOCK_NUMBER_INDEX = 8;
            /// @notice Semantic version.
            /// @custom:semver 1.3.1
            string public constant version = "1.3.1";
            /// @notice The starting timestamp of the game
            Timestamp public createdAt;
            /// @notice The timestamp of the game's global resolution.
            Timestamp public resolvedAt;
            /// @notice Returns the current status of the game.
            GameStatus public status;
            /// @notice Flag for the `initialize` function to prevent re-initialization.
            bool internal initialized;
            /// @notice Flag for whether or not the L2 block number claim has been invalidated via `challengeRootL2Block`.
            bool public l2BlockNumberChallenged;
            /// @notice The challenger of the L2 block number claim. Should always be `address(0)` if `l2BlockNumberChallenged`
            ///         is `false`. Should be the address of the challenger if `l2BlockNumberChallenged` is `true`.
            address public l2BlockNumberChallenger;
            /// @notice An append-only array of all claims made during the dispute game.
            ClaimData[] public claimData;
            /// @notice Credited balances for winning participants.
            mapping(address => uint256) public credit;
            /// @notice A mapping to allow for constant-time lookups of existing claims.
            mapping(Hash => bool) public claims;
            /// @notice A mapping of subgames rooted at a claim index to other claim indices in the subgame.
            mapping(uint256 => uint256[]) public subgames;
            /// @notice A mapping of resolved subgames rooted at a claim index.
            mapping(uint256 => bool) public resolvedSubgames;
            /// @notice A mapping of claim indices to resolution checkpoints.
            mapping(uint256 => ResolutionCheckpoint) public resolutionCheckpoints;
            /// @notice The latest finalized output root, serving as the anchor for output bisection.
            OutputRoot public startingOutputRoot;
            /// @param _gameType The type ID of the game.
            /// @param _absolutePrestate The absolute prestate of the instruction trace.
            /// @param _maxGameDepth The maximum depth of bisection.
            /// @param _splitDepth The final depth of the output bisection portion of the game.
            /// @param _clockExtension The clock extension to perform when the remaining duration is less than the extension.
            /// @param _maxClockDuration The maximum amount of time that may accumulate on a team's chess clock.
            /// @param _vm An onchain VM that performs single instruction steps on an FPP trace.
            /// @param _weth WETH contract for holding ETH.
            /// @param _anchorStateRegistry The contract that stores the anchor state for each game type.
            /// @param _l2ChainId Chain ID of the L2 network this contract argues about.
            constructor(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId
            ) {
                // The max game depth may not be greater than `LibPosition.MAX_POSITION_BITLEN - 1`.
                if (_maxGameDepth > LibPosition.MAX_POSITION_BITLEN - 1) revert MaxDepthTooLarge();
                // The split depth plus one cannot be greater than or equal to the max game depth. We add
                // an additional depth to the split depth to avoid a bug in trace ancestor lookup. We know
                // that the case where the split depth is the max value for uint256 is equivalent to the
                // second check though we do need to check it explicitly to avoid an overflow.
                if (_splitDepth == type(uint256).max || _splitDepth + 1 >= _maxGameDepth) revert InvalidSplitDepth();
                // The split depth cannot be 0 or 1 to stay in bounds of clock extension arithmetic.
                if (_splitDepth < 2) revert InvalidSplitDepth();
                // The PreimageOracle challenge period must fit into uint64 so we can safely use it here.
                // Runtime check was added instead of changing the ABI since the contract is already
                // deployed in production. We perform the same check within the PreimageOracle for the
                // benefit of developers but also perform this check here defensively.
                if (_vm.oracle().challengePeriod() > type(uint64).max) revert InvalidChallengePeriod();
                // Determine the maximum clock extension which is either the split depth extension or the
                // maximum game depth extension depending on the configuration of these contracts.
                uint256 splitDepthExtension = uint256(_clockExtension.raw()) * 2;
                uint256 maxGameDepthExtension = uint256(_clockExtension.raw()) + uint256(_vm.oracle().challengePeriod());
                uint256 maxClockExtension = Math.max(splitDepthExtension, maxGameDepthExtension);
                // The maximum clock extension must fit into a uint64.
                if (maxClockExtension > type(uint64).max) revert InvalidClockExtension();
                // The maximum clock extension may not be greater than the maximum clock duration.
                if (uint64(maxClockExtension) > _maxClockDuration.raw()) revert InvalidClockExtension();
                // Set up initial game state.
                GAME_TYPE = _gameType;
                ABSOLUTE_PRESTATE = _absolutePrestate;
                MAX_GAME_DEPTH = _maxGameDepth;
                SPLIT_DEPTH = _splitDepth;
                CLOCK_EXTENSION = _clockExtension;
                MAX_CLOCK_DURATION = _maxClockDuration;
                VM = _vm;
                WETH = _weth;
                ANCHOR_STATE_REGISTRY = _anchorStateRegistry;
                L2_CHAIN_ID = _l2ChainId;
            }
            /// @notice Initializes the contract.
            /// @dev This function may only be called once.
            function initialize() public payable virtual {
                // SAFETY: Any revert in this function will bubble up to the DisputeGameFactory and
                // prevent the game from being created.
                //
                // Implicit assumptions:
                // - The `gameStatus` state variable defaults to 0, which is `GameStatus.IN_PROGRESS`
                // - The dispute game factory will enforce the required bond to initialize the game.
                //
                // Explicit checks:
                // - The game must not have already been initialized.
                // - An output root cannot be proposed at or before the starting block number.
                // INVARIANT: The game must not have already been initialized.
                if (initialized) revert AlreadyInitialized();
                // Grab the latest anchor root.
                (Hash root, uint256 rootBlockNumber) = ANCHOR_STATE_REGISTRY.anchors(GAME_TYPE);
                // Should only happen if this is a new game type that hasn't been set up yet.
                if (root.raw() == bytes32(0)) revert AnchorRootNotFound();
                // Set the starting output root.
                startingOutputRoot = OutputRoot({ l2BlockNumber: rootBlockNumber, root: root });
                // Revert if the calldata size is not the expected length.
                //
                // This is to prevent adding extra or omitting bytes from to `extraData` that result in a different game UUID
                // in the factory, but are not used by the game, which would allow for multiple dispute games for the same
                // output proposal to be created.
                //
                // Expected length: 0x7A
                // - 0x04 selector
                // - 0x14 creator address
                // - 0x20 root claim
                // - 0x20 l1 head
                // - 0x20 extraData
                // - 0x02 CWIA bytes
                assembly {
                    if iszero(eq(calldatasize(), 0x7A)) {
                        // Store the selector for `BadExtraData()` & revert
                        mstore(0x00, 0x9824bdab)
                        revert(0x1C, 0x04)
                    }
                }
                // Do not allow the game to be initialized if the root claim corresponds to a block at or before the
                // configured starting block number.
                if (l2BlockNumber() <= rootBlockNumber) revert UnexpectedRootClaim(rootClaim());
                // Set the root claim
                claimData.push(
                    ClaimData({
                        parentIndex: type(uint32).max,
                        counteredBy: address(0),
                        claimant: gameCreator(),
                        bond: uint128(msg.value),
                        claim: rootClaim(),
                        position: ROOT_POSITION,
                        clock: LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp)))
                    })
                );
                // Set the game as initialized.
                initialized = true;
                // Deposit the bond.
                WETH.deposit{ value: msg.value }();
                // Set the game's starting timestamp
                createdAt = Timestamp.wrap(uint64(block.timestamp));
            }
            ////////////////////////////////////////////////////////////////
            //                  `IFaultDisputeGame` impl                  //
            ////////////////////////////////////////////////////////////////
            /// @notice Perform an instruction step via an on-chain fault proof processor.
            /// @dev This function should point to a fault proof processor in order to execute
            ///      a step in the fault proof program on-chain. The interface of the fault proof
            ///      processor contract should adhere to the `IBigStepper` interface.
            /// @param _claimIndex The index of the challenged claim within `claimData`.
            /// @param _isAttack Whether or not the step is an attack or a defense.
            /// @param _stateData The stateData of the step is the preimage of the claim at the given
            ///        prestate, which is at `_stateIndex` if the move is an attack and `_claimIndex` if
            ///        the move is a defense. If the step is an attack on the first instruction, it is
            ///        the absolute prestate of the fault proof VM.
            /// @param _proof Proof to access memory nodes in the VM's merkle state tree.
            function step(
                uint256 _claimIndex,
                bool _isAttack,
                bytes calldata _stateData,
                bytes calldata _proof
            )
                public
                virtual
            {
                // INVARIANT: Steps cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // Get the parent. If it does not exist, the call will revert with OOB.
                ClaimData storage parent = claimData[_claimIndex];
                // Pull the parent position out of storage.
                Position parentPos = parent.position;
                // Determine the position of the step.
                Position stepPos = parentPos.move(_isAttack);
                // INVARIANT: A step cannot be made unless the move position is 1 below the `MAX_GAME_DEPTH`
                if (stepPos.depth() != MAX_GAME_DEPTH + 1) revert InvalidParent();
                // Determine the expected pre & post states of the step.
                Claim preStateClaim;
                ClaimData storage postState;
                if (_isAttack) {
                    // If the step position's index at depth is 0, the prestate is the absolute
                    // prestate.
                    // If the step is an attack at a trace index > 0, the prestate exists elsewhere in
                    // the game state.
                    // NOTE: We localize the `indexAtDepth` for the current execution trace subgame by finding
                    //       the remainder of the index at depth divided by 2 ** (MAX_GAME_DEPTH - SPLIT_DEPTH),
                    //       which is the number of leaves in each execution trace subgame. This is so that we can
                    //       determine whether or not the step position is represents the `ABSOLUTE_PRESTATE`.
                    preStateClaim = (stepPos.indexAtDepth() % (1 << (MAX_GAME_DEPTH - SPLIT_DEPTH))) == 0
                        ? ABSOLUTE_PRESTATE
                        : _findTraceAncestor(Position.wrap(parentPos.raw() - 1), parent.parentIndex, false).claim;
                    // For all attacks, the poststate is the parent claim.
                    postState = parent;
                } else {
                    // If the step is a defense, the poststate exists elsewhere in the game state,
                    // and the parent claim is the expected pre-state.
                    preStateClaim = parent.claim;
                    postState = _findTraceAncestor(Position.wrap(parentPos.raw() + 1), parent.parentIndex, false);
                }
                // INVARIANT: The prestate is always invalid if the passed `_stateData` is not the
                //            preimage of the prestate claim hash.
                //            We ignore the highest order byte of the digest because it is used to
                //            indicate the VM Status and is added after the digest is computed.
                if (keccak256(_stateData) << 8 != preStateClaim.raw() << 8) revert InvalidPrestate();
                // Compute the local preimage context for the step.
                Hash uuid = _findLocalContext(_claimIndex);
                // INVARIANT: If a step is an attack, the poststate is valid if the step produces
                //            the same poststate hash as the parent claim's value.
                //            If a step is a defense:
                //              1. If the parent claim and the found post state agree with each other
                //                 (depth diff % 2 == 0), the step is valid if it produces the same
                //                 state hash as the post state's claim.
                //              2. If the parent claim and the found post state disagree with each other
                //                 (depth diff % 2 != 0), the parent cannot be countered unless the step
                //                 produces the same state hash as `postState.claim`.
                // SAFETY:    While the `attack` path does not need an extra check for the post
                //            state's depth in relation to the parent, we don't need another
                //            branch because (n - n) % 2 == 0.
                bool validStep = VM.step(_stateData, _proof, uuid.raw()) == postState.claim.raw();
                bool parentPostAgree = (parentPos.depth() - postState.position.depth()) % 2 == 0;
                if (parentPostAgree == validStep) revert ValidStep();
                // INVARIANT: A step cannot be made against a claim for a second time.
                if (parent.counteredBy != address(0)) revert DuplicateStep();
                // Set the parent claim as countered. We do not need to append a new claim to the game;
                // instead, we can just set the existing parent as countered.
                parent.counteredBy = msg.sender;
            }
            /// @notice Generic move function, used for both `attack` and `defend` moves.
            /// @param _disputed The disputed `Claim`.
            /// @param _challengeIndex The index of the claim being moved against.
            /// @param _claim The claim at the next logical position in the game.
            /// @param _isAttack Whether or not the move is an attack or defense.
            function move(Claim _disputed, uint256 _challengeIndex, Claim _claim, bool _isAttack) public payable virtual {
                // INVARIANT: Moves cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // Get the parent. If it does not exist, the call will revert with OOB.
                ClaimData memory parent = claimData[_challengeIndex];
                // INVARIANT: The claim at the _challengeIndex must be the disputed claim.
                if (Claim.unwrap(parent.claim) != Claim.unwrap(_disputed)) revert InvalidDisputedClaimIndex();
                // Compute the position that the claim commits to. Because the parent's position is already
                // known, we can compute the next position by moving left or right depending on whether
                // or not the move is an attack or defense.
                Position parentPos = parent.position;
                Position nextPosition = parentPos.move(_isAttack);
                uint256 nextPositionDepth = nextPosition.depth();
                // INVARIANT: A defense can never be made against the root claim of either the output root game or any
                //            of the execution trace bisection subgames. This is because the root claim commits to the
                //            entire state. Therefore, the only valid defense is to do nothing if it is agreed with.
                if ((_challengeIndex == 0 || nextPositionDepth == SPLIT_DEPTH + 2) && !_isAttack) {
                    revert CannotDefendRootClaim();
                }
                // INVARIANT: No moves against the root claim can be made after it has been challenged with
                //            `challengeRootL2Block`.`
                if (l2BlockNumberChallenged && _challengeIndex == 0) revert L2BlockNumberChallenged();
                // INVARIANT: A move can never surpass the `MAX_GAME_DEPTH`. The only option to counter a
                //            claim at this depth is to perform a single instruction step on-chain via
                //            the `step` function to prove that the state transition produces an unexpected
                //            post-state.
                if (nextPositionDepth > MAX_GAME_DEPTH) revert GameDepthExceeded();
                // When the next position surpasses the split depth (i.e., it is the root claim of an execution
                // trace bisection sub-game), we need to perform some extra verification steps.
                if (nextPositionDepth == SPLIT_DEPTH + 1) {
                    _verifyExecBisectionRoot(_claim, _challengeIndex, parentPos, _isAttack);
                }
                // INVARIANT: The `msg.value` must exactly equal the required bond.
                if (getRequiredBond(nextPosition) != msg.value) revert IncorrectBondAmount();
                // Compute the duration of the next clock. This is done by adding the duration of the
                // grandparent claim to the difference between the current block timestamp and the
                // parent's clock timestamp.
                Duration nextDuration = getChallengerDuration(_challengeIndex);
                // INVARIANT: A move can never be made once its clock has exceeded `MAX_CLOCK_DURATION`
                //            seconds of time.
                if (nextDuration.raw() == MAX_CLOCK_DURATION.raw()) revert ClockTimeExceeded();
                // Clock extension is a mechanism that automatically extends the clock for a potential
                // grandchild claim when there would be less than the clock extension time left if a player
                // is forced to inherit another team's clock when countering a freeloader claim. Exact
                // amount of clock extension time depends exactly where we are within the game.
                uint64 actualExtension;
                if (nextPositionDepth == MAX_GAME_DEPTH - 1) {
                    // If the next position is `MAX_GAME_DEPTH - 1` then we're about to execute a step. Our
                    // clock extension must therefore account for the LPP challenge period in addition to
                    // the standard clock extension.
                    actualExtension = CLOCK_EXTENSION.raw() + uint64(VM.oracle().challengePeriod());
                } else if (nextPositionDepth == SPLIT_DEPTH - 1) {
                    // If the next position is `SPLIT_DEPTH - 1` then we're about to begin an execution
                    // trace bisection and we need to give extra time for the off-chain challenge agent to
                    // be able to generate the initial instruction trace on the native FPVM.
                    actualExtension = CLOCK_EXTENSION.raw() * 2;
                } else {
                    // Otherwise, we just use the standard clock extension.
                    actualExtension = CLOCK_EXTENSION.raw();
                }
                // Check if we need to apply the clock extension.
                if (nextDuration.raw() > MAX_CLOCK_DURATION.raw() - actualExtension) {
                    nextDuration = Duration.wrap(MAX_CLOCK_DURATION.raw() - actualExtension);
                }
                // Construct the next clock with the new duration and the current block timestamp.
                Clock nextClock = LibClock.wrap(nextDuration, Timestamp.wrap(uint64(block.timestamp)));
                // INVARIANT: There cannot be multiple identical claims with identical moves on the same challengeIndex. Multiple
                //            claims at the same position may dispute the same challengeIndex. However, they must have different
                //            values.
                Hash claimHash = _claim.hashClaimPos(nextPosition, _challengeIndex);
                if (claims[claimHash]) revert ClaimAlreadyExists();
                claims[claimHash] = true;
                // Create the new claim.
                claimData.push(
                    ClaimData({
                        parentIndex: uint32(_challengeIndex),
                        // This is updated during subgame resolution
                        counteredBy: address(0),
                        claimant: msg.sender,
                        bond: uint128(msg.value),
                        claim: _claim,
                        position: nextPosition,
                        clock: nextClock
                    })
                );
                // Update the subgame rooted at the parent claim.
                subgames[_challengeIndex].push(claimData.length - 1);
                // Deposit the bond.
                WETH.deposit{ value: msg.value }();
                // Emit the appropriate event for the attack or defense.
                emit Move(_challengeIndex, _claim, msg.sender);
            }
            /// @notice Attack a disagreed upon `Claim`.
            /// @param _disputed The `Claim` being attacked.
            /// @param _parentIndex Index of the `Claim` to attack in the `claimData` array. This must match the `_disputed`
            /// claim.
            /// @param _claim The `Claim` at the relative attack position.
            function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
                move(_disputed, _parentIndex, _claim, true);
            }
            /// @notice Defend an agreed upon `Claim`.
            /// @notice _disputed The `Claim` being defended.
            /// @param _parentIndex Index of the claim to defend in the `claimData` array. This must match the `_disputed`
            /// claim.
            /// @param _claim The `Claim` at the relative defense position.
            function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
                move(_disputed, _parentIndex, _claim, false);
            }
            /// @notice Posts the requested local data to the VM's `PreimageOralce`.
            /// @param _ident The local identifier of the data to post.
            /// @param _execLeafIdx The index of the leaf claim in an execution subgame that requires the local data for a step.
            /// @param _partOffset The offset of the data to post.
            function addLocalData(uint256 _ident, uint256 _execLeafIdx, uint256 _partOffset) external {
                // INVARIANT: Local data can only be added if the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                (Claim starting, Position startingPos, Claim disputed, Position disputedPos) =
                    _findStartingAndDisputedOutputs(_execLeafIdx);
                Hash uuid = _computeLocalContext(starting, startingPos, disputed, disputedPos);
                IPreimageOracle oracle = VM.oracle();
                if (_ident == LocalPreimageKey.L1_HEAD_HASH) {
                    // Load the L1 head hash
                    oracle.loadLocalData(_ident, uuid.raw(), l1Head().raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.STARTING_OUTPUT_ROOT) {
                    // Load the starting proposal's output root.
                    oracle.loadLocalData(_ident, uuid.raw(), starting.raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.DISPUTED_OUTPUT_ROOT) {
                    // Load the disputed proposal's output root
                    oracle.loadLocalData(_ident, uuid.raw(), disputed.raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER) {
                    // Load the disputed proposal's L2 block number as a big-endian uint64 in the
                    // high order 8 bytes of the word.
                    // We add the index at depth + 1 to the starting block number to get the disputed L2
                    // block number.
                    uint256 l2Number = startingOutputRoot.l2BlockNumber + disputedPos.traceIndex(SPLIT_DEPTH) + 1;
                    // Choose the minimum between the `l2BlockNumber` claim and the bisected-to L2 block number.
                    l2Number = l2Number < l2BlockNumber() ? l2Number : l2BlockNumber();
                    oracle.loadLocalData(_ident, uuid.raw(), bytes32(l2Number << 0xC0), 8, _partOffset);
                } else if (_ident == LocalPreimageKey.CHAIN_ID) {
                    // Load the chain ID as a big-endian uint64 in the high order 8 bytes of the word.
                    oracle.loadLocalData(_ident, uuid.raw(), bytes32(L2_CHAIN_ID << 0xC0), 8, _partOffset);
                } else {
                    revert InvalidLocalIdent();
                }
            }
            /// @notice Returns the number of children that still need to be resolved in order to fully resolve a subgame rooted
            ///         at `_claimIndex`.
            /// @param _claimIndex The subgame root claim's index within `claimData`.
            /// @return numRemainingChildren_ The number of children that still need to be checked to resolve the subgame.
            function getNumToResolve(uint256 _claimIndex) public view returns (uint256 numRemainingChildren_) {
                ResolutionCheckpoint storage checkpoint = resolutionCheckpoints[_claimIndex];
                uint256[] storage challengeIndices = subgames[_claimIndex];
                uint256 challengeIndicesLen = challengeIndices.length;
                numRemainingChildren_ = challengeIndicesLen - checkpoint.subgameIndex;
            }
            /// @notice The l2BlockNumber of the disputed output root in the `L2OutputOracle`.
            function l2BlockNumber() public pure returns (uint256 l2BlockNumber_) {
                l2BlockNumber_ = _getArgUint256(0x54);
            }
            /// @notice Only the starting block number of the game.
            function startingBlockNumber() external view returns (uint256 startingBlockNumber_) {
                startingBlockNumber_ = startingOutputRoot.l2BlockNumber;
            }
            /// @notice Starting output root and block number of the game.
            function startingRootHash() external view returns (Hash startingRootHash_) {
                startingRootHash_ = startingOutputRoot.root;
            }
            /// @notice Challenges the root L2 block number by providing the preimage of the output root and the L2 block header
            ///         and showing that the committed L2 block number is incorrect relative to the claimed L2 block number.
            /// @param _outputRootProof The output root proof.
            /// @param _headerRLP The RLP-encoded L2 block header.
            function challengeRootL2Block(
                Types.OutputRootProof calldata _outputRootProof,
                bytes calldata _headerRLP
            )
                external
            {
                // INVARIANT: Moves cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // The root L2 block claim can only be challenged once.
                if (l2BlockNumberChallenged) revert L2BlockNumberChallenged();
                // Verify the output root preimage.
                if (Hashing.hashOutputRootProof(_outputRootProof) != rootClaim().raw()) revert InvalidOutputRootProof();
                // Verify the block hash preimage.
                if (keccak256(_headerRLP) != _outputRootProof.latestBlockhash) revert InvalidHeaderRLP();
                // Decode the header RLP to find the number of the block. In the consensus encoding, the timestamp
                // is the 9th element in the list that represents the block header.
                RLPReader.RLPItem[] memory headerContents = RLPReader.readList(RLPReader.toRLPItem(_headerRLP));
                bytes memory rawBlockNumber = RLPReader.readBytes(headerContents[HEADER_BLOCK_NUMBER_INDEX]);
                // Sanity check the block number string length.
                if (rawBlockNumber.length > 32) revert InvalidHeaderRLP();
                // Convert the raw, left-aligned block number to a uint256 by aligning it as a big-endian
                // number in the low-order bytes of a 32-byte word.
                //
                // SAFETY: The length of `rawBlockNumber` is checked above to ensure it is at most 32 bytes.
                uint256 blockNumber;
                assembly {
                    blockNumber := shr(shl(0x03, sub(0x20, mload(rawBlockNumber))), mload(add(rawBlockNumber, 0x20)))
                }
                // Ensure the block number does not match the block number claimed in the dispute game.
                if (blockNumber == l2BlockNumber()) revert BlockNumberMatches();
                // Issue a special counter to the root claim. This counter will always win the root claim subgame, and receive
                // the bond from the root claimant.
                l2BlockNumberChallenger = msg.sender;
                l2BlockNumberChallenged = true;
            }
            ////////////////////////////////////////////////////////////////
            //                    `IDisputeGame` impl                     //
            ////////////////////////////////////////////////////////////////
            /// @notice If all necessary information has been gathered, this function should mark the game
            ///         status as either `CHALLENGER_WINS` or `DEFENDER_WINS` and return the status of
            ///         the resolved game. It is at this stage that the bonds should be awarded to the
            ///         necessary parties.
            /// @dev May only be called if the `status` is `IN_PROGRESS`.
            /// @return status_ The status of the game after resolution.
            function resolve() external returns (GameStatus status_) {
                // INVARIANT: Resolution cannot occur unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // INVARIANT: Resolution cannot occur unless the absolute root subgame has been resolved.
                if (!resolvedSubgames[0]) revert OutOfOrderResolution();
                // Update the global game status; The dispute has concluded.
                status_ = claimData[0].counteredBy == address(0) ? GameStatus.DEFENDER_WINS : GameStatus.CHALLENGER_WINS;
                resolvedAt = Timestamp.wrap(uint64(block.timestamp));
                // Update the status and emit the resolved event, note that we're performing an assignment here.
                emit Resolved(status = status_);
                // Try to update the anchor state, this should not revert.
                ANCHOR_STATE_REGISTRY.tryUpdateAnchorState();
            }
            /// @notice Resolves the subgame rooted at the given claim index. `_numToResolve` specifies how many children of
            ///         the subgame will be checked in this call. If `_numToResolve` is less than the number of children, an
            ///         internal cursor will be updated and this function may be called again to complete resolution of the
            ///         subgame.
            /// @dev This function must be called bottom-up in the DAG
            ///      A subgame is a tree of claims that has a maximum depth of 1.
            ///      A subgame root claims is valid if, and only if, all of its child claims are invalid.
            ///      At the deepest level in the DAG, a claim is invalid if there's a successful step against it.
            /// @param _claimIndex The index of the subgame root claim to resolve.
            /// @param _numToResolve The number of subgames to resolve in this call. If the input is `0`, and this is the first
            ///                      page, this function will attempt to check all of the subgame's children at once.
            function resolveClaim(uint256 _claimIndex, uint256 _numToResolve) external {
                // INVARIANT: Resolution cannot occur unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                ClaimData storage subgameRootClaim = claimData[_claimIndex];
                Duration challengeClockDuration = getChallengerDuration(_claimIndex);
                // INVARIANT: Cannot resolve a subgame unless the clock of its would-be counter has expired
                // INVARIANT: Assuming ordered subgame resolution, challengeClockDuration is always >= MAX_CLOCK_DURATION if all
                // descendant subgames are resolved
                if (challengeClockDuration.raw() < MAX_CLOCK_DURATION.raw()) revert ClockNotExpired();
                // INVARIANT: Cannot resolve a subgame twice.
                if (resolvedSubgames[_claimIndex]) revert ClaimAlreadyResolved();
                uint256[] storage challengeIndices = subgames[_claimIndex];
                uint256 challengeIndicesLen = challengeIndices.length;
                // Uncontested claims are resolved implicitly unless they are the root claim. Pay out the bond to the claimant
                // and return early.
                if (challengeIndicesLen == 0 && _claimIndex != 0) {
                    // In the event that the parent claim is at the max depth, there will always be 0 subgames. If the
                    // `counteredBy` field is set and there are no subgames, this implies that the parent claim was successfully
                    // stepped against. In this case, we pay out the bond to the party that stepped against the parent claim.
                    // Otherwise, the parent claim is uncontested, and the bond is returned to the claimant.
                    address counteredBy = subgameRootClaim.counteredBy;
                    address recipient = counteredBy == address(0) ? subgameRootClaim.claimant : counteredBy;
                    _distributeBond(recipient, subgameRootClaim);
                    resolvedSubgames[_claimIndex] = true;
                    return;
                }
                // Fetch the resolution checkpoint from storage.
                ResolutionCheckpoint memory checkpoint = resolutionCheckpoints[_claimIndex];
                // If the checkpoint does not currently exist, initialize the current left most position as max u128.
                if (!checkpoint.initialCheckpointComplete) {
                    checkpoint.leftmostPosition = Position.wrap(type(uint128).max);
                    checkpoint.initialCheckpointComplete = true;
                    // If `_numToResolve == 0`, assume that we can check all child subgames in this one callframe.
                    if (_numToResolve == 0) _numToResolve = challengeIndicesLen;
                }
                // Assume parent is honest until proven otherwise
                uint256 lastToResolve = checkpoint.subgameIndex + _numToResolve;
                uint256 finalCursor = lastToResolve > challengeIndicesLen ? challengeIndicesLen : lastToResolve;
                for (uint256 i = checkpoint.subgameIndex; i < finalCursor; i++) {
                    uint256 challengeIndex = challengeIndices[i];
                    // INVARIANT: Cannot resolve a subgame containing an unresolved claim
                    if (!resolvedSubgames[challengeIndex]) revert OutOfOrderResolution();
                    ClaimData storage claim = claimData[challengeIndex];
                    // If the child subgame is uncountered and further left than the current left-most counter,
                    // update the parent subgame's `countered` address and the current `leftmostCounter`.
                    // The left-most correct counter is preferred in bond payouts in order to discourage attackers
                    // from countering invalid subgame roots via an invalid defense position. As such positions
                    // cannot be correctly countered.
                    // Note that correctly positioned defense, but invalid claimes can still be successfully countered.
                    if (claim.counteredBy == address(0) && checkpoint.leftmostPosition.raw() > claim.position.raw()) {
                        checkpoint.counteredBy = claim.claimant;
                        checkpoint.leftmostPosition = claim.position;
                    }
                }
                // Increase the checkpoint's cursor position by the number of children that were checked.
                checkpoint.subgameIndex = uint32(finalCursor);
                // Persist the checkpoint and allow for continuing in a separate transaction, if resolution is not already
                // complete.
                resolutionCheckpoints[_claimIndex] = checkpoint;
                // If all children have been traversed in the above loop, the subgame may be resolved. Otherwise, persist the
                // checkpoint and allow for continuation in a separate transaction.
                if (checkpoint.subgameIndex == challengeIndicesLen) {
                    address countered = checkpoint.counteredBy;
                    // Mark the subgame as resolved.
                    resolvedSubgames[_claimIndex] = true;
                    // Distribute the bond to the appropriate party.
                    if (_claimIndex == 0 && l2BlockNumberChallenged) {
                        // Special case: If the root claim has been challenged with the `challengeRootL2Block` function,
                        // the bond is always paid out to the issuer of that challenge.
                        address challenger = l2BlockNumberChallenger;
                        _distributeBond(challenger, subgameRootClaim);
                        subgameRootClaim.counteredBy = challenger;
                    } else {
                        // If the parent was not successfully countered, pay out the parent's bond to the claimant.
                        // If the parent was successfully countered, pay out the parent's bond to the challenger.
                        _distributeBond(countered == address(0) ? subgameRootClaim.claimant : countered, subgameRootClaim);
                        // Once a subgame is resolved, we percolate the result up the DAG so subsequent calls to
                        // resolveClaim will not need to traverse this subgame.
                        subgameRootClaim.counteredBy = countered;
                    }
                }
            }
            /// @notice Getter for the game type.
            /// @dev The reference impl should be entirely different depending on the type (fault, validity)
            ///      i.e. The game type should indicate the security model.
            /// @return gameType_ The type of proof system being used.
            function gameType() public view returns (GameType gameType_) {
                gameType_ = GAME_TYPE;
            }
            /// @notice Getter for the creator of the dispute game.
            /// @dev `clones-with-immutable-args` argument #1
            /// @return creator_ The creator of the dispute game.
            function gameCreator() public pure returns (address creator_) {
                creator_ = _getArgAddress(0x00);
            }
            /// @notice Getter for the root claim.
            /// @dev `clones-with-immutable-args` argument #2
            /// @return rootClaim_ The root claim of the DisputeGame.
            function rootClaim() public pure returns (Claim rootClaim_) {
                rootClaim_ = Claim.wrap(_getArgBytes32(0x14));
            }
            /// @notice Getter for the parent hash of the L1 block when the dispute game was created.
            /// @dev `clones-with-immutable-args` argument #3
            /// @return l1Head_ The parent hash of the L1 block when the dispute game was created.
            function l1Head() public pure returns (Hash l1Head_) {
                l1Head_ = Hash.wrap(_getArgBytes32(0x34));
            }
            /// @notice Getter for the extra data.
            /// @dev `clones-with-immutable-args` argument #4
            /// @return extraData_ Any extra data supplied to the dispute game contract by the creator.
            function extraData() public pure returns (bytes memory extraData_) {
                // The extra data starts at the second word within the cwia calldata and
                // is 32 bytes long.
                extraData_ = _getArgBytes(0x54, 0x20);
            }
            /// @notice A compliant implementation of this interface should return the components of the
            ///         game UUID's preimage provided in the cwia payload. The preimage of the UUID is
            ///         constructed as `keccak256(gameType . rootClaim . extraData)` where `.` denotes
            ///         concatenation.
            /// @return gameType_ The type of proof system being used.
            /// @return rootClaim_ The root claim of the DisputeGame.
            /// @return extraData_ Any extra data supplied to the dispute game contract by the creator.
            function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_) {
                gameType_ = gameType();
                rootClaim_ = rootClaim();
                extraData_ = extraData();
            }
            ////////////////////////////////////////////////////////////////
            //                       MISC EXTERNAL                        //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the required bond for a given move kind.
            /// @param _position The position of the bonded interaction.
            /// @return requiredBond_ The required ETH bond for the given move, in wei.
            function getRequiredBond(Position _position) public view returns (uint256 requiredBond_) {
                uint256 depth = uint256(_position.depth());
                if (depth > MAX_GAME_DEPTH) revert GameDepthExceeded();
                // Values taken from Big Bonds v1.5 (TM) spec.
                uint256 assumedBaseFee = 200 gwei;
                uint256 baseGasCharged = 400_000;
                uint256 highGasCharged = 300_000_000;
                // Goal here is to compute the fixed multiplier that will be applied to the base gas
                // charged to get the required gas amount for the given depth. We apply this multiplier
                // some `n` times where `n` is the depth of the position. We are looking for some number
                // that, when multiplied by itself `MAX_GAME_DEPTH` times and then multiplied by the base
                // gas charged, will give us the maximum gas that we want to charge.
                // We want to solve for (highGasCharged/baseGasCharged) ** (1/MAX_GAME_DEPTH).
                // We know that a ** (b/c) is equal to e ** (ln(a) * (b/c)).
                // We can compute e ** (ln(a) * (b/c)) quite easily with FixedPointMathLib.
                // Set up a, b, and c.
                uint256 a = highGasCharged / baseGasCharged;
                uint256 b = FixedPointMathLib.WAD;
                uint256 c = MAX_GAME_DEPTH * FixedPointMathLib.WAD;
                // Compute ln(a).
                // slither-disable-next-line divide-before-multiply
                uint256 lnA = uint256(FixedPointMathLib.lnWad(int256(a * FixedPointMathLib.WAD)));
                // Computes (b / c) with full precision using WAD = 1e18.
                uint256 bOverC = FixedPointMathLib.divWad(b, c);
                // Compute e ** (ln(a) * (b/c))
                // sMulWad can be used here since WAD = 1e18 maintains the same precision.
                uint256 numerator = FixedPointMathLib.mulWad(lnA, bOverC);
                int256 base = FixedPointMathLib.expWad(int256(numerator));
                // Compute the required gas amount.
                int256 rawGas = FixedPointMathLib.powWad(base, int256(depth * FixedPointMathLib.WAD));
                uint256 requiredGas = FixedPointMathLib.mulWad(baseGasCharged, uint256(rawGas));
                // Compute the required bond.
                requiredBond_ = assumedBaseFee * requiredGas;
            }
            /// @notice Claim the credit belonging to the recipient address.
            /// @param _recipient The owner and recipient of the credit.
            function claimCredit(address _recipient) external {
                // Remove the credit from the recipient prior to performing the external call.
                uint256 recipientCredit = credit[_recipient];
                credit[_recipient] = 0;
                // Revert if the recipient has no credit to claim.
                if (recipientCredit == 0) revert NoCreditToClaim();
                // Try to withdraw the WETH amount so it can be used here.
                WETH.withdraw(_recipient, recipientCredit);
                // Transfer the credit to the recipient.
                (bool success,) = _recipient.call{ value: recipientCredit }(hex"");
                if (!success) revert BondTransferFailed();
            }
            /// @notice Returns the amount of time elapsed on the potential challenger to `_claimIndex`'s chess clock. Maxes
            ///         out at `MAX_CLOCK_DURATION`.
            /// @param _claimIndex The index of the subgame root claim.
            /// @return duration_ The time elapsed on the potential challenger to `_claimIndex`'s chess clock.
            function getChallengerDuration(uint256 _claimIndex) public view returns (Duration duration_) {
                // INVARIANT: The game must be in progress to query the remaining time to respond to a given claim.
                if (status != GameStatus.IN_PROGRESS) {
                    revert GameNotInProgress();
                }
                // Fetch the subgame root claim.
                ClaimData storage subgameRootClaim = claimData[_claimIndex];
                // Fetch the parent of the subgame root's clock, if it exists.
                Clock parentClock;
                if (subgameRootClaim.parentIndex != type(uint32).max) {
                    parentClock = claimData[subgameRootClaim.parentIndex].clock;
                }
                // Compute the duration elapsed of the potential challenger's clock.
                uint64 challengeDuration =
                    uint64(parentClock.duration().raw() + (block.timestamp - subgameRootClaim.clock.timestamp().raw()));
                duration_ = challengeDuration > MAX_CLOCK_DURATION.raw() ? MAX_CLOCK_DURATION : Duration.wrap(challengeDuration);
            }
            /// @notice Returns the length of the `claimData` array.
            function claimDataLen() external view returns (uint256 len_) {
                len_ = claimData.length;
            }
            ////////////////////////////////////////////////////////////////
            //                     IMMUTABLE GETTERS                      //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the absolute prestate of the instruction trace.
            function absolutePrestate() external view returns (Claim absolutePrestate_) {
                absolutePrestate_ = ABSOLUTE_PRESTATE;
            }
            /// @notice Returns the max game depth.
            function maxGameDepth() external view returns (uint256 maxGameDepth_) {
                maxGameDepth_ = MAX_GAME_DEPTH;
            }
            /// @notice Returns the split depth.
            function splitDepth() external view returns (uint256 splitDepth_) {
                splitDepth_ = SPLIT_DEPTH;
            }
            /// @notice Returns the max clock duration.
            function maxClockDuration() external view returns (Duration maxClockDuration_) {
                maxClockDuration_ = MAX_CLOCK_DURATION;
            }
            /// @notice Returns the clock extension constant.
            function clockExtension() external view returns (Duration clockExtension_) {
                clockExtension_ = CLOCK_EXTENSION;
            }
            /// @notice Returns the address of the VM.
            function vm() external view returns (IBigStepper vm_) {
                vm_ = VM;
            }
            /// @notice Returns the WETH contract for holding ETH.
            function weth() external view returns (IDelayedWETH weth_) {
                weth_ = WETH;
            }
            /// @notice Returns the anchor state registry contract.
            function anchorStateRegistry() external view returns (IAnchorStateRegistry registry_) {
                registry_ = ANCHOR_STATE_REGISTRY;
            }
            /// @notice Returns the chain ID of the L2 network this contract argues about.
            function l2ChainId() external view returns (uint256 l2ChainId_) {
                l2ChainId_ = L2_CHAIN_ID;
            }
            ////////////////////////////////////////////////////////////////
            //                          HELPERS                           //
            ////////////////////////////////////////////////////////////////
            /// @notice Pays out the bond of a claim to a given recipient.
            /// @param _recipient The recipient of the bond.
            /// @param _bonded The claim to pay out the bond of.
            function _distributeBond(address _recipient, ClaimData storage _bonded) internal {
                // Set all bits in the bond value to indicate that the bond has been paid out.
                uint256 bond = _bonded.bond;
                // Increase the recipient's credit.
                credit[_recipient] += bond;
                // Unlock the bond.
                WETH.unlock(_recipient, bond);
            }
            /// @notice Verifies the integrity of an execution bisection subgame's root claim. Reverts if the claim
            ///         is invalid.
            /// @param _rootClaim The root claim of the execution bisection subgame.
            function _verifyExecBisectionRoot(
                Claim _rootClaim,
                uint256 _parentIdx,
                Position _parentPos,
                bool _isAttack
            )
                internal
                view
            {
                // The root claim of an execution trace bisection sub-game must:
                // 1. Signal that the VM panicked or resulted in an invalid transition if the disputed output root
                //    was made by the opposing party.
                // 2. Signal that the VM resulted in a valid transition if the disputed output root was made by the same party.
                // If the move is a defense, the disputed output could have been made by either party. In this case, we
                // need to search for the parent output to determine what the expected status byte should be.
                Position disputedLeafPos = Position.wrap(_parentPos.raw() + 1);
                ClaimData storage disputed = _findTraceAncestor({ _pos: disputedLeafPos, _start: _parentIdx, _global: true });
                uint8 vmStatus = uint8(_rootClaim.raw()[0]);
                if (_isAttack || disputed.position.depth() % 2 == SPLIT_DEPTH % 2) {
                    // If the move is an attack, the parent output is always deemed to be disputed. In this case, we only need
                    // to check that the root claim signals that the VM panicked or resulted in an invalid transition.
                    // If the move is a defense, and the disputed output and creator of the execution trace subgame disagree,
                    // the root claim should also signal that the VM panicked or resulted in an invalid transition.
                    if (!(vmStatus == VMStatuses.INVALID.raw() || vmStatus == VMStatuses.PANIC.raw())) {
                        revert UnexpectedRootClaim(_rootClaim);
                    }
                } else if (vmStatus != VMStatuses.VALID.raw()) {
                    // The disputed output and the creator of the execution trace subgame agree. The status byte should
                    // have signaled that the VM succeeded.
                    revert UnexpectedRootClaim(_rootClaim);
                }
            }
            /// @notice Finds the trace ancestor of a given position within the DAG.
            /// @param _pos The position to find the trace ancestor claim of.
            /// @param _start The index to start searching from.
            /// @param _global Whether or not to search the entire dag or just within an execution trace subgame. If set to
            ///                `true`, and `_pos` is at or above the split depth, this function will revert.
            /// @return ancestor_ The ancestor claim that commits to the same trace index as `_pos`.
            function _findTraceAncestor(
                Position _pos,
                uint256 _start,
                bool _global
            )
                internal
                view
                returns (ClaimData storage ancestor_)
            {
                // Grab the trace ancestor's expected position.
                Position traceAncestorPos = _global ? _pos.traceAncestor() : _pos.traceAncestorBounded(SPLIT_DEPTH);
                // Walk up the DAG to find a claim that commits to the same trace index as `_pos`. It is
                // guaranteed that such a claim exists.
                ancestor_ = claimData[_start];
                while (ancestor_.position.raw() != traceAncestorPos.raw()) {
                    ancestor_ = claimData[ancestor_.parentIndex];
                }
            }
            /// @notice Finds the starting and disputed output root for a given `ClaimData` within the DAG. This
            ///         `ClaimData` must be below the `SPLIT_DEPTH`.
            /// @param _start The index within `claimData` of the claim to start searching from.
            /// @return startingClaim_ The starting output root claim.
            /// @return startingPos_ The starting output root position.
            /// @return disputedClaim_ The disputed output root claim.
            /// @return disputedPos_ The disputed output root position.
            function _findStartingAndDisputedOutputs(uint256 _start)
                internal
                view
                returns (Claim startingClaim_, Position startingPos_, Claim disputedClaim_, Position disputedPos_)
            {
                // Fatch the starting claim.
                uint256 claimIdx = _start;
                ClaimData storage claim = claimData[claimIdx];
                // If the starting claim's depth is less than or equal to the split depth, we revert as this is UB.
                if (claim.position.depth() <= SPLIT_DEPTH) revert ClaimAboveSplit();
                // We want to:
                // 1. Find the first claim at the split depth.
                // 2. Determine whether it was the starting or disputed output for the exec game.
                // 3. Find the complimentary claim depending on the info from #2 (pre or post).
                // Walk up the DAG until the ancestor's depth is equal to the split depth.
                uint256 currentDepth;
                ClaimData storage execRootClaim = claim;
                while ((currentDepth = claim.position.depth()) > SPLIT_DEPTH) {
                    uint256 parentIndex = claim.parentIndex;
                    // If we're currently at the split depth + 1, we're at the root of the execution sub-game.
                    // We need to keep track of the root claim here to determine whether the execution sub-game was
                    // started with an attack or defense against the output leaf claim.
                    if (currentDepth == SPLIT_DEPTH + 1) execRootClaim = claim;
                    claim = claimData[parentIndex];
                    claimIdx = parentIndex;
                }
                // Determine whether the start of the execution sub-game was an attack or defense to the output root
                // above. This is important because it determines which claim is the starting output root and which
                // is the disputed output root.
                (Position execRootPos, Position outputPos) = (execRootClaim.position, claim.position);
                bool wasAttack = execRootPos.parent().raw() == outputPos.raw();
                // Determine the starting and disputed output root indices.
                // 1. If it was an attack, the disputed output root is `claim`, and the starting output root is
                //    elsewhere in the DAG (it must commit to the block # index at depth of `outputPos - 1`).
                // 2. If it was a defense, the starting output root is `claim`, and the disputed output root is
                //    elsewhere in the DAG (it must commit to the block # index at depth of `outputPos + 1`).
                if (wasAttack) {
                    // If this is an attack on the first output root (the block directly after the starting
                    // block number), the starting claim nor position exists in the tree. We leave these as
                    // 0, which can be easily identified due to 0 being an invalid Gindex.
                    if (outputPos.indexAtDepth() > 0) {
                        ClaimData storage starting = _findTraceAncestor(Position.wrap(outputPos.raw() - 1), claimIdx, true);
                        (startingClaim_, startingPos_) = (starting.claim, starting.position);
                    } else {
                        startingClaim_ = Claim.wrap(startingOutputRoot.root.raw());
                    }
                    (disputedClaim_, disputedPos_) = (claim.claim, claim.position);
                } else {
                    ClaimData storage disputed = _findTraceAncestor(Position.wrap(outputPos.raw() + 1), claimIdx, true);
                    (startingClaim_, startingPos_) = (claim.claim, claim.position);
                    (disputedClaim_, disputedPos_) = (disputed.claim, disputed.position);
                }
            }
            /// @notice Finds the local context hash for a given claim index that is present in an execution trace subgame.
            /// @param _claimIndex The index of the claim to find the local context hash for.
            /// @return uuid_ The local context hash.
            function _findLocalContext(uint256 _claimIndex) internal view returns (Hash uuid_) {
                (Claim starting, Position startingPos, Claim disputed, Position disputedPos) =
                    _findStartingAndDisputedOutputs(_claimIndex);
                uuid_ = _computeLocalContext(starting, startingPos, disputed, disputedPos);
            }
            /// @notice Computes the local context hash for a set of starting/disputed claim values and positions.
            /// @param _starting The starting claim.
            /// @param _startingPos The starting claim's position.
            /// @param _disputed The disputed claim.
            /// @param _disputedPos The disputed claim's position.
            /// @return uuid_ The local context hash.
            function _computeLocalContext(
                Claim _starting,
                Position _startingPos,
                Claim _disputed,
                Position _disputedPos
            )
                internal
                pure
                returns (Hash uuid_)
            {
                // A position of 0 indicates that the starting claim is the absolute prestate. In this special case,
                // we do not include the starting claim within the local context hash.
                uuid_ = _startingPos.raw() == 0
                    ? Hash.wrap(keccak256(abi.encode(_disputed, _disputedPos)))
                    : Hash.wrap(keccak256(abi.encode(_starting, _startingPos, _disputed, _disputedPos)));
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibUDT.sol";
        /// @notice The current status of the dispute game.
        enum GameStatus {
            // The game is currently in progress, and has not been resolved.
            IN_PROGRESS,
            // The game has concluded, and the `rootClaim` was challenged successfully.
            CHALLENGER_WINS,
            // The game has concluded, and the `rootClaim` could not be contested.
            DEFENDER_WINS
        }
        /// @notice Represents an L2 output root and the L2 block number at which it was generated.
        /// @custom:field root The output root.
        /// @custom:field l2BlockNumber The L2 block number at which the output root was generated.
        struct OutputRoot {
            Hash root;
            uint256 l2BlockNumber;
        }
        /// @title GameTypes
        /// @notice A library that defines the IDs of games that can be played.
        library GameTypes {
            /// @dev A dispute game type the uses the cannon vm.
            GameType internal constant CANNON = GameType.wrap(0);
            /// @dev A permissioned dispute game type the uses the cannon vm.
            GameType internal constant PERMISSIONED_CANNON = GameType.wrap(1);
            /// @notice A dispute game type the uses the asterisc VM
            GameType internal constant ASTERISC = GameType.wrap(2);
            /// @notice A dispute game type with short game duration for testing withdrawals.
            ///         Not intended for production use.
            GameType internal constant FAST = GameType.wrap(254);
            /// @notice A dispute game type that uses an alphabet vm.
            ///         Not intended for production use.
            GameType internal constant ALPHABET = GameType.wrap(255);
        }
        /// @title VMStatuses
        /// @notice Named type aliases for the various valid VM status bytes.
        library VMStatuses {
            /// @notice The VM has executed successfully and the outcome is valid.
            VMStatus internal constant VALID = VMStatus.wrap(0);
            /// @notice The VM has executed successfully and the outcome is invalid.
            VMStatus internal constant INVALID = VMStatus.wrap(1);
            /// @notice The VM has paniced.
            VMStatus internal constant PANIC = VMStatus.wrap(2);
            /// @notice The VM execution is still in progress.
            VMStatus internal constant UNFINISHED = VMStatus.wrap(3);
        }
        /// @title LocalPreimageKey
        /// @notice Named type aliases for local `PreimageOracle` key identifiers.
        library LocalPreimageKey {
            /// @notice The identifier for the L1 head hash.
            uint256 internal constant L1_HEAD_HASH = 0x01;
            /// @notice The identifier for the starting output root.
            uint256 internal constant STARTING_OUTPUT_ROOT = 0x02;
            /// @notice The identifier for the disputed output root.
            uint256 internal constant DISPUTED_OUTPUT_ROOT = 0x03;
            /// @notice The identifier for the disputed L2 block number.
            uint256 internal constant DISPUTED_L2_BLOCK_NUMBER = 0x04;
            /// @notice The identifier for the chain ID.
            uint256 internal constant CHAIN_ID = 0x05;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibUDT.sol";
        ////////////////////////////////////////////////////////////////
        //                `DisputeGameFactory` Errors                 //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when a dispute game is attempted to be created with an unsupported game type.
        /// @param gameType The unsupported game type.
        error NoImplementation(GameType gameType);
        /// @notice Thrown when a dispute game that already exists is attempted to be created.
        /// @param uuid The UUID of the dispute game that already exists.
        error GameAlreadyExists(Hash uuid);
        /// @notice Thrown when the root claim has an unexpected VM status.
        ///         Some games can only start with a root-claim with a specific status.
        /// @param rootClaim is the claim that was unexpected.
        error UnexpectedRootClaim(Claim rootClaim);
        ////////////////////////////////////////////////////////////////
        //                 `FaultDisputeGame` Errors                  //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when a dispute game has already been initialized.
        error AlreadyInitialized();
        /// @notice Thrown when a supplied bond is not equal to the required bond amount to cover the cost of the interaction.
        error IncorrectBondAmount();
        /// @notice Thrown when a credit claim is attempted for a value of 0.
        error NoCreditToClaim();
        /// @notice Thrown when the transfer of credit to a recipient account reverts.
        error BondTransferFailed();
        /// @notice Thrown when the `extraData` passed to the CWIA proxy is of improper length, or contains invalid information.
        error BadExtraData();
        /// @notice Thrown when a defense against the root claim is attempted.
        error CannotDefendRootClaim();
        /// @notice Thrown when a claim is attempting to be made that already exists.
        error ClaimAlreadyExists();
        /// @notice Thrown when a disputed claim does not match its index in the game.
        error InvalidDisputedClaimIndex();
        /// @notice Thrown when an action that requires the game to be `IN_PROGRESS` is invoked when
        ///         the game is not in progress.
        error GameNotInProgress();
        /// @notice Thrown when a move is attempted to be made after the clock has timed out.
        error ClockTimeExceeded();
        /// @notice Thrown when the game is attempted to be resolved too early.
        error ClockNotExpired();
        /// @notice Thrown when a move is attempted to be made at or greater than the max depth of the game.
        error GameDepthExceeded();
        /// @notice Thrown when a step is attempted above the maximum game depth.
        error InvalidParent();
        /// @notice Thrown when an invalid prestate is supplied to `step`.
        error InvalidPrestate();
        /// @notice Thrown when a step is made that computes the expected post state correctly.
        error ValidStep();
        /// @notice Thrown when a game is attempted to be initialized with an L1 head that does
        ///         not contain the disputed output root.
        error L1HeadTooOld();
        /// @notice Thrown when an invalid local identifier is passed to the `addLocalData` function.
        error InvalidLocalIdent();
        /// @notice Thrown when resolving claims out of order.
        error OutOfOrderResolution();
        /// @notice Thrown when resolving a claim that has already been resolved.
        error ClaimAlreadyResolved();
        /// @notice Thrown when a parent output root is attempted to be found on a claim that is in
        ///         the output root portion of the tree.
        error ClaimAboveSplit();
        /// @notice Thrown on deployment if the split depth is greater than or equal to the max
        ///         depth of the game.
        error InvalidSplitDepth();
        /// @notice Thrown on deployment if the max clock duration is less than or equal to the clock extension.
        error InvalidClockExtension();
        /// @notice Thrown on deployment if the PreimageOracle challenge period is too high.
        error InvalidChallengePeriod();
        /// @notice Thrown on deployment if the max depth is greater than `LibPosition.`
        error MaxDepthTooLarge();
        /// @notice Thrown when trying to step against a claim for a second time, after it has already been countered with
        ///         an instruction step.
        error DuplicateStep();
        /// @notice Thrown when an anchor root is not found for a given game type.
        error AnchorRootNotFound();
        /// @notice Thrown when an output root proof is invalid.
        error InvalidOutputRootProof();
        /// @notice Thrown when header RLP is invalid with respect to the block hash in an output root proof.
        error InvalidHeaderRLP();
        /// @notice Thrown when there is a match between the block number in the output root proof and the block number
        ///         claimed in the dispute game.
        error BlockNumberMatches();
        /// @notice Thrown when the L2 block number claim has already been challenged.
        error L2BlockNumberChallenged();
        ////////////////////////////////////////////////////////////////
        //              `PermissionedDisputeGame` Errors              //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when an unauthorized address attempts to interact with the game.
        error BadAuth();
        ////////////////////////////////////////////////////////////////
        //              `AnchorStateRegistry` Errors                  //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when attempting to set an anchor state using an unregistered game.
        error UnregisteredGame();
        /// @notice Thrown when attempting to set an anchor state using an invalid game result.
        error InvalidGameStatus();
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { ISuperchainConfig } from "src/L1/interfaces/ISuperchainConfig.sol";
        interface IDelayedWETH {
            struct WithdrawalRequest {
                uint256 amount;
                uint256 timestamp;
            }
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            event Initialized(uint8 version);
            event Unwrap(address indexed src, uint256 wad);
            fallback() external payable;
            receive() external payable;
            function config() external view returns (ISuperchainConfig);
            function delay() external view returns (uint256);
            function hold(address _guy, uint256 _wad) external;
            function initialize(address _owner, ISuperchainConfig _config) external;
            function owner() external view returns (address);
            function recover(uint256 _wad) external;
            function transferOwnership(address newOwner) external; // nosemgrep
            function renounceOwnership() external;
            function unlock(address _guy, uint256 _wad) external;
            function withdraw(address _guy, uint256 _wad) external;
            function withdrawals(address, address) external view returns (uint256 amount, uint256 timestamp);
            function version() external view returns (string memory);
            function withdraw(uint256 _wad) external;
            event Approval(address indexed src, address indexed guy, uint256 wad);
            event Transfer(address indexed src, address indexed dst, uint256 wad);
            event Deposit(address indexed dst, uint256 wad);
            event Withdrawal(address indexed src, uint256 wad);
            function name() external view returns (string memory);
            function symbol() external view returns (string memory);
            function decimals() external view returns (uint8);
            function balanceOf(address src) external view returns (uint256);
            function allowance(address owner, address spender) external view returns (uint256);
            function deposit() external payable;
            function totalSupply() external view returns (uint256);
            function approve(address guy, uint256 wad) external returns (bool);
            function transfer(address dst, uint256 wad) external returns (bool);
            function transferFrom(address src, address dst, uint256 wad) external returns (bool);
            function __constructor__(uint256 _delay) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IFaultDisputeGame } from "src/dispute/interfaces/IFaultDisputeGame.sol";
        import { IDisputeGameFactory } from "src/dispute/interfaces/IDisputeGameFactory.sol";
        import { ISuperchainConfig } from "src/L1/interfaces/ISuperchainConfig.sol";
        import "src/dispute/lib/Types.sol";
        interface IAnchorStateRegistry {
            struct StartingAnchorRoot {
                GameType gameType;
                OutputRoot outputRoot;
            }
            error InvalidGameStatus();
            error Unauthorized();
            error UnregisteredGame();
            event Initialized(uint8 version);
            function anchors(GameType) external view returns (Hash root, uint256 l2BlockNumber); // nosemgrep
            function disputeGameFactory() external view returns (IDisputeGameFactory);
            function initialize(
                StartingAnchorRoot[] memory _startingAnchorRoots,
                ISuperchainConfig _superchainConfig
            )
                external;
            function setAnchorState(IFaultDisputeGame _game) external;
            function superchainConfig() external view returns (ISuperchainConfig);
            function tryUpdateAnchorState() external;
            function version() external view returns (string memory);
            function __constructor__(IDisputeGameFactory _disputeGameFactory) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IPreimageOracle } from "src/cannon/interfaces/IPreimageOracle.sol";
        /// @title IBigStepper
        /// @notice Describes a state machine that can perform a single instruction step, provided a prestate and an optional
        ///         proof.
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⠶⢅⠒⢄⢔⣶⡦⣤⡤⠄⣀⠀⠀⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⡏⠀⠀⠈⠢⣙⢯⣄⠀⢨⠯⡺⡘⢄⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣶⡆⠀⠀⠀⠀⠈⠓⠬⡒⠡⣀⢙⡜⡀⠓⠄⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡷⠿⣧⣀⡀⠀⠀⠀⠀⠀⠀⠉⠣⣞⠩⠥⠀⠼⢄⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀⠉⢹⣶⠒⠒⠂⠈⠉⠁⠘⡆⠀⣿⣿⠫⡄⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⢶⣤⣀⡀⠀⠀⢸⡿⠀⠀⠀⠀⠀⢀⠞⠀⠀⢡⢨⢀⡄⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡒⣿⢿⡤⠝⡣⠉⠁⠚⠛⠀⠤⠤⣄⡰⠁⠀⠀⠀⠉⠙⢸⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⢯⡌⡿⡇⠘⡷⠀⠁⠀⠀⢀⣰⠢⠲⠛⣈⣸⠦⠤⠶⠴⢬⣐⣊⡂⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⡪⡗⢫⠞⠀⠆⣀⠻⠤⠴⠐⠚⣉⢀⠦⠂⠋⠁⠀⠁⠀⠀⠀⠀⢋⠉⠇⠀
        /// ⠀⠀⠀⠀⣀⡤⠐⠒⠘⡹⠉⢸⠇⠸⠀⠀⠀⠀⣀⣤⠴⠚⠉⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠀⣾⠀
        /// ⠀⠀⠀⡰⠀⠉⠉⠀⠁⠀⠀⠈⢇⠈⠒⠒⠘⠈⢀⢡⡂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠀⢸⡄
        /// ⠀⠀⠸⣿⣆⠤⢀⡀⠀⠀⠀⠀⢘⡌⠀⠀⣀⣀⣀⡈⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢸⡇
        /// ⠀⠀⢸⣀⠀⠉⠒⠐⠛⠋⠭⠭⠍⠉⠛⠒⠒⠒⠀⠒⠚⠛⠛⠛⠩⠭⠭⠭⠭⠤⠤⠤⠤⠤⠭⠭⠉⠓⡆
        /// ⠀⠀⠘⠿⣷⣶⣤⣤⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣤⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇
        /// ⠀⠀⠀⠀⠀⠉⠙⠛⠛⠻⠿⢿⣿⣿⣷⣶⣶⣶⣤⣤⣀⣁⣛⣃⣒⠿⠿⠿⠤⠠⠄⠤⠤⢤⣛⣓⣂⣻⡇
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠙⠛⠻⠿⠿⠿⢿⣿⣿⣿⣷⣶⣶⣾⣿⣿⣿⣿⠿⠟⠁
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠈⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀
        interface IBigStepper {
            /// @notice Performs the state transition from a given prestate and returns the hash of the post state witness.
            /// @param _stateData The raw opaque prestate data.
            /// @param _proof Opaque proof data, can be used to prove things about the prestate in relation to the state of the
            ///               interface's implementation.
            /// @param _localContext The local key context for the preimage oracle. Optional, can be set as a constant if the
            ///                      implementation only requires one set of local keys.
            /// @return postState_ The hash of the post state witness after the state transition.
            function step(
                bytes calldata _stateData,
                bytes calldata _proof,
                bytes32 _localContext
            )
                external
                returns (bytes32 postState_);
            /// @notice Returns the preimage oracle used by the state machine.
            function oracle() external view returns (IPreimageOracle oracle_);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Standard math utilities missing in the Solidity language.
         */
        library Math {
            enum Rounding {
                Down, // Toward negative infinity
                Up, // Toward infinity
                Zero // Toward zero
            }
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a >= b ? a : b;
            }
            /**
             * @dev Returns the smallest of two numbers.
             */
            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                return a < b ? a : b;
            }
            /**
             * @dev Returns the average of two numbers. The result is rounded towards
             * zero.
             */
            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b) / 2 can overflow.
                return (a & b) + (a ^ b) / 2;
            }
            /**
             * @dev Returns the ceiling of the division of two numbers.
             *
             * This differs from standard division with `/` in that it rounds up instead
             * of rounding down.
             */
            function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b - 1) / b can overflow on addition, so we distribute.
                return a == 0 ? 0 : (a - 1) / b + 1;
            }
            /**
             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
             * with further edits by Uniswap Labs also under MIT license.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator
            ) internal pure returns (uint256 result) {
                unchecked {
                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                    // variables such that product = prod1 * 2^256 + prod0.
                    uint256 prod0; // Least significant 256 bits of the product
                    uint256 prod1; // Most significant 256 bits of the product
                    assembly {
                        let mm := mulmod(x, y, not(0))
                        prod0 := mul(x, y)
                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                    }
                    // Handle non-overflow cases, 256 by 256 division.
                    if (prod1 == 0) {
                        return prod0 / denominator;
                    }
                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                    require(denominator > prod1);
                    ///////////////////////////////////////////////
                    // 512 by 256 division.
                    ///////////////////////////////////////////////
                    // Make division exact by subtracting the remainder from [prod1 prod0].
                    uint256 remainder;
                    assembly {
                        // Compute remainder using mulmod.
                        remainder := mulmod(x, y, denominator)
                        // Subtract 256 bit number from 512 bit number.
                        prod1 := sub(prod1, gt(remainder, prod0))
                        prod0 := sub(prod0, remainder)
                    }
                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                    // See https://cs.stackexchange.com/q/138556/92363.
                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                    uint256 twos = denominator & (~denominator + 1);
                    assembly {
                        // Divide denominator by twos.
                        denominator := div(denominator, twos)
                        // Divide [prod1 prod0] by twos.
                        prod0 := div(prod0, twos)
                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                        twos := add(div(sub(0, twos), twos), 1)
                    }
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * twos;
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                    // in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                    return result;
                }
            }
            /**
             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator,
                Rounding rounding
            ) internal pure returns (uint256) {
                uint256 result = mulDiv(x, y, denominator);
                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                    result += 1;
                }
                return result;
            }
            /**
             * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
             *
             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
             */
            function sqrt(uint256 a) internal pure returns (uint256) {
                if (a == 0) {
                    return 0;
                }
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                // `msb(a) <= a < 2*msb(a)`.
                // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
                // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
                // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
                // good first aproximation of `sqrt(a)` with at least 1 correct bit.
                uint256 result = 1;
                uint256 x = a;
                if (x >> 128 > 0) {
                    x >>= 128;
                    result <<= 64;
                }
                if (x >> 64 > 0) {
                    x >>= 64;
                    result <<= 32;
                }
                if (x >> 32 > 0) {
                    x >>= 32;
                    result <<= 16;
                }
                if (x >> 16 > 0) {
                    x >>= 16;
                    result <<= 8;
                }
                if (x >> 8 > 0) {
                    x >>= 8;
                    result <<= 4;
                }
                if (x >> 4 > 0) {
                    x >>= 4;
                    result <<= 2;
                }
                if (x >> 2 > 0) {
                    result <<= 1;
                }
                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                // into the expected uint128 result.
                unchecked {
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    return min(result, a / result);
                }
            }
            /**
             * @notice Calculates sqrt(a), following the selected rounding direction.
             */
            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                uint256 result = sqrt(a);
                if (rounding == Rounding.Up && result * result < a) {
                    result += 1;
                }
                return result;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        /// @notice Arithmetic library with operations for fixed-point numbers.
        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
        library FixedPointMathLib {
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                       CUSTOM ERRORS                        */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
            error ExpOverflow();
            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
            error FactorialOverflow();
            /// @dev The operation failed, due to an overflow.
            error RPowOverflow();
            /// @dev The mantissa is too big to fit.
            error MantissaOverflow();
            /// @dev The operation failed, due to an multiplication overflow.
            error MulWadFailed();
            /// @dev The operation failed, due to an multiplication overflow.
            error SMulWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error DivWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error SDivWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error MulDivFailed();
            /// @dev The division failed, as the denominator is zero.
            error DivFailed();
            /// @dev The full precision multiply-divide operation failed, either due
            /// to the result being larger than 256 bits, or a division by a zero.
            error FullMulDivFailed();
            /// @dev The output is undefined, as the input is less-than-or-equal to zero.
            error LnWadUndefined();
            /// @dev The input outside the acceptable domain.
            error OutOfDomain();
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                         CONSTANTS                          */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev The scalar of ETH and most ERC20s.
            uint256 internal constant WAD = 1e18;
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*              SIMPLIFIED FIXED POINT OPERATIONS             */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Equivalent to `(x * y) / WAD` rounded down.
            function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                    if mul(y, gt(x, div(not(0), y))) {
                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down.
            function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(x, y)
                    // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
                    if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                        mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := sdiv(z, WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
            function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
            function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded up.
            function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                    if mul(y, gt(x, div(not(0), y))) {
                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
            function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down.
            function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down.
            function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(x, WAD)
                    // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
                    if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                        mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := sdiv(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
            function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
            function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded up.
            function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
            function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                }
            }
            /// @dev Equivalent to `x` to the power of `y`.
            /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
            function powWad(int256 x, int256 y) internal pure returns (int256) {
                // Using `ln(x)` means `x` must be greater than 0.
                return expWad((lnWad(x) * y) / int256(WAD));
            }
            /// @dev Returns `exp(x)`, denominated in `WAD`.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/exp-ln
            function expWad(int256 x) internal pure returns (int256 r) {
                unchecked {
                    // When the result is less than 0.5 we return zero.
                    // This happens when `x <= floor(log(0.5e18) * 1e18) ≈ -42e18`.
                    if (x <= -41446531673892822313) return r;
                    /// @solidity memory-safe-assembly
                    assembly {
                        // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                        // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                        if iszero(slt(x, 135305999368893231589)) {
                            mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                            revert(0x1c, 0x04)
                        }
                    }
                    // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
                    // for more intermediate precision and a binary basis. This base conversion
                    // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                    x = (x << 78) / 5 ** 18;
                    // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                    // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                    // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                    int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
                    x = x - k * 54916777467707473351141471128;
                    // `k` is in the range `[-61, 195]`.
                    // Evaluate using a (6, 7)-term rational approximation.
                    // `p` is made monic, we'll multiply by a scale factor later.
                    int256 y = x + 1346386616545796478920950773328;
                    y = ((y * x) >> 96) + 57155421227552351082224309758442;
                    int256 p = y + x - 94201549194550492254356042504812;
                    p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                    p = p * x + (4385272521454847904659076985693276 << 96);
                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                    int256 q = x - 2855989394907223263936484059900;
                    q = ((q * x) >> 96) + 50020603652535783019961831881945;
                    q = ((q * x) >> 96) - 533845033583426703283633433725380;
                    q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                    q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                    q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                    /// @solidity memory-safe-assembly
                    assembly {
                        // Div in assembly because solidity adds a zero check despite the unchecked.
                        // The q polynomial won't have zeros in the domain as all its roots are complex.
                        // No scaling is necessary because p is already `2**96` too large.
                        r := sdiv(p, q)
                    }
                    // r should be in the range `(0.09, 0.25) * 2**96`.
                    // We now need to multiply r by:
                    // - The scale factor `s ≈ 6.031367120`.
                    // - The `2**k` factor from the range reduction.
                    // - The `1e18 / 2**96` factor for base conversion.
                    // We do this all at once, with an intermediate result in `2**213`
                    // basis, so the final right shift is always by a positive amount.
                    r = int256(
                        (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
                    );
                }
            }
            /// @dev Returns `ln(x)`, denominated in `WAD`.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/exp-ln
            function lnWad(int256 x) internal pure returns (int256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
                    // We do this by multiplying by `2**96 / 10**18`. But since
                    // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
                    // and add `ln(2**96 / 10**18)` at the end.
                    // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    // We place the check here for more optimal stack operations.
                    if iszero(sgt(x, 0)) {
                        mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                        revert(0x1c, 0x04)
                    }
                    // forgefmt: disable-next-item
                    r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                        0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
                    // Reduce range of x to (1, 2) * 2**96
                    // ln(2^k * x) = k * ln(2) + ln(x)
                    x := shr(159, shl(r, x))
                    // Evaluate using a (8, 8)-term rational approximation.
                    // `p` is made monic, we will multiply by a scale factor later.
                    // forgefmt: disable-next-item
                    let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                        sar(96, mul(add(43456485725739037958740375743393,
                        sar(96, mul(add(24828157081833163892658089445524,
                        sar(96, mul(add(3273285459638523848632254066296,
                            x), x))), x))), x)), 11111509109440967052023855526967)
                    p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
                    p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
                    p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                    // `q` is monic by convention.
                    let q := add(5573035233440673466300451813936, x)
                    q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
                    q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
                    q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
                    q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
                    q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
                    q := add(909429971244387300277376558375, sar(96, mul(x, q)))
                    // `p / q` is in the range `(0, 0.125) * 2**96`.
                    // Finalization, we need to:
                    // - Multiply by the scale factor `s = 5.549…`.
                    // - Add `ln(2**96 / 10**18)`.
                    // - Add `k * ln(2)`.
                    // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
                    // The q polynomial is known not to have zeros in the domain.
                    // No scaling required because p is already `2**96` too large.
                    p := sdiv(p, q)
                    // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
                    p := mul(1677202110996718588342820967067443963516166, p)
                    // Add `ln(2) * k * 5**18 * 2**192`.
                    // forgefmt: disable-next-item
                    p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
                    // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
                    p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
                    // Base conversion: mul `2**18 / 2**192`.
                    r := sar(174, p)
                }
            }
            /// @dev Returns `W_0(x)`, denominated in `WAD`.
            /// See: https://en.wikipedia.org/wiki/Lambert_W_function
            /// a.k.a. Product log function. This is an approximation of the principal branch.
            function lambertW0Wad(int256 x) internal pure returns (int256 w) {
                // forgefmt: disable-next-item
                unchecked {
                    if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
                    int256 wad = int256(WAD);
                    int256 p = x;
                    uint256 c; // Whether we need to avoid catastrophic cancellation.
                    uint256 i = 4; // Number of iterations.
                    if (w <= 0x1ffffffffffff) {
                        if (-0x4000000000000 <= w) {
                            i = 1; // Inputs near zero only take one step to converge.
                        } else if (w <= -0x3ffffffffffffff) {
                            i = 32; // Inputs near `-1/e` take very long to converge.
                        }
                    } else if (w >> 63 == 0) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Inline log2 for more performance, since the range is small.
                            let v := shr(49, w)
                            let l := shl(3, lt(0xff, v))
                            l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                                0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                            w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                            c := gt(l, 60)
                            i := add(2, add(gt(l, 53), c))
                        }
                    } else {
                        int256 ll = lnWad(w = lnWad(w));
                        /// @solidity memory-safe-assembly
                        assembly {
                            // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                            w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                            i := add(3, iszero(shr(68, x)))
                            c := iszero(shr(143, x))
                        }
                        if (c == 0) {
                            do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                                int256 e = expWad(w);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let t := mul(w, div(e, wad))
                                    w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                                }
                                if (p <= w) break;
                                p = w;
                            } while (--i != 0);
                            /// @solidity memory-safe-assembly
                            assembly {
                                w := sub(w, sgt(w, 2))
                            }
                            return w;
                        }
                    }
                    do { // Otherwise, use Halley's for faster convergence.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := add(w, wad)
                            let s := sub(mul(w, e), mul(x, wad))
                            w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != c);
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
                    // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
                    if (c != 0) {
                        int256 t = w | 1;
                        /// @solidity memory-safe-assembly
                        assembly {
                            x := sdiv(mul(x, wad), t)
                        }
                        x = (t * (wad + lnWad(x)));
                        /// @solidity memory-safe-assembly
                        assembly {
                            w := sdiv(x, add(wad, t))
                        }
                    }
                }
            }
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                  GENERAL NUMBER UTILITIES                  */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Calculates `floor(a * b / d)` with full precision.
            /// Throws if result overflows a uint256 or when `d` is zero.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
            function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                /// @solidity memory-safe-assembly
                assembly {
                    for {} 1 {} {
                        // 512-bit multiply `[p1 p0] = x * y`.
                        // Compute the product mod `2**256` and mod `2**256 - 1`
                        // then use the Chinese Remainder Theorem to reconstruct
                        // the 512 bit result. The result is stored in two 256
                        // variables such that `product = p1 * 2**256 + p0`.
                        // Least significant 256 bits of the product.
                        result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                        let mm := mulmod(x, y, not(0))
                        // Most significant 256 bits of the product.
                        let p1 := sub(mm, add(result, lt(mm, result)))
                        // Handle non-overflow cases, 256 by 256 division.
                        if iszero(p1) {
                            if iszero(d) {
                                mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                revert(0x1c, 0x04)
                            }
                            result := div(result, d)
                            break
                        }
                        // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                        if iszero(gt(d, p1)) {
                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                            revert(0x1c, 0x04)
                        }
                        /*------------------- 512 by 256 division --------------------*/
                        // Make division exact by subtracting the remainder from `[p1 p0]`.
                        // Compute remainder using mulmod.
                        let r := mulmod(x, y, d)
                        // `t` is the least significant bit of `d`.
                        // Always greater or equal to 1.
                        let t := and(d, sub(0, d))
                        // Divide `d` by `t`, which is a power of two.
                        d := div(d, t)
                        // Invert `d mod 2**256`
                        // Now that `d` is an odd number, it has an inverse
                        // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                        // Compute the inverse by starting with a seed that is correct
                        // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                        let inv := xor(2, mul(3, d))
                        // Now use Newton-Raphson iteration to improve the precision.
                        // Thanks to Hensel's lifting lemma, this also works in modular
                        // arithmetic, doubling the correct bits in each step.
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                        result :=
                            mul(
                                // Divide [p1 p0] by the factors of two.
                                // Shift in bits from `p1` into `p0`. For this we need
                                // to flip `t` such that it is `2**256 / t`.
                                or(
                                    mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                                    div(sub(result, r), t)
                                ),
                                // inverse mod 2**256
                                mul(inv, sub(2, mul(d, inv)))
                            )
                        break
                    }
                }
            }
            /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
            /// Throws if result overflows a uint256 or when `d` is zero.
            /// Credit to Uniswap-v3-core under MIT license:
            /// https://github.com/Uniswap/v3-core/blob/contracts/libraries/FullMath.sol
            function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                result = fullMulDiv(x, y, d);
                /// @solidity memory-safe-assembly
                assembly {
                    if mulmod(x, y, d) {
                        result := add(result, 1)
                        if iszero(result) {
                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            /// @dev Returns `floor(x * y / d)`.
            /// Reverts if `x * y` overflows, or `d` is zero.
            function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, y), d)
                }
            }
            /// @dev Returns `ceil(x * y / d)`.
            /// Reverts if `x * y` overflows, or `d` is zero.
            function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
                }
            }
            /// @dev Returns `ceil(x / d)`.
            /// Reverts if `d` is zero.
            function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(d) {
                        mstore(0x00, 0x65244e4e) // `DivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(x, d))), div(x, d))
                }
            }
            /// @dev Returns `max(0, x - y)`.
            function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(gt(x, y), sub(x, y))
                }
            }
            /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
            /// Reverts if the computation overflows.
            function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
                    if x {
                        z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                        let half := shr(1, b) // Divide `b` by 2.
                        // Divide `y` by 2 every iteration.
                        for { y := shr(1, y) } y { y := shr(1, y) } {
                            let xx := mul(x, x) // Store x squared.
                            let xxRound := add(xx, half) // Round to the nearest number.
                            // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                            if or(lt(xxRound, xx), shr(128, x)) {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                            x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                            // If `y` is odd:
                            if and(y, 1) {
                                let zx := mul(z, x) // Compute `z * x`.
                                let zxRound := add(zx, half) // Round to the nearest number.
                                // If `z * x` overflowed or `zx + half` overflowed:
                                if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                                    // Revert if `x` is non-zero.
                                    if iszero(iszero(x)) {
                                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                z := div(zxRound, b) // Return properly scaled `zxRound`.
                            }
                        }
                    }
                }
            }
            /// @dev Returns the square root of `x`.
            function sqrt(uint256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
                    z := 181 // The "correct" value is 1, but this saves a multiplication later.
                    // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                    // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                    // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
                    // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffffff, shr(r, x))))
                    z := shl(shr(1, r), z)
                    // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
                    // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
                    // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
                    // That's not possible if `x < 256` but we can just verify those cases exhaustively.
                    // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
                    // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
                    // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
                    // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
                    // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
                    // with largest error when `s = 1` and when `s = 256` or `1/256`.
                    // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
                    // Then we can estimate `sqrt(y)` using
                    // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
                    // There is no overflow risk here since `y < 2**136` after the first branch above.
                    z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
                    // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    // If `x+1` is a perfect square, the Babylonian method cycles between
                    // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
                    // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                    z := sub(z, lt(div(x, z), z))
                }
            }
            /// @dev Returns the cube root of `x`.
            /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
            /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
            function cbrt(uint256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := sub(z, lt(div(x, mul(z, z)), z))
                }
            }
            /// @dev Returns the square root of `x`, denominated in `WAD`.
            function sqrtWad(uint256 x) internal pure returns (uint256 z) {
                unchecked {
                    z = 10 ** 9;
                    if (x <= type(uint256).max / 10 ** 36 - 1) {
                        x *= 10 ** 18;
                        z = 1;
                    }
                    z *= sqrt(x);
                }
            }
            /// @dev Returns the cube root of `x`, denominated in `WAD`.
            function cbrtWad(uint256 x) internal pure returns (uint256 z) {
                unchecked {
                    z = 10 ** 12;
                    if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                        if (x >= type(uint256).max / 10 ** 36) {
                            x *= 10 ** 18;
                            z = 10 ** 6;
                        } else {
                            x *= 10 ** 36;
                            z = 1;
                        }
                    }
                    z *= cbrt(x);
                }
            }
            /// @dev Returns the factorial of `x`.
            function factorial(uint256 x) internal pure returns (uint256 result) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(lt(x, 58)) {
                        mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
                }
            }
            /// @dev Returns the log2 of `x`.
            /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
            /// Returns 0 if `x` is zero.
            function log2(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    // forgefmt: disable-next-item
                    r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000))
                }
            }
            /// @dev Returns the log2 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log2Up(uint256 x) internal pure returns (uint256 r) {
                r = log2(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(shl(r, 1), x))
                }
            }
            /// @dev Returns the log10 of `x`.
            /// Returns 0 if `x` is zero.
            function log10(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(lt(x, 100000000000000000000000000000000000000)) {
                        x := div(x, 100000000000000000000000000000000000000)
                        r := 38
                    }
                    if iszero(lt(x, 100000000000000000000)) {
                        x := div(x, 100000000000000000000)
                        r := add(r, 20)
                    }
                    if iszero(lt(x, 10000000000)) {
                        x := div(x, 10000000000)
                        r := add(r, 10)
                    }
                    if iszero(lt(x, 100000)) {
                        x := div(x, 100000)
                        r := add(r, 5)
                    }
                    r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
                }
            }
            /// @dev Returns the log10 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log10Up(uint256 x) internal pure returns (uint256 r) {
                r = log10(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(exp(10, r), x))
                }
            }
            /// @dev Returns the log256 of `x`.
            /// Returns 0 if `x` is zero.
            function log256(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(shr(3, r), lt(0xff, shr(r, x)))
                }
            }
            /// @dev Returns the log256 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log256Up(uint256 x) internal pure returns (uint256 r) {
                r = log256(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(shl(shl(3, r), 1), x))
                }
            }
            /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
            /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
            function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
                /// @solidity memory-safe-assembly
                assembly {
                    mantissa := x
                    if mantissa {
                        if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                            mantissa := div(mantissa, 1000000000000000000000000000000000)
                            exponent := 33
                        }
                        if iszero(mod(mantissa, 10000000000000000000)) {
                            mantissa := div(mantissa, 10000000000000000000)
                            exponent := add(exponent, 19)
                        }
                        if iszero(mod(mantissa, 1000000000000)) {
                            mantissa := div(mantissa, 1000000000000)
                            exponent := add(exponent, 12)
                        }
                        if iszero(mod(mantissa, 1000000)) {
                            mantissa := div(mantissa, 1000000)
                            exponent := add(exponent, 6)
                        }
                        if iszero(mod(mantissa, 10000)) {
                            mantissa := div(mantissa, 10000)
                            exponent := add(exponent, 4)
                        }
                        if iszero(mod(mantissa, 100)) {
                            mantissa := div(mantissa, 100)
                            exponent := add(exponent, 2)
                        }
                        if iszero(mod(mantissa, 10)) {
                            mantissa := div(mantissa, 10)
                            exponent := add(exponent, 1)
                        }
                    }
                }
            }
            /// @dev Convenience function for packing `x` into a smaller number using `sci`.
            /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
            /// The `exponent` will be in bits [0..6] (the lower 7 bits).
            /// Use `SafeCastLib` to safely ensure that the `packed` number is small
            /// enough to fit in the desired unsigned integer type:
            /// ```
            ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
            /// ```
            function packSci(uint256 x) internal pure returns (uint256 packed) {
                (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
                /// @solidity memory-safe-assembly
                assembly {
                    if shr(249, x) {
                        mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    packed := or(shl(7, x), packed)
                }
            }
            /// @dev Convenience function for unpacking a packed number from `packSci`.
            function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
                unchecked {
                    unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
                }
            }
            /// @dev Returns the average of `x` and `y`.
            function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = (x & y) + ((x ^ y) >> 1);
                }
            }
            /// @dev Returns the average of `x` and `y`.
            function avg(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = (x >> 1) + (y >> 1) + (((x & 1) + (y & 1)) >> 1);
                }
            }
            /// @dev Returns the absolute value of `x`.
            function abs(int256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
                }
            }
            /// @dev Returns the absolute distance between `x` and `y`.
            function dist(int256 x, int256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
                }
            }
            /// @dev Returns the minimum of `x` and `y`.
            function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), lt(y, x)))
                }
            }
            /// @dev Returns the minimum of `x` and `y`.
            function min(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), slt(y, x)))
                }
            }
            /// @dev Returns the maximum of `x` and `y`.
            function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), gt(y, x)))
                }
            }
            /// @dev Returns the maximum of `x` and `y`.
            function max(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), sgt(y, x)))
                }
            }
            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
            function clamp(uint256 x, uint256 minValue, uint256 maxValue)
                internal
                pure
                returns (uint256 z)
            {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
                    z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
                }
            }
            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
            function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
                    z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
                }
            }
            /// @dev Returns greatest common divisor of `x` and `y`.
            function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    for { z := x } y {} {
                        let t := y
                        y := mod(z, y)
                        z := t
                    }
                }
            }
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                   RAW NUMBER OPERATIONS                    */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Returns `x + y`, without checking for overflow.
            function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x + y;
                }
            }
            /// @dev Returns `x + y`, without checking for overflow.
            function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x + y;
                }
            }
            /// @dev Returns `x - y`, without checking for underflow.
            function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x - y;
                }
            }
            /// @dev Returns `x - y`, without checking for underflow.
            function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x - y;
                }
            }
            /// @dev Returns `x * y`, without checking for overflow.
            function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x * y;
                }
            }
            /// @dev Returns `x * y`, without checking for overflow.
            function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x * y;
                }
            }
            /// @dev Returns `x / y`, returning 0 if `y` is zero.
            function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(x, y)
                }
            }
            /// @dev Returns `x / y`, returning 0 if `y` is zero.
            function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(x, y)
                }
            }
            /// @dev Returns `x % y`, returning 0 if `y` is zero.
            function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mod(x, y)
                }
            }
            /// @dev Returns `x % y`, returning 0 if `y` is zero.
            function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := smod(x, y)
                }
            }
            /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
            function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := addmod(x, y, d)
                }
            }
            /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
            function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mulmod(x, y, d)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        /// @notice Class with helper read functions for clone with immutable args.
        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Clone.sol)
        /// @author Adapted from clones with immutable args by zefram.eth, Saw-mon & Natalie
        /// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args)
        abstract contract Clone {
            /// @dev Reads all of the immutable args.
            function _getArgBytes() internal pure returns (bytes memory arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    let length := sub(calldatasize(), add(2, offset)) // 2 bytes are used for the length.
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), offset, length)
                    let o := add(add(arg, 0x20), length)
                    mstore(o, 0) // Zeroize the slot after the bytes.
                    mstore(0x40, add(o, 0x20)) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type bytes.
            function _getArgBytes(uint256 argOffset, uint256 length)
                internal
                pure
                returns (bytes memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), length)
                    let o := add(add(arg, 0x20), length)
                    mstore(o, 0) // Zeroize the slot after the bytes.
                    mstore(0x40, add(o, 0x20)) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type address.
            function _getArgAddress(uint256 argOffset) internal pure returns (address arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(96, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads a uint256 array stored in the immutable args.
            function _getArgUint256Array(uint256 argOffset, uint256 length)
                internal
                pure
                returns (uint256[] memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), shl(5, length))
                    mstore(0x40, add(add(arg, 0x20), shl(5, length))) // Allocate the memory.
                }
            }
            /// @dev Reads a bytes32 array stored in the immutable args.
            function _getArgBytes32Array(uint256 argOffset, uint256 length)
                internal
                pure
                returns (bytes32[] memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), shl(5, length))
                    mstore(0x40, add(add(arg, 0x20), shl(5, length))) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type bytes32.
            function _getArgBytes32(uint256 argOffset) internal pure returns (bytes32 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := calldataload(add(offset, argOffset))
                }
            }
            /// @dev Reads an immutable arg with type uint256.
            function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := calldataload(add(offset, argOffset))
                }
            }
            /// @dev Reads an immutable arg with type uint248.
            function _getArgUint248(uint256 argOffset) internal pure returns (uint248 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(8, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint240.
            function _getArgUint240(uint256 argOffset) internal pure returns (uint240 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(16, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint232.
            function _getArgUint232(uint256 argOffset) internal pure returns (uint232 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(24, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint224.
            function _getArgUint224(uint256 argOffset) internal pure returns (uint224 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(0x20, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint216.
            function _getArgUint216(uint256 argOffset) internal pure returns (uint216 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(40, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint208.
            function _getArgUint208(uint256 argOffset) internal pure returns (uint208 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(48, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint200.
            function _getArgUint200(uint256 argOffset) internal pure returns (uint200 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(56, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint192.
            function _getArgUint192(uint256 argOffset) internal pure returns (uint192 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(64, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint184.
            function _getArgUint184(uint256 argOffset) internal pure returns (uint184 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(72, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint176.
            function _getArgUint176(uint256 argOffset) internal pure returns (uint176 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(80, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint168.
            function _getArgUint168(uint256 argOffset) internal pure returns (uint168 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(88, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint160.
            function _getArgUint160(uint256 argOffset) internal pure returns (uint160 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(96, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint152.
            function _getArgUint152(uint256 argOffset) internal pure returns (uint152 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(104, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint144.
            function _getArgUint144(uint256 argOffset) internal pure returns (uint144 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(112, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint136.
            function _getArgUint136(uint256 argOffset) internal pure returns (uint136 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(120, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint128.
            function _getArgUint128(uint256 argOffset) internal pure returns (uint128 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(128, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint120.
            function _getArgUint120(uint256 argOffset) internal pure returns (uint120 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(136, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint112.
            function _getArgUint112(uint256 argOffset) internal pure returns (uint112 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(144, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint104.
            function _getArgUint104(uint256 argOffset) internal pure returns (uint104 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(152, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint96.
            function _getArgUint96(uint256 argOffset) internal pure returns (uint96 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(160, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint88.
            function _getArgUint88(uint256 argOffset) internal pure returns (uint88 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(168, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint80.
            function _getArgUint80(uint256 argOffset) internal pure returns (uint80 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(176, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint72.
            function _getArgUint72(uint256 argOffset) internal pure returns (uint72 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(184, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint64.
            function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(192, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint56.
            function _getArgUint56(uint256 argOffset) internal pure returns (uint56 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(200, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint48.
            function _getArgUint48(uint256 argOffset) internal pure returns (uint48 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(208, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint40.
            function _getArgUint40(uint256 argOffset) internal pure returns (uint40 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(216, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint32.
            function _getArgUint32(uint256 argOffset) internal pure returns (uint32 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(224, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint24.
            function _getArgUint24(uint256 argOffset) internal pure returns (uint24 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(232, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint16.
            function _getArgUint16(uint256 argOffset) internal pure returns (uint16 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(240, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint8.
            function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(248, calldataload(add(offset, argOffset)))
                }
            }
            /// @return offset The offset of the packed immutable args in calldata.
            function _getImmutableArgsOffset() internal pure returns (uint256 offset) {
                /// @solidity memory-safe-assembly
                assembly {
                    offset := sub(calldatasize(), shr(240, calldataload(sub(calldatasize(), 2))))
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title Types
        /// @notice Contains various types used throughout the Optimism contract system.
        library Types {
            /// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
            ///         timestamp that the output root is posted. This timestamp is used to verify that the
            ///         finalization period has passed since the output root was submitted.
            /// @custom:field outputRoot    Hash of the L2 output.
            /// @custom:field timestamp     Timestamp of the L1 block that the output root was submitted in.
            /// @custom:field l2BlockNumber L2 block number that the output corresponds to.
            struct OutputProposal {
                bytes32 outputRoot;
                uint128 timestamp;
                uint128 l2BlockNumber;
            }
            /// @notice Struct representing the elements that are hashed together to generate an output root
            ///         which itself represents a snapshot of the L2 state.
            /// @custom:field version                  Version of the output root.
            /// @custom:field stateRoot                Root of the state trie at the block of this output.
            /// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
            /// @custom:field latestBlockhash          Hash of the block this output was generated from.
            struct OutputRootProof {
                bytes32 version;
                bytes32 stateRoot;
                bytes32 messagePasserStorageRoot;
                bytes32 latestBlockhash;
            }
            /// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
            ///         user (as opposed to a system deposit transaction generated by the system).
            /// @custom:field from        Address of the sender of the transaction.
            /// @custom:field to          Address of the recipient of the transaction.
            /// @custom:field isCreation  True if the transaction is a contract creation.
            /// @custom:field value       Value to send to the recipient.
            /// @custom:field mint        Amount of ETH to mint.
            /// @custom:field gasLimit    Gas limit of the transaction.
            /// @custom:field data        Data of the transaction.
            /// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
            /// @custom:field logIndex    Index of the log in the block the transaction was submitted in.
            struct UserDepositTransaction {
                address from;
                address to;
                bool isCreation;
                uint256 value;
                uint256 mint;
                uint64 gasLimit;
                bytes data;
                bytes32 l1BlockHash;
                uint256 logIndex;
            }
            /// @notice Struct representing a withdrawal transaction.
            /// @custom:field nonce    Nonce of the withdrawal transaction
            /// @custom:field sender   Address of the sender of the transaction.
            /// @custom:field target   Address of the recipient of the transaction.
            /// @custom:field value    Value to send to the recipient.
            /// @custom:field gasLimit Gas limit of the transaction.
            /// @custom:field data     Data of the transaction.
            struct WithdrawalTransaction {
                uint256 nonce;
                address sender;
                address target;
                uint256 value;
                uint256 gasLimit;
                bytes data;
            }
            /// @notice Enum representing where the FeeVault withdraws funds to.
            /// @custom:value L1 FeeVault withdraws funds to L1.
            /// @custom:value L2 FeeVault withdraws funds to L2.
            enum WithdrawalNetwork {
                L1,
                L2
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { Types } from "src/libraries/Types.sol";
        import { Encoding } from "src/libraries/Encoding.sol";
        /// @title Hashing
        /// @notice Hashing handles Optimism's various different hashing schemes.
        library Hashing {
            /// @notice Computes the hash of the RLP encoded L2 transaction that would be generated when a
            ///         given deposit is sent to the L2 system. Useful for searching for a deposit in the L2
            ///         system.
            /// @param _tx User deposit transaction to hash.
            /// @return Hash of the RLP encoded L2 deposit transaction.
            function hashDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes32) {
                return keccak256(Encoding.encodeDepositTransaction(_tx));
            }
            /// @notice Computes the deposit transaction's "source hash", a value that guarantees the hash
            ///         of the L2 transaction that corresponds to a deposit is unique and is
            ///         deterministically generated from L1 transaction data.
            /// @param _l1BlockHash Hash of the L1 block where the deposit was included.
            /// @param _logIndex    The index of the log that created the deposit transaction.
            /// @return Hash of the deposit transaction's "source hash".
            function hashDepositSource(bytes32 _l1BlockHash, uint256 _logIndex) internal pure returns (bytes32) {
                bytes32 depositId = keccak256(abi.encode(_l1BlockHash, _logIndex));
                return keccak256(abi.encode(bytes32(0), depositId));
            }
            /// @notice Hashes the cross domain message based on the version that is encoded into the
            ///         message nonce.
            /// @param _nonce    Message nonce with version encoded into the first two bytes.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessage(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes32)
            {
                (, uint16 version) = Encoding.decodeVersionedNonce(_nonce);
                if (version == 0) {
                    return hashCrossDomainMessageV0(_target, _sender, _data, _nonce);
                } else if (version == 1) {
                    return hashCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);
                } else {
                    revert("Hashing: unknown cross domain message version");
                }
            }
            /// @notice Hashes a cross domain message based on the V0 (legacy) encoding.
            /// @param _target Address of the target of the message.
            /// @param _sender Address of the sender of the message.
            /// @param _data   Data to send with the message.
            /// @param _nonce  Message nonce.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessageV0(
                address _target,
                address _sender,
                bytes memory _data,
                uint256 _nonce
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(Encoding.encodeCrossDomainMessageV0(_target, _sender, _data, _nonce));
            }
            /// @notice Hashes a cross domain message based on the V1 (current) encoding.
            /// @param _nonce    Message nonce.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessageV1(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(Encoding.encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data));
            }
            /// @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract
            /// @param _tx Withdrawal transaction to hash.
            /// @return Hashed withdrawal transaction.
            function hashWithdrawal(Types.WithdrawalTransaction memory _tx) internal pure returns (bytes32) {
                return keccak256(abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data));
            }
            /// @notice Hashes the various elements of an output root proof into an output root hash which
            ///         can be used to check if the proof is valid.
            /// @param _outputRootProof Output root proof which should hash to an output root.
            /// @return Hashed output root proof.
            function hashOutputRootProof(Types.OutputRootProof memory _outputRootProof) internal pure returns (bytes32) {
                return keccak256(
                    abi.encode(
                        _outputRootProof.version,
                        _outputRootProof.stateRoot,
                        _outputRootProof.messagePasserStorageRoot,
                        _outputRootProof.latestBlockhash
                    )
                );
            }
            /// @notice Generates a unique hash for cross l2 messages. This hash is used to identify
            ///         the message and ensure it is not relayed more than once.
            /// @param _destination Chain ID of the destination chain.
            /// @param _source Chain ID of the source chain.
            /// @param _nonce Unique nonce associated with the message to prevent replay attacks.
            /// @param _sender Address of the user who originally sent the message.
            /// @param _target Address of the contract or wallet that the message is targeting on the destination chain.
            /// @param _message The message payload to be relayed to the target on the destination chain.
            /// @return Hash of the encoded message parameters, used to uniquely identify the message.
            function hashL2toL2CrossDomainMessage(
                uint256 _destination,
                uint256 _source,
                uint256 _nonce,
                address _sender,
                address _target,
                bytes memory _message
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(abi.encode(_destination, _source, _nonce, _sender, _target, _message));
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.8;
        import "./RLPErrors.sol";
        /// @custom:attribution https://github.com/hamdiallam/Solidity-RLP
        /// @title RLPReader
        /// @notice RLPReader is a library for parsing RLP-encoded byte arrays into Solidity types. Adapted
        ///         from Solidity-RLP (https://github.com/hamdiallam/Solidity-RLP) by Hamdi Allam with
        ///         various tweaks to improve readability.
        library RLPReader {
            /// @notice Custom pointer type to avoid confusion between pointers and uint256s.
            type MemoryPointer is uint256;
            /// @notice RLP item types.
            /// @custom:value DATA_ITEM Represents an RLP data item (NOT a list).
            /// @custom:value LIST_ITEM Represents an RLP list item.
            enum RLPItemType {
                DATA_ITEM,
                LIST_ITEM
            }
            /// @notice Struct representing an RLP item.
            /// @custom:field length Length of the RLP item.
            /// @custom:field ptr    Pointer to the RLP item in memory.
            struct RLPItem {
                uint256 length;
                MemoryPointer ptr;
            }
            /// @notice Max list length that this library will accept.
            uint256 internal constant MAX_LIST_LENGTH = 32;
            /// @notice Converts bytes to a reference to memory position and length.
            /// @param _in Input bytes to convert.
            /// @return out_ Output memory reference.
            function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory out_) {
                // Empty arrays are not RLP items.
                if (_in.length == 0) revert EmptyItem();
                MemoryPointer ptr;
                assembly {
                    ptr := add(_in, 32)
                }
                out_ = RLPItem({ length: _in.length, ptr: ptr });
            }
            /// @notice Reads an RLP list value into a list of RLP items.
            /// @param _in RLP list value.
            /// @return out_ Decoded RLP list items.
            function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory out_) {
                (uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);
                if (itemType != RLPItemType.LIST_ITEM) revert UnexpectedString();
                if (listOffset + listLength != _in.length) revert InvalidDataRemainder();
                // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
                // writing to the length. Since we can't know the number of RLP items without looping over
                // the entire input, we'd have to loop twice to accurately size this array. It's easier to
                // simply set a reasonable maximum list length and decrease the size before we finish.
                out_ = new RLPItem[](MAX_LIST_LENGTH);
                uint256 itemCount = 0;
                uint256 offset = listOffset;
                while (offset < _in.length) {
                    (uint256 itemOffset, uint256 itemLength,) = _decodeLength(
                        RLPItem({ length: _in.length - offset, ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset) })
                    );
                    // We don't need to check itemCount < out.length explicitly because Solidity already
                    // handles this check on our behalf, we'd just be wasting gas.
                    out_[itemCount] = RLPItem({
                        length: itemLength + itemOffset,
                        ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
                    });
                    itemCount += 1;
                    offset += itemOffset + itemLength;
                }
                // Decrease the array size to match the actual item count.
                assembly {
                    mstore(out_, itemCount)
                }
            }
            /// @notice Reads an RLP list value into a list of RLP items.
            /// @param _in RLP list value.
            /// @return out_ Decoded RLP list items.
            function readList(bytes memory _in) internal pure returns (RLPItem[] memory out_) {
                out_ = readList(toRLPItem(_in));
            }
            /// @notice Reads an RLP bytes value into bytes.
            /// @param _in RLP bytes value.
            /// @return out_ Decoded bytes.
            function readBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
                (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
                if (itemType != RLPItemType.DATA_ITEM) revert UnexpectedList();
                if (_in.length != itemOffset + itemLength) revert InvalidDataRemainder();
                out_ = _copy(_in.ptr, itemOffset, itemLength);
            }
            /// @notice Reads an RLP bytes value into bytes.
            /// @param _in RLP bytes value.
            /// @return out_ Decoded bytes.
            function readBytes(bytes memory _in) internal pure returns (bytes memory out_) {
                out_ = readBytes(toRLPItem(_in));
            }
            /// @notice Reads the raw bytes of an RLP item.
            /// @param _in RLP item to read.
            /// @return out_ Raw RLP bytes.
            function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
                out_ = _copy(_in.ptr, 0, _in.length);
            }
            /// @notice Decodes the length of an RLP item.
            /// @param _in RLP item to decode.
            /// @return offset_ Offset of the encoded data.
            /// @return length_ Length of the encoded data.
            /// @return type_ RLP item type (LIST_ITEM or DATA_ITEM).
            function _decodeLength(RLPItem memory _in)
                private
                pure
                returns (uint256 offset_, uint256 length_, RLPItemType type_)
            {
                // Short-circuit if there's nothing to decode, note that we perform this check when
                // the user creates an RLP item via toRLPItem, but it's always possible for them to bypass
                // that function and create an RLP item directly. So we need to check this anyway.
                if (_in.length == 0) revert EmptyItem();
                MemoryPointer ptr = _in.ptr;
                uint256 prefix;
                assembly {
                    prefix := byte(0, mload(ptr))
                }
                if (prefix <= 0x7f) {
                    // Single byte.
                    return (0, 1, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xb7) {
                    // Short string.
                    // slither-disable-next-line variable-scope
                    uint256 strLen = prefix - 0x80;
                    if (_in.length <= strLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (strLen == 1 && firstByteOfContent < 0x80) revert InvalidHeader();
                    return (1, strLen, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xbf) {
                    // Long string.
                    uint256 lenOfStrLen = prefix - 0xb7;
                    if (_in.length <= lenOfStrLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (firstByteOfContent == 0x00) revert InvalidHeader();
                    uint256 strLen;
                    assembly {
                        strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))
                    }
                    if (strLen <= 55) revert InvalidHeader();
                    if (_in.length <= lenOfStrLen + strLen) revert ContentLengthMismatch();
                    return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xf7) {
                    // Short list.
                    // slither-disable-next-line variable-scope
                    uint256 listLen = prefix - 0xc0;
                    if (_in.length <= listLen) revert ContentLengthMismatch();
                    return (1, listLen, RLPItemType.LIST_ITEM);
                } else {
                    // Long list.
                    uint256 lenOfListLen = prefix - 0xf7;
                    if (_in.length <= lenOfListLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (firstByteOfContent == 0x00) revert InvalidHeader();
                    uint256 listLen;
                    assembly {
                        listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))
                    }
                    if (listLen <= 55) revert InvalidHeader();
                    if (_in.length <= lenOfListLen + listLen) revert ContentLengthMismatch();
                    return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
                }
            }
            /// @notice Copies the bytes from a memory location.
            /// @param _src    Pointer to the location to read from.
            /// @param _offset Offset to start reading from.
            /// @param _length Number of bytes to read.
            /// @return out_ Copied bytes.
            function _copy(MemoryPointer _src, uint256 _offset, uint256 _length) private pure returns (bytes memory out_) {
                out_ = new bytes(_length);
                if (_length == 0) {
                    return out_;
                }
                // Mostly based on Solidity's copy_memory_to_memory:
                // https://github.com/ethereum/solidity/blob/34dd30d71b4da730488be72ff6af7083cf2a91f6/libsolidity/codegen/YulUtilFunctions.cpp#L102-L114
                uint256 src = MemoryPointer.unwrap(_src) + _offset;
                assembly {
                    let dest := add(out_, 32)
                    let i := 0
                    for { } lt(i, _length) { i := add(i, 32) } { mstore(add(dest, i), mload(add(src, i))) }
                    if gt(i, _length) { mstore(add(dest, _length), 0) }
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title ISemver
        /// @notice ISemver is a simple contract for ensuring that contracts are
        ///         versioned using semantic versioning.
        interface ISemver {
            /// @notice Getter for the semantic version of the contract. This is not
            ///         meant to be used onchain but instead meant to be used by offchain
            ///         tooling.
            /// @return Semver contract version as a string.
            function version() external view returns (string memory);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibPosition.sol";
        using LibClaim for Claim global;
        using LibHash for Hash global;
        using LibDuration for Duration global;
        using LibClock for Clock global;
        using LibGameId for GameId global;
        using LibTimestamp for Timestamp global;
        using LibVMStatus for VMStatus global;
        using LibGameType for GameType global;
        /// @notice A `Clock` represents a packed `Duration` and `Timestamp`
        /// @dev The packed layout of this type is as follows:
        /// ┌────────────┬────────────────┐
        /// │    Bits    │     Value      │
        /// ├────────────┼────────────────┤
        /// │ [0, 64)    │ Duration       │
        /// │ [64, 128)  │ Timestamp      │
        /// └────────────┴────────────────┘
        type Clock is uint128;
        /// @title LibClock
        /// @notice This library contains helper functions for working with the `Clock` type.
        library LibClock {
            /// @notice Packs a `Duration` and `Timestamp` into a `Clock` type.
            /// @param _duration The `Duration` to pack into the `Clock` type.
            /// @param _timestamp The `Timestamp` to pack into the `Clock` type.
            /// @return clock_ The `Clock` containing the `_duration` and `_timestamp`.
            function wrap(Duration _duration, Timestamp _timestamp) internal pure returns (Clock clock_) {
                assembly {
                    clock_ := or(shl(0x40, _duration), _timestamp)
                }
            }
            /// @notice Pull the `Duration` out of a `Clock` type.
            /// @param _clock The `Clock` type to pull the `Duration` out of.
            /// @return duration_ The `Duration` pulled out of `_clock`.
            function duration(Clock _clock) internal pure returns (Duration duration_) {
                // Shift the high-order 64 bits into the low-order 64 bits, leaving only the `duration`.
                assembly {
                    duration_ := shr(0x40, _clock)
                }
            }
            /// @notice Pull the `Timestamp` out of a `Clock` type.
            /// @param _clock The `Clock` type to pull the `Timestamp` out of.
            /// @return timestamp_ The `Timestamp` pulled out of `_clock`.
            function timestamp(Clock _clock) internal pure returns (Timestamp timestamp_) {
                // Clean the high-order 192 bits by shifting the clock left and then right again, leaving
                // only the `timestamp`.
                assembly {
                    timestamp_ := shr(0xC0, shl(0xC0, _clock))
                }
            }
            /// @notice Get the value of a `Clock` type in the form of the underlying uint128.
            /// @param _clock The `Clock` type to get the value of.
            /// @return clock_ The value of the `Clock` type as a uint128 type.
            function raw(Clock _clock) internal pure returns (uint128 clock_) {
                assembly {
                    clock_ := _clock
                }
            }
        }
        /// @notice A `GameId` represents a packed 4 byte game ID, a 8 byte timestamp, and a 20 byte address.
        /// @dev The packed layout of this type is as follows:
        /// ┌───────────┬───────────┐
        /// │   Bits    │   Value   │
        /// ├───────────┼───────────┤
        /// │ [0, 32)   │ Game Type │
        /// │ [32, 96)  │ Timestamp │
        /// │ [96, 256) │ Address   │
        /// └───────────┴───────────┘
        type GameId is bytes32;
        /// @title LibGameId
        /// @notice Utility functions for packing and unpacking GameIds.
        library LibGameId {
            /// @notice Packs values into a 32 byte GameId type.
            /// @param _gameType The game type.
            /// @param _timestamp The timestamp of the game's creation.
            /// @param _gameProxy The game proxy address.
            /// @return gameId_ The packed GameId.
            function pack(
                GameType _gameType,
                Timestamp _timestamp,
                address _gameProxy
            )
                internal
                pure
                returns (GameId gameId_)
            {
                assembly {
                    gameId_ := or(or(shl(224, _gameType), shl(160, _timestamp)), _gameProxy)
                }
            }
            /// @notice Unpacks values from a 32 byte GameId type.
            /// @param _gameId The packed GameId.
            /// @return gameType_ The game type.
            /// @return timestamp_ The timestamp of the game's creation.
            /// @return gameProxy_ The game proxy address.
            function unpack(GameId _gameId)
                internal
                pure
                returns (GameType gameType_, Timestamp timestamp_, address gameProxy_)
            {
                assembly {
                    gameType_ := shr(224, _gameId)
                    timestamp_ := and(shr(160, _gameId), 0xFFFFFFFFFFFFFFFF)
                    gameProxy_ := and(_gameId, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
                }
            }
        }
        /// @notice A claim represents an MPT root representing the state of the fault proof program.
        type Claim is bytes32;
        /// @title LibClaim
        /// @notice This library contains helper functions for working with the `Claim` type.
        library LibClaim {
            /// @notice Get the value of a `Claim` type in the form of the underlying bytes32.
            /// @param _claim The `Claim` type to get the value of.
            /// @return claim_ The value of the `Claim` type as a bytes32 type.
            function raw(Claim _claim) internal pure returns (bytes32 claim_) {
                assembly {
                    claim_ := _claim
                }
            }
            /// @notice Hashes a claim and a position together.
            /// @param _claim A Claim type.
            /// @param _position The position of `claim`.
            /// @param _challengeIndex The index of the claim being moved against.
            /// @return claimHash_ A hash of abi.encodePacked(claim, position|challengeIndex);
            function hashClaimPos(
                Claim _claim,
                Position _position,
                uint256 _challengeIndex
            )
                internal
                pure
                returns (Hash claimHash_)
            {
                assembly {
                    mstore(0x00, _claim)
                    mstore(0x20, or(shl(128, _position), and(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, _challengeIndex)))
                    claimHash_ := keccak256(0x00, 0x40)
                }
            }
        }
        /// @notice A dedicated duration type.
        /// @dev Unit: seconds
        type Duration is uint64;
        /// @title LibDuration
        /// @notice This library contains helper functions for working with the `Duration` type.
        library LibDuration {
            /// @notice Get the value of a `Duration` type in the form of the underlying uint64.
            /// @param _duration The `Duration` type to get the value of.
            /// @return duration_ The value of the `Duration` type as a uint64 type.
            function raw(Duration _duration) internal pure returns (uint64 duration_) {
                assembly {
                    duration_ := _duration
                }
            }
        }
        /// @notice A custom type for a generic hash.
        type Hash is bytes32;
        /// @title LibHash
        /// @notice This library contains helper functions for working with the `Hash` type.
        library LibHash {
            /// @notice Get the value of a `Hash` type in the form of the underlying bytes32.
            /// @param _hash The `Hash` type to get the value of.
            /// @return hash_ The value of the `Hash` type as a bytes32 type.
            function raw(Hash _hash) internal pure returns (bytes32 hash_) {
                assembly {
                    hash_ := _hash
                }
            }
        }
        /// @notice A dedicated timestamp type.
        type Timestamp is uint64;
        /// @title LibTimestamp
        /// @notice This library contains helper functions for working with the `Timestamp` type.
        library LibTimestamp {
            /// @notice Get the value of a `Timestamp` type in the form of the underlying uint64.
            /// @param _timestamp The `Timestamp` type to get the value of.
            /// @return timestamp_ The value of the `Timestamp` type as a uint64 type.
            function raw(Timestamp _timestamp) internal pure returns (uint64 timestamp_) {
                assembly {
                    timestamp_ := _timestamp
                }
            }
        }
        /// @notice A `VMStatus` represents the status of a VM execution.
        type VMStatus is uint8;
        /// @title LibVMStatus
        /// @notice This library contains helper functions for working with the `VMStatus` type.
        library LibVMStatus {
            /// @notice Get the value of a `VMStatus` type in the form of the underlying uint8.
            /// @param _vmstatus The `VMStatus` type to get the value of.
            /// @return vmstatus_ The value of the `VMStatus` type as a uint8 type.
            function raw(VMStatus _vmstatus) internal pure returns (uint8 vmstatus_) {
                assembly {
                    vmstatus_ := _vmstatus
                }
            }
        }
        /// @notice A `GameType` represents the type of game being played.
        type GameType is uint32;
        /// @title LibGameType
        /// @notice This library contains helper functions for working with the `GameType` type.
        library LibGameType {
            /// @notice Get the value of a `GameType` type in the form of the underlying uint32.
            /// @param _gametype The `GameType` type to get the value of.
            /// @return gametype_ The value of the `GameType` type as a uint32 type.
            function raw(GameType _gametype) internal pure returns (uint32 gametype_) {
                assembly {
                    gametype_ := _gametype
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface ISuperchainConfig {
            enum UpdateType {
                GUARDIAN
            }
            event ConfigUpdate(UpdateType indexed updateType, bytes data);
            event Initialized(uint8 version);
            event Paused(string identifier);
            event Unpaused();
            function GUARDIAN_SLOT() external view returns (bytes32);
            function PAUSED_SLOT() external view returns (bytes32);
            function guardian() external view returns (address guardian_);
            function initialize(address _guardian, bool _paused) external;
            function pause(string memory _identifier) external;
            function paused() external view returns (bool paused_);
            function unpause() external;
            function version() external view returns (string memory);
            function __constructor__() external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol";
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        import { IBigStepper } from "src/dispute/interfaces/IBigStepper.sol";
        import { Types } from "src/libraries/Types.sol";
        import "src/dispute/lib/Types.sol";
        interface IFaultDisputeGame is IDisputeGame {
            struct ClaimData {
                uint32 parentIndex;
                address counteredBy;
                address claimant;
                uint128 bond;
                Claim claim;
                Position position;
                Clock clock;
            }
            struct ResolutionCheckpoint {
                bool initialCheckpointComplete;
                uint32 subgameIndex;
                Position leftmostPosition;
                address counteredBy;
            }
            error AlreadyInitialized();
            error AnchorRootNotFound();
            error BlockNumberMatches();
            error BondTransferFailed();
            error CannotDefendRootClaim();
            error ClaimAboveSplit();
            error ClaimAlreadyExists();
            error ClaimAlreadyResolved();
            error ClockNotExpired();
            error ClockTimeExceeded();
            error ContentLengthMismatch();
            error DuplicateStep();
            error EmptyItem();
            error GameDepthExceeded();
            error GameNotInProgress();
            error IncorrectBondAmount();
            error InvalidChallengePeriod();
            error InvalidClockExtension();
            error InvalidDataRemainder();
            error InvalidDisputedClaimIndex();
            error InvalidHeader();
            error InvalidHeaderRLP();
            error InvalidLocalIdent();
            error InvalidOutputRootProof();
            error InvalidParent();
            error InvalidPrestate();
            error InvalidSplitDepth();
            error L2BlockNumberChallenged();
            error MaxDepthTooLarge();
            error NoCreditToClaim();
            error OutOfOrderResolution();
            error UnexpectedList();
            error UnexpectedRootClaim(Claim rootClaim);
            error UnexpectedString();
            error ValidStep();
            event Move(uint256 indexed parentIndex, Claim indexed claim, address indexed claimant);
            function absolutePrestate() external view returns (Claim absolutePrestate_);
            function addLocalData(uint256 _ident, uint256 _execLeafIdx, uint256 _partOffset) external;
            function anchorStateRegistry() external view returns (IAnchorStateRegistry registry_);
            function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable;
            function challengeRootL2Block(Types.OutputRootProof memory _outputRootProof, bytes memory _headerRLP) external;
            function claimCredit(address _recipient) external;
            function claimData(uint256)
                external
                view // nosemgrep
                returns (
                    uint32 parentIndex,
                    address counteredBy,
                    address claimant,
                    uint128 bond,
                    Claim claim,
                    Position position,
                    Clock clock
                );
            function claimDataLen() external view returns (uint256 len_);
            function claims(Hash) external view returns (bool);
            function clockExtension() external view returns (Duration clockExtension_);
            function credit(address) external view returns (uint256);
            function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable;
            function getChallengerDuration(uint256 _claimIndex) external view returns (Duration duration_);
            function getNumToResolve(uint256 _claimIndex) external view returns (uint256 numRemainingChildren_);
            function getRequiredBond(Position _position) external view returns (uint256 requiredBond_);
            function l2BlockNumber() external pure returns (uint256 l2BlockNumber_);
            function l2BlockNumberChallenged() external view returns (bool);
            function l2BlockNumberChallenger() external view returns (address);
            function l2ChainId() external view returns (uint256 l2ChainId_);
            function maxClockDuration() external view returns (Duration maxClockDuration_);
            function maxGameDepth() external view returns (uint256 maxGameDepth_);
            function move(Claim _disputed, uint256 _challengeIndex, Claim _claim, bool _isAttack) external payable;
            function resolutionCheckpoints(uint256)
                external
                view
                returns (bool initialCheckpointComplete, uint32 subgameIndex, Position leftmostPosition, address counteredBy); // nosemgrep
            function resolveClaim(uint256 _claimIndex, uint256 _numToResolve) external;
            function resolvedSubgames(uint256) external view returns (bool);
            function splitDepth() external view returns (uint256 splitDepth_);
            function startingBlockNumber() external view returns (uint256 startingBlockNumber_);
            function startingOutputRoot() external view returns (Hash root, uint256 l2BlockNumber); // nosemgrep
            function startingRootHash() external view returns (Hash startingRootHash_);
            function step(uint256 _claimIndex, bool _isAttack, bytes memory _stateData, bytes memory _proof) external;
            function subgames(uint256, uint256) external view returns (uint256);
            function version() external view returns (string memory);
            function vm() external view returns (IBigStepper vm_);
            function weth() external view returns (IDelayedWETH weth_);
            function __constructor__(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId
            )
                external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol";
        import "src/dispute/lib/Types.sol";
        interface IDisputeGameFactory {
            struct GameSearchResult {
                uint256 index;
                GameId metadata;
                Timestamp timestamp;
                Claim rootClaim;
                bytes extraData;
            }
            error GameAlreadyExists(Hash uuid);
            error IncorrectBondAmount();
            error NoImplementation(GameType gameType);
            event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim);
            event ImplementationSet(address indexed impl, GameType indexed gameType);
            event InitBondUpdated(GameType indexed gameType, uint256 indexed newBond);
            event Initialized(uint8 version);
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            function create(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                payable
                returns (IDisputeGame proxy_);
            function findLatestGames(
                GameType _gameType,
                uint256 _start,
                uint256 _n
            )
                external
                view
                returns (GameSearchResult[] memory games_);
            function gameAtIndex(uint256 _index)
                external
                view
                returns (GameType gameType_, Timestamp timestamp_, IDisputeGame proxy_);
            function gameCount() external view returns (uint256 gameCount_);
            function gameImpls(GameType) external view returns (IDisputeGame);
            function games(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                view
                returns (IDisputeGame proxy_, Timestamp timestamp_);
            function getGameUUID(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                pure
                returns (Hash uuid_);
            function initBonds(GameType) external view returns (uint256);
            function initialize(address _owner) external;
            function owner() external view returns (address);
            function renounceOwnership() external;
            function setImplementation(GameType _gameType, IDisputeGame _impl) external;
            function setInitBond(GameType _gameType, uint256 _initBond) external;
            function transferOwnership(address newOwner) external; // nosemgrep
            function version() external view returns (string memory);
            function __constructor__() external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { LibKeccak } from "@lib-keccak/LibKeccak.sol";
        import { LPPMetaData } from "src/cannon/libraries/CannonTypes.sol";
        interface IPreimageOracle {
            struct Leaf {
                bytes input;
                uint256 index;
                bytes32 stateCommitment;
            }
            error ActiveProposal();
            error AlreadyFinalized();
            error AlreadyInitialized();
            error BadProposal();
            error BondTransferFailed();
            error InsufficientBond();
            error InvalidInputSize();
            error InvalidPreimage();
            error InvalidProof();
            error NotEOA();
            error NotInitialized();
            error PartOffsetOOB();
            error PostStateMatches();
            error StatesNotContiguous();
            error TreeSizeOverflow();
            error WrongStartingBlock();
            function KECCAK_TREE_DEPTH() external view returns (uint256);
            function MAX_LEAF_COUNT() external view returns (uint256);
            function MIN_BOND_SIZE() external view returns (uint256);
            function PRECOMPILE_CALL_RESERVED_GAS() external view returns (uint256);
            function addLeavesLPP(
                uint256 _uuid,
                uint256 _inputStartBlock,
                bytes memory _input,
                bytes32[] memory _stateCommitments,
                bool _finalize
            )
                external;
            function challengeFirstLPP(
                address _claimant,
                uint256 _uuid,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function challengeLPP(
                address _claimant,
                uint256 _uuid,
                LibKeccak.StateMatrix memory _stateMatrix,
                Leaf memory _preState,
                bytes32[] memory _preStateProof,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function challengePeriod() external view returns (uint256 challengePeriod_);
            function getTreeRootLPP(address _owner, uint256 _uuid) external view returns (bytes32 treeRoot_);
            function initLPP(uint256 _uuid, uint32 _partOffset, uint32 _claimedSize) external payable;
            function loadBlobPreimagePart(
                uint256 _z,
                uint256 _y,
                bytes memory _commitment,
                bytes memory _proof,
                uint256 _partOffset
            )
                external;
            function loadKeccak256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
            function loadLocalData(
                uint256 _ident,
                bytes32 _localContext,
                bytes32 _word,
                uint256 _size,
                uint256 _partOffset
            )
                external
                returns (bytes32 key_);
            function loadPrecompilePreimagePart(
                uint256 _partOffset,
                address _precompile,
                uint64 _requiredGas,
                bytes memory _input
            )
                external;
            function loadSha256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
            function minProposalSize() external view returns (uint256 minProposalSize_);
            function preimageLengths(bytes32) external view returns (uint256);
            function preimagePartOk(bytes32, uint256) external view returns (bool);
            function preimageParts(bytes32, uint256) external view returns (bytes32);
            function proposalBlocks(address, uint256, uint256) external view returns (uint64);
            function proposalBlocksLen(address _claimant, uint256 _uuid) external view returns (uint256 len_);
            function proposalBonds(address, uint256) external view returns (uint256);
            function proposalBranches(address, uint256, uint256) external view returns (bytes32);
            function proposalCount() external view returns (uint256 count_);
            function proposalMetadata(address, uint256) external view returns (LPPMetaData);
            function proposalParts(address, uint256) external view returns (bytes32);
            function proposals(uint256) external view returns (address claimant, uint256 uuid); // nosemgrep:
                // sol-style-return-arg-fmt
            function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_);
            function squeezeLPP(
                address _claimant,
                uint256 _uuid,
                LibKeccak.StateMatrix memory _stateMatrix,
                Leaf memory _preState,
                bytes32[] memory _preStateProof,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function version() external view returns (string memory);
            function zeroHashes(uint256) external view returns (bytes32);
            function __constructor__(uint256 _minProposalSize, uint256 _challengePeriod) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { Types } from "src/libraries/Types.sol";
        import { Hashing } from "src/libraries/Hashing.sol";
        import { RLPWriter } from "src/libraries/rlp/RLPWriter.sol";
        /// @title Encoding
        /// @notice Encoding handles Optimism's various different encoding schemes.
        library Encoding {
            /// @notice RLP encodes the L2 transaction that would be generated when a given deposit is sent
            ///         to the L2 system. Useful for searching for a deposit in the L2 system. The
            ///         transaction is prefixed with 0x7e to identify its EIP-2718 type.
            /// @param _tx User deposit transaction to encode.
            /// @return RLP encoded L2 deposit transaction.
            function encodeDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes memory) {
                bytes32 source = Hashing.hashDepositSource(_tx.l1BlockHash, _tx.logIndex);
                bytes[] memory raw = new bytes[](8);
                raw[0] = RLPWriter.writeBytes(abi.encodePacked(source));
                raw[1] = RLPWriter.writeAddress(_tx.from);
                raw[2] = _tx.isCreation ? RLPWriter.writeBytes("") : RLPWriter.writeAddress(_tx.to);
                raw[3] = RLPWriter.writeUint(_tx.mint);
                raw[4] = RLPWriter.writeUint(_tx.value);
                raw[5] = RLPWriter.writeUint(uint256(_tx.gasLimit));
                raw[6] = RLPWriter.writeBool(false);
                raw[7] = RLPWriter.writeBytes(_tx.data);
                return abi.encodePacked(uint8(0x7e), RLPWriter.writeList(raw));
            }
            /// @notice Encodes the cross domain message based on the version that is encoded into the
            ///         message nonce.
            /// @param _nonce    Message nonce with version encoded into the first two bytes.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessage(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes memory)
            {
                (, uint16 version) = decodeVersionedNonce(_nonce);
                if (version == 0) {
                    return encodeCrossDomainMessageV0(_target, _sender, _data, _nonce);
                } else if (version == 1) {
                    return encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);
                } else {
                    revert("Encoding: unknown cross domain message version");
                }
            }
            /// @notice Encodes a cross domain message based on the V0 (legacy) encoding.
            /// @param _target Address of the target of the message.
            /// @param _sender Address of the sender of the message.
            /// @param _data   Data to send with the message.
            /// @param _nonce  Message nonce.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessageV0(
                address _target,
                address _sender,
                bytes memory _data,
                uint256 _nonce
            )
                internal
                pure
                returns (bytes memory)
            {
                // nosemgrep: sol-style-use-abi-encodecall
                return abi.encodeWithSignature("relayMessage(address,address,bytes,uint256)", _target, _sender, _data, _nonce);
            }
            /// @notice Encodes a cross domain message based on the V1 (current) encoding.
            /// @param _nonce    Message nonce.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessageV1(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes memory)
            {
                // nosemgrep: sol-style-use-abi-encodecall
                return abi.encodeWithSignature(
                    "relayMessage(uint256,address,address,uint256,uint256,bytes)",
                    _nonce,
                    _sender,
                    _target,
                    _value,
                    _gasLimit,
                    _data
                );
            }
            /// @notice Adds a version number into the first two bytes of a message nonce.
            /// @param _nonce   Message nonce to encode into.
            /// @param _version Version number to encode into the message nonce.
            /// @return Message nonce with version encoded into the first two bytes.
            function encodeVersionedNonce(uint240 _nonce, uint16 _version) internal pure returns (uint256) {
                uint256 nonce;
                assembly {
                    nonce := or(shl(240, _version), _nonce)
                }
                return nonce;
            }
            /// @notice Pulls the version out of a version-encoded nonce.
            /// @param _nonce Message nonce with version encoded into the first two bytes.
            /// @return Nonce without encoded version.
            /// @return Version of the message.
            function decodeVersionedNonce(uint256 _nonce) internal pure returns (uint240, uint16) {
                uint240 nonce;
                uint16 version;
                assembly {
                    nonce := and(_nonce, 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                    version := shr(240, _nonce)
                }
                return (nonce, version);
            }
            /// @notice Returns an appropriately encoded call to L1Block.setL1BlockValuesEcotone
            /// @param _baseFeeScalar       L1 base fee Scalar
            /// @param _blobBaseFeeScalar   L1 blob base fee Scalar
            /// @param _sequenceNumber      Number of L2 blocks since epoch start.
            /// @param _timestamp           L1 timestamp.
            /// @param _number              L1 blocknumber.
            /// @param _baseFee             L1 base fee.
            /// @param _blobBaseFee         L1 blob base fee.
            /// @param _hash                L1 blockhash.
            /// @param _batcherHash         Versioned hash to authenticate batcher by.
            function encodeSetL1BlockValuesEcotone(
                uint32 _baseFeeScalar,
                uint32 _blobBaseFeeScalar,
                uint64 _sequenceNumber,
                uint64 _timestamp,
                uint64 _number,
                uint256 _baseFee,
                uint256 _blobBaseFee,
                bytes32 _hash,
                bytes32 _batcherHash
            )
                internal
                pure
                returns (bytes memory)
            {
                bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesEcotone()"));
                return abi.encodePacked(
                    functionSignature,
                    _baseFeeScalar,
                    _blobBaseFeeScalar,
                    _sequenceNumber,
                    _timestamp,
                    _number,
                    _baseFee,
                    _blobBaseFee,
                    _hash,
                    _batcherHash
                );
            }
            /// @notice Returns an appropriately encoded call to L1Block.setL1BlockValuesInterop
            /// @param _baseFeeScalar       L1 base fee Scalar
            /// @param _blobBaseFeeScalar   L1 blob base fee Scalar
            /// @param _sequenceNumber      Number of L2 blocks since epoch start.
            /// @param _timestamp           L1 timestamp.
            /// @param _number              L1 blocknumber.
            /// @param _baseFee             L1 base fee.
            /// @param _blobBaseFee         L1 blob base fee.
            /// @param _hash                L1 blockhash.
            /// @param _batcherHash         Versioned hash to authenticate batcher by.
            function encodeSetL1BlockValuesInterop(
                uint32 _baseFeeScalar,
                uint32 _blobBaseFeeScalar,
                uint64 _sequenceNumber,
                uint64 _timestamp,
                uint64 _number,
                uint256 _baseFee,
                uint256 _blobBaseFee,
                bytes32 _hash,
                bytes32 _batcherHash
            )
                internal
                pure
                returns (bytes memory)
            {
                bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesInterop()"));
                return abi.encodePacked(
                    functionSignature,
                    _baseFeeScalar,
                    _blobBaseFeeScalar,
                    _sequenceNumber,
                    _timestamp,
                    _number,
                    _baseFee,
                    _blobBaseFee,
                    _hash,
                    _batcherHash
                );
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @notice The length of an RLP item must be greater than zero to be decodable
        error EmptyItem();
        /// @notice The decoded item type for list is not a list item
        error UnexpectedString();
        /// @notice The RLP item has an invalid data remainder
        error InvalidDataRemainder();
        /// @notice Decoded item type for bytes is not a string item
        error UnexpectedList();
        /// @notice The length of the content must be greater than the RLP item length
        error ContentLengthMismatch();
        /// @notice Invalid RLP header for RLP item
        error InvalidHeader();
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        using LibPosition for Position global;
        /// @notice A `Position` represents a position of a claim within the game tree.
        /// @dev This is represented as a "generalized index" where the high-order bit
        /// is the level in the tree and the remaining bits is a unique bit pattern, allowing
        /// a unique identifier for each node in the tree. Mathematically, it is calculated
        /// as 2^{depth} + indexAtDepth.
        type Position is uint128;
        /// @title LibPosition
        /// @notice This library contains helper functions for working with the `Position` type.
        library LibPosition {
            /// @notice the `MAX_POSITION_BITLEN` is the number of bits that the `Position` type, and the implementation of
            ///         its behavior within this library, can safely support.
            uint8 internal constant MAX_POSITION_BITLEN = 126;
            /// @notice Computes a generalized index (2^{depth} + indexAtDepth).
            /// @param _depth The depth of the position.
            /// @param _indexAtDepth The index at the depth of the position.
            /// @return position_ The computed generalized index.
            function wrap(uint8 _depth, uint128 _indexAtDepth) internal pure returns (Position position_) {
                assembly {
                    // gindex = 2^{_depth} + _indexAtDepth
                    position_ := add(shl(_depth, 1), _indexAtDepth)
                }
            }
            /// @notice Pulls the `depth` out of a `Position` type.
            /// @param _position The generalized index to get the `depth` of.
            /// @return depth_ The `depth` of the `position` gindex.
            /// @custom:attribution Solady <https://github.com/Vectorized/Solady>
            function depth(Position _position) internal pure returns (uint8 depth_) {
                // Return the most significant bit offset, which signifies the depth of the gindex.
                assembly {
                    depth_ := or(depth_, shl(6, lt(0xffffffffffffffff, shr(depth_, _position))))
                    depth_ := or(depth_, shl(5, lt(0xffffffff, shr(depth_, _position))))
                    // For the remaining 32 bits, use a De Bruijn lookup.
                    _position := shr(depth_, _position)
                    _position := or(_position, shr(1, _position))
                    _position := or(_position, shr(2, _position))
                    _position := or(_position, shr(4, _position))
                    _position := or(_position, shr(8, _position))
                    _position := or(_position, shr(16, _position))
                    depth_ :=
                        or(
                            depth_,
                            byte(
                                shr(251, mul(_position, shl(224, 0x07c4acdd))),
                                0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
                            )
                        )
                }
            }
            /// @notice Pulls the `indexAtDepth` out of a `Position` type.
            ///         The `indexAtDepth` is the left/right index of a position at a specific depth within
            ///         the binary tree, starting from index 0. For example, at gindex 2, the `depth` = 1
            ///         and the `indexAtDepth` = 0.
            /// @param _position The generalized index to get the `indexAtDepth` of.
            /// @return indexAtDepth_ The `indexAtDepth` of the `position` gindex.
            function indexAtDepth(Position _position) internal pure returns (uint128 indexAtDepth_) {
                // Return bits p_{msb-1}...p_{0}. This effectively pulls the 2^{depth} out of the gindex,
                // leaving only the `indexAtDepth`.
                uint256 msb = depth(_position);
                assembly {
                    indexAtDepth_ := sub(_position, shl(msb, 1))
                }
            }
            /// @notice Get the left child of `_position`.
            /// @param _position The position to get the left position of.
            /// @return left_ The position to the left of `position`.
            function left(Position _position) internal pure returns (Position left_) {
                assembly {
                    left_ := shl(1, _position)
                }
            }
            /// @notice Get the right child of `_position`
            /// @param _position The position to get the right position of.
            /// @return right_ The position to the right of `position`.
            function right(Position _position) internal pure returns (Position right_) {
                assembly {
                    right_ := or(1, shl(1, _position))
                }
            }
            /// @notice Get the parent position of `_position`.
            /// @param _position The position to get the parent position of.
            /// @return parent_ The parent position of `position`.
            function parent(Position _position) internal pure returns (Position parent_) {
                assembly {
                    parent_ := shr(1, _position)
                }
            }
            /// @notice Get the deepest, right most gindex relative to the `position`. This is equivalent to
            ///         calling `right` on a position until the maximum depth is reached.
            /// @param _position The position to get the relative deepest, right most gindex of.
            /// @param _maxDepth The maximum depth of the game.
            /// @return rightIndex_ The deepest, right most gindex relative to the `position`.
            function rightIndex(Position _position, uint256 _maxDepth) internal pure returns (Position rightIndex_) {
                uint256 msb = depth(_position);
                assembly {
                    let remaining := sub(_maxDepth, msb)
                    rightIndex_ := or(shl(remaining, _position), sub(shl(remaining, 1), 1))
                }
            }
            /// @notice Get the deepest, right most trace index relative to the `position`. This is
            ///         equivalent to calling `right` on a position until the maximum depth is reached and
            ///         then finding its index at depth.
            /// @param _position The position to get the relative trace index of.
            /// @param _maxDepth The maximum depth of the game.
            /// @return traceIndex_ The trace index relative to the `position`.
            function traceIndex(Position _position, uint256 _maxDepth) internal pure returns (uint256 traceIndex_) {
                uint256 msb = depth(_position);
                assembly {
                    let remaining := sub(_maxDepth, msb)
                    traceIndex_ := sub(or(shl(remaining, _position), sub(shl(remaining, 1), 1)), shl(_maxDepth, 1))
                }
            }
            /// @notice Gets the position of the highest ancestor of `_position` that commits to the same
            ///         trace index.
            /// @param _position The position to get the highest ancestor of.
            /// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
            function traceAncestor(Position _position) internal pure returns (Position ancestor_) {
                // Create a field with only the lowest unset bit of `_position` set.
                Position lsb;
                assembly {
                    lsb := and(not(_position), add(_position, 1))
                }
                // Find the index of the lowest unset bit within the field.
                uint256 msb = depth(lsb);
                // The highest ancestor that commits to the same trace index is the original position
                // shifted right by the index of the lowest unset bit.
                assembly {
                    let a := shr(msb, _position)
                    // Bound the ancestor to the minimum gindex, 1.
                    ancestor_ := or(a, iszero(a))
                }
            }
            /// @notice Gets the position of the highest ancestor of `_position` that commits to the same
            ///         trace index, while still being below `_upperBoundExclusive`.
            /// @param _position The position to get the highest ancestor of.
            /// @param _upperBoundExclusive The exclusive upper depth bound, used to inform where to stop in order
            ///                             to not escape a sub-tree.
            /// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
            function traceAncestorBounded(
                Position _position,
                uint256 _upperBoundExclusive
            )
                internal
                pure
                returns (Position ancestor_)
            {
                // This function only works for positions that are below the upper bound.
                if (_position.depth() <= _upperBoundExclusive) {
                    assembly {
                        // Revert with `ClaimAboveSplit()`
                        mstore(0x00, 0xb34b5c22)
                        revert(0x1C, 0x04)
                    }
                }
                // Grab the global trace ancestor.
                ancestor_ = traceAncestor(_position);
                // If the ancestor is above or at the upper bound, shift it to be below the upper bound.
                // This should be a special case that only covers positions that commit to the final leaf
                // in a sub-tree.
                if (ancestor_.depth() <= _upperBoundExclusive) {
                    ancestor_ = ancestor_.rightIndex(_upperBoundExclusive + 1);
                }
            }
            /// @notice Get the move position of `_position`, which is the left child of:
            ///         1. `_position` if `_isAttack` is true.
            ///         2. `_position | 1` if `_isAttack` is false.
            /// @param _position The position to get the relative attack/defense position of.
            /// @param _isAttack Whether or not the move is an attack move.
            /// @return move_ The move position relative to `position`.
            function move(Position _position, bool _isAttack) internal pure returns (Position move_) {
                assembly {
                    move_ := shl(1, or(iszero(_isAttack), _position))
                }
            }
            /// @notice Get the value of a `Position` type in the form of the underlying uint128.
            /// @param _position The position to get the value of.
            /// @return raw_ The value of the `position` as a uint128 type.
            function raw(Position _position) internal pure returns (uint128 raw_) {
                assembly {
                    raw_ := _position
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IInitializable } from "src/dispute/interfaces/IInitializable.sol";
        import "src/dispute/lib/Types.sol";
        interface IDisputeGame is IInitializable {
            event Resolved(GameStatus indexed status);
            function createdAt() external view returns (Timestamp);
            function resolvedAt() external view returns (Timestamp);
            function status() external view returns (GameStatus);
            function gameType() external view returns (GameType gameType_);
            function gameCreator() external pure returns (address creator_);
            function rootClaim() external pure returns (Claim rootClaim_);
            function l1Head() external pure returns (Hash l1Head_);
            function extraData() external pure returns (bytes memory extraData_);
            function resolve() external returns (GameStatus status_);
            function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        /// @title LibKeccak
        /// @notice An EVM implementation of the Keccak-f[1600] permutation.
        /// @author clabby <https://github.com/clabby>
        /// @custom:attribution geohot <https://github.com/geohot>
        library LibKeccak {
            /// @notice The block size of the Keccak-f[1600] permutation, 1088 bits (136 bytes).
            uint256 internal constant BLOCK_SIZE_BYTES = 136;
            /// @notice The round constants for the keccak256 hash function. Packed in memory for efficient reading during the
            ///         permutation.
            bytes internal constant ROUND_CONSTANTS = abi.encode(
                0x00000000000000010000000000008082800000000000808a8000000080008000, // r1,r2,r3,r4
                0x000000000000808b000000008000000180000000800080818000000000008009, // r5,r6,r7,r8
                0x000000000000008a00000000000000880000000080008009000000008000000a, // r9,r10,r11,r12
                0x000000008000808b800000000000008b80000000000080898000000000008003, // r13,r14,r15,r16
                0x80000000000080028000000000000080000000000000800a800000008000000a, // r17,r18,r19,r20
                0x8000000080008081800000000000808000000000800000018000000080008008 // r21,r22,r23,r24
            );
            /// @notice A mask for 64-bit values.
            uint64 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
            /// @notice The 5x5 state matrix for the keccak-f[1600] permutation.
            struct StateMatrix {
                uint64[25] state;
            }
            /// @notice Performs the Keccak-f[1600] permutation on the given 5x5 state matrix.
            function permutation(StateMatrix memory _stateMatrix) internal pure {
                // Pull the round constants into memory to avoid reallocation in the unrolled permutation loop.
                bytes memory roundConstants = ROUND_CONSTANTS;
                assembly {
                    // Add 32 to the state matrix pointer to skip the data location field.
                    let stateMatrixPtr := add(_stateMatrix, 0x20)
                    let rcPtr := add(roundConstants, 0x20)
                    // set a state element in the passed `StateMatrix` struct memory ptr.
                    function setStateElem(ptr, idx, data) {
                        mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    // 64 bit logical shift
                    function shl64(a, b) -> val {
                        val := and(shl(a, b), U64_MASK)
                    }
                    // Performs an indivudual rho + pi computation, to be used in the full `thetaRhoPi` chain.
                    function rhoPi(ptr, destIdx, srcIdx, fact, dt) {
                        let xs1 := xor(stateElem(ptr, srcIdx), dt)
                        let res := xor(shl(fact, xs1), shr(sub(64, fact), xs1))
                        setStateElem(ptr, destIdx, res)
                    }
                    // xor a column in the state matrix
                    function xorColumn(ptr, col) -> val {
                        val :=
                            xor(
                                xor(xor(stateElem(ptr, col), stateElem(ptr, add(col, 5))), stateElem(ptr, add(col, 10))),
                                xor(stateElem(ptr, add(col, 15)), stateElem(ptr, add(col, 20)))
                            )
                    }
                    // Performs the `theta`, `rho`, and `pi` steps of the Keccak-f[1600] permutation on
                    // the passed `StateMatrix` struct memory ptr.
                    function thetaRhoPi(ptr) {
                        // Theta
                        let C0 := xorColumn(ptr, 0)
                        let C1 := xorColumn(ptr, 1)
                        let C2 := xorColumn(ptr, 2)
                        let C3 := xorColumn(ptr, 3)
                        let C4 := xorColumn(ptr, 4)
                        let D0 := xor(xor(shl64(1, C1), shr(63, C1)), C4)
                        let D1 := xor(xor(shl64(1, C2), shr(63, C2)), C0)
                        let D2 := xor(xor(shl64(1, C3), shr(63, C3)), C1)
                        let D3 := xor(xor(shl64(1, C4), shr(63, C4)), C2)
                        let D4 := xor(xor(shl64(1, C0), shr(63, C0)), C3)
                        let xs1 := xor(stateElem(ptr, 1), D1)
                        let A1 := xor(shl(1, xs1), shr(63, xs1))
                        setStateElem(ptr, 0, xor(stateElem(ptr, 0), D0))
                        rhoPi(ptr, 1, 6, 44, D1)
                        rhoPi(ptr, 6, 9, 20, D4)
                        rhoPi(ptr, 9, 22, 61, D2)
                        rhoPi(ptr, 22, 14, 39, D4)
                        rhoPi(ptr, 14, 20, 18, D0)
                        rhoPi(ptr, 20, 2, 62, D2)
                        rhoPi(ptr, 2, 12, 43, D2)
                        rhoPi(ptr, 12, 13, 25, D3)
                        rhoPi(ptr, 13, 19, 8, D4)
                        rhoPi(ptr, 19, 23, 56, D3)
                        rhoPi(ptr, 23, 15, 41, D0)
                        rhoPi(ptr, 15, 4, 27, D4)
                        rhoPi(ptr, 4, 24, 14, D4)
                        rhoPi(ptr, 24, 21, 2, D1)
                        rhoPi(ptr, 21, 8, 55, D3)
                        rhoPi(ptr, 8, 16, 45, D1)
                        rhoPi(ptr, 16, 5, 36, D0)
                        rhoPi(ptr, 5, 3, 28, D3)
                        rhoPi(ptr, 3, 18, 21, D3)
                        rhoPi(ptr, 18, 17, 15, D2)
                        rhoPi(ptr, 17, 11, 10, D1)
                        rhoPi(ptr, 11, 7, 6, D2)
                        rhoPi(ptr, 7, 10, 3, D0)
                        setStateElem(ptr, 10, A1)
                    }
                    // Inner `chi` function, unrolled in `chi` for performance.
                    function innerChi(ptr, start) {
                        let A0 := stateElem(ptr, start)
                        let A1 := stateElem(ptr, add(start, 1))
                        let A2 := stateElem(ptr, add(start, 2))
                        let A3 := stateElem(ptr, add(start, 3))
                        let A4 := stateElem(ptr, add(start, 4))
                        setStateElem(ptr, start, xor(A0, and(not(A1), A2)))
                        setStateElem(ptr, add(start, 1), xor(A1, and(not(A2), A3)))
                        setStateElem(ptr, add(start, 2), xor(A2, and(not(A3), A4)))
                        setStateElem(ptr, add(start, 3), xor(A3, and(not(A4), A0)))
                        setStateElem(ptr, add(start, 4), xor(A4, and(not(A0), A1)))
                    }
                    // Performs the `chi` step of the Keccak-f[1600] permutation on the passed `StateMatrix` struct memory ptr
                    function chi(ptr) {
                        innerChi(ptr, 0)
                        innerChi(ptr, 5)
                        innerChi(ptr, 10)
                        innerChi(ptr, 15)
                        innerChi(ptr, 20)
                    }
                    // Perform the full Keccak-f[1600] permutation on a `StateMatrix` struct memory ptr for a given round.
                    function permute(ptr, roundsPtr, round) {
                        // Theta, Rho, Pi, Chi
                        thetaRhoPi(ptr)
                        chi(ptr)
                        // Iota
                        let roundConst := shr(192, mload(add(roundsPtr, shl(0x03, round))))
                        setStateElem(ptr, 0, xor(stateElem(ptr, 0), roundConst))
                    }
                    // Unroll the permutation loop.
                    permute(stateMatrixPtr, rcPtr, 0)
                    permute(stateMatrixPtr, rcPtr, 1)
                    permute(stateMatrixPtr, rcPtr, 2)
                    permute(stateMatrixPtr, rcPtr, 3)
                    permute(stateMatrixPtr, rcPtr, 4)
                    permute(stateMatrixPtr, rcPtr, 5)
                    permute(stateMatrixPtr, rcPtr, 6)
                    permute(stateMatrixPtr, rcPtr, 7)
                    permute(stateMatrixPtr, rcPtr, 8)
                    permute(stateMatrixPtr, rcPtr, 9)
                    permute(stateMatrixPtr, rcPtr, 10)
                    permute(stateMatrixPtr, rcPtr, 11)
                    permute(stateMatrixPtr, rcPtr, 12)
                    permute(stateMatrixPtr, rcPtr, 13)
                    permute(stateMatrixPtr, rcPtr, 14)
                    permute(stateMatrixPtr, rcPtr, 15)
                    permute(stateMatrixPtr, rcPtr, 16)
                    permute(stateMatrixPtr, rcPtr, 17)
                    permute(stateMatrixPtr, rcPtr, 18)
                    permute(stateMatrixPtr, rcPtr, 19)
                    permute(stateMatrixPtr, rcPtr, 20)
                    permute(stateMatrixPtr, rcPtr, 21)
                    permute(stateMatrixPtr, rcPtr, 22)
                    permute(stateMatrixPtr, rcPtr, 23)
                }
            }
            /// @notice Absorb a fixed-sized block into the sponge.
            function absorb(StateMatrix memory _stateMatrix, bytes memory _input) internal pure {
                assembly {
                    // The input must be 1088 bits long.
                    if iszero(eq(mload(_input), 136)) { revert(0, 0) }
                    let dataPtr := add(_input, 0x20)
                    let statePtr := add(_stateMatrix, 0x20)
                    // set a state element in the passed `StateMatrix` struct memory ptr.
                    function setStateElem(ptr, idx, data) {
                        mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    // Inner sha3 absorb XOR function
                    function absorbInner(stateMatrixPtr, inputPtr, idx) {
                        let boWord := mload(add(inputPtr, shl(3, idx)))
                        let res :=
                            or(
                                or(
                                    or(shl(56, byte(7, boWord)), shl(48, byte(6, boWord))),
                                    or(shl(40, byte(5, boWord)), shl(32, byte(4, boWord)))
                                ),
                                or(
                                    or(shl(24, byte(3, boWord)), shl(16, byte(2, boWord))),
                                    or(shl(8, byte(1, boWord)), byte(0, boWord))
                                )
                            )
                        setStateElem(stateMatrixPtr, idx, xor(stateElem(stateMatrixPtr, idx), res))
                    }
                    // Unroll the input XOR loop.
                    absorbInner(statePtr, dataPtr, 0)
                    absorbInner(statePtr, dataPtr, 1)
                    absorbInner(statePtr, dataPtr, 2)
                    absorbInner(statePtr, dataPtr, 3)
                    absorbInner(statePtr, dataPtr, 4)
                    absorbInner(statePtr, dataPtr, 5)
                    absorbInner(statePtr, dataPtr, 6)
                    absorbInner(statePtr, dataPtr, 7)
                    absorbInner(statePtr, dataPtr, 8)
                    absorbInner(statePtr, dataPtr, 9)
                    absorbInner(statePtr, dataPtr, 10)
                    absorbInner(statePtr, dataPtr, 11)
                    absorbInner(statePtr, dataPtr, 12)
                    absorbInner(statePtr, dataPtr, 13)
                    absorbInner(statePtr, dataPtr, 14)
                    absorbInner(statePtr, dataPtr, 15)
                    absorbInner(statePtr, dataPtr, 16)
                }
            }
            /// @notice Squeezes the final keccak256 digest from the passed `StateMatrix`.
            function squeeze(StateMatrix memory _stateMatrix) internal pure returns (bytes32 hash_) {
                assembly {
                    // 64 bit logical shift
                    function shl64(a, b) -> val {
                        val := and(shl(a, b), U64_MASK)
                    }
                    // convert a big endian 64-bit value to a little endian 64-bit value.
                    function toLE(beVal) -> leVal {
                        beVal := or(and(shl64(8, beVal), 0xFF00FF00FF00FF00), and(shr(8, beVal), 0x00FF00FF00FF00FF))
                        beVal := or(and(shl64(16, beVal), 0xFFFF0000FFFF0000), and(shr(16, beVal), 0x0000FFFF0000FFFF))
                        leVal := or(shl64(32, beVal), shr(32, beVal))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    let stateMatrixPtr := add(_stateMatrix, 0x20)
                    hash_ :=
                        or(
                            or(shl(192, toLE(stateElem(stateMatrixPtr, 0))), shl(128, toLE(stateElem(stateMatrixPtr, 1)))),
                            or(shl(64, toLE(stateElem(stateMatrixPtr, 2))), toLE(stateElem(stateMatrixPtr, 3)))
                        )
                }
            }
            /// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
            function pad(bytes calldata _data) internal pure returns (bytes memory padded_) {
                assembly {
                    padded_ := mload(0x40)
                    // Grab the original length of `_data`
                    let len := _data.length
                    let dataPtr := add(padded_, 0x20)
                    let endPtr := add(dataPtr, len)
                    // Copy the data into memory.
                    calldatacopy(dataPtr, _data.offset, len)
                    let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
                    switch modBlockSize
                    case false {
                        // Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
                        // not update the free memory pointer when allocating memory, for example with external calls. To do
                        // this, we read out-of-bounds from the calldata, which will always return 0 bytes.
                        calldatacopy(endPtr, calldatasize(), 0x88)
                        // If the input is a perfect multiple of the block size, then we add a full extra block of padding.
                        mstore8(endPtr, 0x01)
                        mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
                        // Update the length of the data to include the padding.
                        mstore(padded_, add(len, BLOCK_SIZE_BYTES))
                    }
                    default {
                        // If the input is not a perfect multiple of the block size, then we add a partial block of padding.
                        // This should entail a set bit after the input, followed by as many zero bits as necessary to fill
                        // the block, followed by a single 1 bit in the lowest-order bit of the final block.
                        let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
                        let newLen := add(len, remaining)
                        let paddedEndPtr := add(dataPtr, newLen)
                        // Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
                        // possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
                        // when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
                        // calldata, which will always return 0 bytes.
                        let partialRemainder := sub(paddedEndPtr, endPtr)
                        calldatacopy(endPtr, calldatasize(), partialRemainder)
                        // Store the padding bits.
                        mstore8(sub(paddedEndPtr, 0x01), 0x80)
                        mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
                        // Update the length of the data to include the padding. The length should be a multiple of the
                        // block size after this.
                        mstore(padded_, newLen)
                    }
                    // Update the free memory pointer.
                    mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
                }
            }
            /// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
            function padMemory(bytes memory _data) internal pure returns (bytes memory padded_) {
                assembly {
                    padded_ := mload(0x40)
                    // Grab the original length of `_data`
                    let len := mload(_data)
                    let dataPtr := add(padded_, 0x20)
                    let endPtr := add(dataPtr, len)
                    // Copy the data.
                    let originalDataPtr := add(_data, 0x20)
                    for { let i := 0x00 } lt(i, len) { i := add(i, 0x20) } {
                        mstore(add(dataPtr, i), mload(add(originalDataPtr, i)))
                    }
                    let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
                    switch modBlockSize
                    case false {
                        // Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
                        // not update the free memory pointer when allocating memory, for example with external calls. To do
                        // this, we read out-of-bounds from the calldata, which will always return 0 bytes.
                        calldatacopy(endPtr, calldatasize(), 0x88)
                        // If the input is a perfect multiple of the block size, then we add a full extra block of padding.
                        mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
                        mstore8(endPtr, 0x01)
                        // Update the length of the data to include the padding.
                        mstore(padded_, add(len, BLOCK_SIZE_BYTES))
                    }
                    default {
                        // If the input is not a perfect multiple of the block size, then we add a partial block of padding.
                        // This should entail a set bit after the input, followed by as many zero bits as necessary to fill
                        // the block, followed by a single 1 bit in the lowest-order bit of the final block.
                        let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
                        let newLen := add(len, remaining)
                        let paddedEndPtr := add(dataPtr, newLen)
                        // Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
                        // possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
                        // when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
                        // calldata, which will always return 0 bytes.
                        let partialRemainder := sub(paddedEndPtr, endPtr)
                        calldatacopy(endPtr, calldatasize(), partialRemainder)
                        // Store the padding bits.
                        mstore8(sub(paddedEndPtr, 0x01), 0x80)
                        mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
                        // Update the length of the data to include the padding. The length should be a multiple of the
                        // block size after this.
                        mstore(padded_, newLen)
                    }
                    // Update the free memory pointer.
                    mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        using LPPMetadataLib for LPPMetaData global;
        /// @notice Packed LPP metadata.
        /// ┌─────────────┬────────────────────────────────────────────┐
        /// │ Bit Offsets │                Description                 │
        /// ├─────────────┼────────────────────────────────────────────┤
        /// │ [0, 64)     │ Timestamp (Finalized - All data available) │
        /// │ [64, 96)    │ Part Offset                                │
        /// │ [96, 128)   │ Claimed Size                               │
        /// │ [128, 160)  │ Blocks Processed (Inclusive of Padding)    │
        /// │ [160, 192)  │ Bytes Processed (Non-inclusive of Padding) │
        /// │ [192, 256)  │ Countered                                  │
        /// └─────────────┴────────────────────────────────────────────┘
        type LPPMetaData is bytes32;
        /// @notice LPP metadata UDT extension functions.
        library LPPMetadataLib {
            uint256 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
            uint256 private constant U32_MASK = 0xFFFFFFFF;
            function setTimestamp(LPPMetaData _self, uint64 _timestamp) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(192, _timestamp), and(_self, not(shl(192, U64_MASK))))
                }
            }
            function setPartOffset(LPPMetaData _self, uint32 _partOffset) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(160, _partOffset), and(_self, not(shl(160, U32_MASK))))
                }
            }
            function setClaimedSize(LPPMetaData _self, uint32 _claimedSize) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(128, _claimedSize), and(_self, not(shl(128, U32_MASK))))
                }
            }
            function setBlocksProcessed(LPPMetaData _self, uint32 _blocksProcessed) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(96, _blocksProcessed), and(_self, not(shl(96, U32_MASK))))
                }
            }
            function setBytesProcessed(LPPMetaData _self, uint32 _bytesProcessed) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(64, _bytesProcessed), and(_self, not(shl(64, U32_MASK))))
                }
            }
            function setCountered(LPPMetaData _self, bool _countered) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(_countered, and(_self, not(U64_MASK)))
                }
            }
            function timestamp(LPPMetaData _self) internal pure returns (uint64 timestamp_) {
                assembly {
                    timestamp_ := shr(192, _self)
                }
            }
            function partOffset(LPPMetaData _self) internal pure returns (uint64 partOffset_) {
                assembly {
                    partOffset_ := and(shr(160, _self), U32_MASK)
                }
            }
            function claimedSize(LPPMetaData _self) internal pure returns (uint32 claimedSize_) {
                assembly {
                    claimedSize_ := and(shr(128, _self), U32_MASK)
                }
            }
            function blocksProcessed(LPPMetaData _self) internal pure returns (uint32 blocksProcessed_) {
                assembly {
                    blocksProcessed_ := and(shr(96, _self), U32_MASK)
                }
            }
            function bytesProcessed(LPPMetaData _self) internal pure returns (uint32 bytesProcessed_) {
                assembly {
                    bytesProcessed_ := and(shr(64, _self), U32_MASK)
                }
            }
            function countered(LPPMetaData _self) internal pure returns (bool countered_) {
                assembly {
                    countered_ := and(_self, U64_MASK)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @custom:attribution https://github.com/bakaoh/solidity-rlp-encode
        /// @title RLPWriter
        /// @author RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh's
        ///         RLPEncode library (https://github.com/bakaoh/solidity-rlp-encode) with minor
        ///         modifications to improve legibility.
        library RLPWriter {
            /// @notice RLP encodes a byte string.
            /// @param _in The byte string to encode.
            /// @return out_ The RLP encoded string in bytes.
            function writeBytes(bytes memory _in) internal pure returns (bytes memory out_) {
                if (_in.length == 1 && uint8(_in[0]) < 128) {
                    out_ = _in;
                } else {
                    out_ = abi.encodePacked(_writeLength(_in.length, 128), _in);
                }
            }
            /// @notice RLP encodes a list of RLP encoded byte byte strings.
            /// @param _in The list of RLP encoded byte strings.
            /// @return list_ The RLP encoded list of items in bytes.
            function writeList(bytes[] memory _in) internal pure returns (bytes memory list_) {
                list_ = _flatten(_in);
                list_ = abi.encodePacked(_writeLength(list_.length, 192), list_);
            }
            /// @notice RLP encodes a string.
            /// @param _in The string to encode.
            /// @return out_ The RLP encoded string in bytes.
            function writeString(string memory _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(bytes(_in));
            }
            /// @notice RLP encodes an address.
            /// @param _in The address to encode.
            /// @return out_ The RLP encoded address in bytes.
            function writeAddress(address _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(abi.encodePacked(_in));
            }
            /// @notice RLP encodes a uint.
            /// @param _in The uint256 to encode.
            /// @return out_ The RLP encoded uint256 in bytes.
            function writeUint(uint256 _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(_toBinary(_in));
            }
            /// @notice RLP encodes a bool.
            /// @param _in The bool to encode.
            /// @return out_ The RLP encoded bool in bytes.
            function writeBool(bool _in) internal pure returns (bytes memory out_) {
                out_ = new bytes(1);
                out_[0] = (_in ? bytes1(0x01) : bytes1(0x80));
            }
            /// @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.
            /// @param _len    The length of the string or the payload.
            /// @param _offset 128 if item is string, 192 if item is list.
            /// @return out_ RLP encoded bytes.
            function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory out_) {
                if (_len < 56) {
                    out_ = new bytes(1);
                    out_[0] = bytes1(uint8(_len) + uint8(_offset));
                } else {
                    uint256 lenLen;
                    uint256 i = 1;
                    while (_len / i != 0) {
                        lenLen++;
                        i *= 256;
                    }
                    out_ = new bytes(lenLen + 1);
                    out_[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
                    for (i = 1; i <= lenLen; i++) {
                        out_[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));
                    }
                }
            }
            /// @notice Encode integer in big endian binary form with no leading zeroes.
            /// @param _x The integer to encode.
            /// @return out_ RLP encoded bytes.
            function _toBinary(uint256 _x) private pure returns (bytes memory out_) {
                bytes memory b = abi.encodePacked(_x);
                uint256 i = 0;
                for (; i < 32; i++) {
                    if (b[i] != 0) {
                        break;
                    }
                }
                out_ = new bytes(32 - i);
                for (uint256 j = 0; j < out_.length; j++) {
                    out_[j] = b[i++];
                }
            }
            /// @custom:attribution https://github.com/Arachnid/solidity-stringutils
            /// @notice Copies a piece of memory to another location.
            /// @param _dest Destination location.
            /// @param _src  Source location.
            /// @param _len  Length of memory to copy.
            function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {
                uint256 dest = _dest;
                uint256 src = _src;
                uint256 len = _len;
                for (; len >= 32; len -= 32) {
                    assembly {
                        mstore(dest, mload(src))
                    }
                    dest += 32;
                    src += 32;
                }
                uint256 mask;
                unchecked {
                    mask = 256 ** (32 - len) - 1;
                }
                assembly {
                    let srcpart := and(mload(src), not(mask))
                    let destpart := and(mload(dest), mask)
                    mstore(dest, or(destpart, srcpart))
                }
            }
            /// @custom:attribution https://github.com/sammayo/solidity-rlp-encoder
            /// @notice Flattens a list of byte strings into one byte string.
            /// @param _list List of byte strings to flatten.
            /// @return out_ The flattened byte string.
            function _flatten(bytes[] memory _list) private pure returns (bytes memory out_) {
                if (_list.length == 0) {
                    return new bytes(0);
                }
                uint256 len;
                uint256 i = 0;
                for (; i < _list.length; i++) {
                    len += _list[i].length;
                }
                out_ = new bytes(len);
                uint256 flattenedPtr;
                assembly {
                    flattenedPtr := add(out_, 0x20)
                }
                for (i = 0; i < _list.length; i++) {
                    bytes memory item = _list[i];
                    uint256 listPtr;
                    assembly {
                        listPtr := add(item, 0x20)
                    }
                    _memcpy(flattenedPtr, listPtr, item.length);
                    flattenedPtr += _list[i].length;
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface IInitializable {
            function initialize() external payable;
        }
        

        File 2 of 4: PermissionedDisputeGame
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        // Contracts
        import { FaultDisputeGame } from "src/dispute/FaultDisputeGame.sol";
        // Libraries
        import { GameType, Claim, Duration } from "src/dispute/lib/Types.sol";
        import { BadAuth } from "src/dispute/lib/Errors.sol";
        // Interfaces
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        import { IBigStepper } from "src/dispute/interfaces/IBigStepper.sol";
        /// @title PermissionedDisputeGame
        /// @notice PermissionedDisputeGame is a contract that inherits from `FaultDisputeGame`, and contains two roles:
        ///         - The `challenger` role, which is allowed to challenge a dispute.
        ///         - The `proposer` role, which is allowed to create proposals and participate in their game.
        ///         This contract exists as a way for networks to support the fault proof iteration of the OptimismPortal
        ///         contract without needing to support a fully permissionless system. Permissionless systems can introduce
        ///         costs that certain networks may not wish to support. This contract can also be used as a fallback mechanism
        ///         in case of a failure in the permissionless fault proof system in the stage one release.
        contract PermissionedDisputeGame is FaultDisputeGame {
            /// @notice The proposer role is allowed to create proposals and participate in the dispute game.
            address internal immutable PROPOSER;
            /// @notice The challenger role is allowed to participate in the dispute game.
            address internal immutable CHALLENGER;
            /// @notice Modifier that gates access to the `challenger` and `proposer` roles.
            modifier onlyAuthorized() {
                if (!(msg.sender == PROPOSER || msg.sender == CHALLENGER)) {
                    revert BadAuth();
                }
                _;
            }
            /// @param _gameType The type ID of the game.
            /// @param _absolutePrestate The absolute prestate of the instruction trace.
            /// @param _maxGameDepth The maximum depth of bisection.
            /// @param _splitDepth The final depth of the output bisection portion of the game.
            /// @param _clockExtension The clock extension to perform when the remaining duration is less than the extension.
            /// @param _maxClockDuration The maximum amount of time that may accumulate on a team's chess clock.
            /// @param _vm An onchain VM that performs single instruction steps on an FPP trace.
            /// @param _weth WETH contract for holding ETH.
            /// @param _anchorStateRegistry The contract that stores the anchor state for each game type.
            /// @param _l2ChainId Chain ID of the L2 network this contract argues about.
            /// @param _proposer Address that is allowed to create instances of this contract.
            /// @param _challenger Address that is allowed to challenge instances of this contract.
            constructor(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId,
                address _proposer,
                address _challenger
            )
                FaultDisputeGame(
                    _gameType,
                    _absolutePrestate,
                    _maxGameDepth,
                    _splitDepth,
                    _clockExtension,
                    _maxClockDuration,
                    _vm,
                    _weth,
                    _anchorStateRegistry,
                    _l2ChainId
                )
            {
                PROPOSER = _proposer;
                CHALLENGER = _challenger;
            }
            /// @inheritdoc FaultDisputeGame
            function step(
                uint256 _claimIndex,
                bool _isAttack,
                bytes calldata _stateData,
                bytes calldata _proof
            )
                public
                override
                onlyAuthorized
            {
                super.step(_claimIndex, _isAttack, _stateData, _proof);
            }
            /// @notice Generic move function, used for both `attack` and `defend` moves.
            /// @notice _disputed The disputed `Claim`.
            /// @param _challengeIndex The index of the claim being moved against. This must match the `_disputed` claim.
            /// @param _claim The claim at the next logical position in the game.
            /// @param _isAttack Whether or not the move is an attack or defense.
            function move(
                Claim _disputed,
                uint256 _challengeIndex,
                Claim _claim,
                bool _isAttack
            )
                public
                payable
                override
                onlyAuthorized
            {
                super.move(_disputed, _challengeIndex, _claim, _isAttack);
            }
            /// @notice Initializes the contract.
            function initialize() public payable override {
                // The creator of the dispute game must be the proposer EOA.
                if (tx.origin != PROPOSER) revert BadAuth();
                // Fallthrough initialization.
                super.initialize();
            }
            ////////////////////////////////////////////////////////////////
            //                     IMMUTABLE GETTERS                      //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the proposer address.
            function proposer() external view returns (address proposer_) {
                proposer_ = PROPOSER;
            }
            /// @notice Returns the challenger address.
            function challenger() external view returns (address challenger_) {
                challenger_ = CHALLENGER;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        // Libraries
        import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
        import { FixedPointMathLib } from "@solady/utils/FixedPointMathLib.sol";
        import { Clone } from "@solady/utils/Clone.sol";
        import { Types } from "src/libraries/Types.sol";
        import { Hashing } from "src/libraries/Hashing.sol";
        import { RLPReader } from "src/libraries/rlp/RLPReader.sol";
        import {
            GameStatus,
            GameType,
            Claim,
            Position,
            Clock,
            Duration,
            Timestamp,
            Hash,
            OutputRoot,
            LibPosition,
            LibClock,
            LocalPreimageKey,
            VMStatuses
        } from "src/dispute/lib/Types.sol";
        import {
            InvalidParent,
            ClaimAlreadyExists,
            ClaimAlreadyResolved,
            OutOfOrderResolution,
            InvalidChallengePeriod,
            InvalidSplitDepth,
            InvalidClockExtension,
            MaxDepthTooLarge,
            AnchorRootNotFound,
            AlreadyInitialized,
            UnexpectedRootClaim,
            GameNotInProgress,
            InvalidPrestate,
            ValidStep,
            GameDepthExceeded,
            L2BlockNumberChallenged,
            InvalidDisputedClaimIndex,
            ClockTimeExceeded,
            DuplicateStep,
            CannotDefendRootClaim,
            IncorrectBondAmount,
            InvalidLocalIdent,
            BlockNumberMatches,
            InvalidHeaderRLP,
            ClockNotExpired,
            BondTransferFailed,
            NoCreditToClaim,
            InvalidOutputRootProof,
            ClaimAboveSplit
        } from "src/dispute/lib/Errors.sol";
        // Interfaces
        import { ISemver } from "src/universal/interfaces/ISemver.sol";
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IBigStepper, IPreimageOracle } from "src/dispute/interfaces/IBigStepper.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        /// @title FaultDisputeGame
        /// @notice An implementation of the `IFaultDisputeGame` interface.
        contract FaultDisputeGame is Clone, ISemver {
            ////////////////////////////////////////////////////////////////
            //                         Structs                            //
            ////////////////////////////////////////////////////////////////
            /// @notice The `ClaimData` struct represents the data associated with a Claim.
            struct ClaimData {
                uint32 parentIndex;
                address counteredBy;
                address claimant;
                uint128 bond;
                Claim claim;
                Position position;
                Clock clock;
            }
            /// @notice The `ResolutionCheckpoint` struct represents the data associated with an in-progress claim resolution.
            struct ResolutionCheckpoint {
                bool initialCheckpointComplete;
                uint32 subgameIndex;
                Position leftmostPosition;
                address counteredBy;
            }
            ////////////////////////////////////////////////////////////////
            //                         Events                             //
            ////////////////////////////////////////////////////////////////
            /// @notice Emitted when the game is resolved.
            /// @param status The status of the game after resolution.
            event Resolved(GameStatus indexed status);
            /// @notice Emitted when a new claim is added to the DAG by `claimant`
            /// @param parentIndex The index within the `claimData` array of the parent claim
            /// @param claim The claim being added
            /// @param claimant The address of the claimant
            event Move(uint256 indexed parentIndex, Claim indexed claim, address indexed claimant);
            ////////////////////////////////////////////////////////////////
            //                         State Vars                         //
            ////////////////////////////////////////////////////////////////
            /// @notice The absolute prestate of the instruction trace. This is a constant that is defined
            ///         by the program that is being used to execute the trace.
            Claim internal immutable ABSOLUTE_PRESTATE;
            /// @notice The max depth of the game.
            uint256 internal immutable MAX_GAME_DEPTH;
            /// @notice The max depth of the output bisection portion of the position tree. Immediately beneath
            ///         this depth, execution trace bisection begins.
            uint256 internal immutable SPLIT_DEPTH;
            /// @notice The maximum duration that may accumulate on a team's chess clock before they may no longer respond.
            Duration internal immutable MAX_CLOCK_DURATION;
            /// @notice An onchain VM that performs single instruction steps on a fault proof program trace.
            IBigStepper internal immutable VM;
            /// @notice The game type ID.
            GameType internal immutable GAME_TYPE;
            /// @notice WETH contract for holding ETH.
            IDelayedWETH internal immutable WETH;
            /// @notice The anchor state registry.
            IAnchorStateRegistry internal immutable ANCHOR_STATE_REGISTRY;
            /// @notice The chain ID of the L2 network this contract argues about.
            uint256 internal immutable L2_CHAIN_ID;
            /// @notice The duration of the clock extension. Will be doubled if the grandchild is the root claim of an execution
            ///         trace bisection subgame.
            Duration internal immutable CLOCK_EXTENSION;
            /// @notice The global root claim's position is always at gindex 1.
            Position internal constant ROOT_POSITION = Position.wrap(1);
            /// @notice The index of the block number in the RLP-encoded block header.
            /// @dev Consensus encoding reference:
            /// https://github.com/paradigmxyz/reth/blob/5f82993c23164ce8ccdc7bf3ae5085205383a5c8/crates/primitives/src/header.rs#L368
            uint256 internal constant HEADER_BLOCK_NUMBER_INDEX = 8;
            /// @notice Semantic version.
            /// @custom:semver 1.3.1
            string public constant version = "1.3.1";
            /// @notice The starting timestamp of the game
            Timestamp public createdAt;
            /// @notice The timestamp of the game's global resolution.
            Timestamp public resolvedAt;
            /// @notice Returns the current status of the game.
            GameStatus public status;
            /// @notice Flag for the `initialize` function to prevent re-initialization.
            bool internal initialized;
            /// @notice Flag for whether or not the L2 block number claim has been invalidated via `challengeRootL2Block`.
            bool public l2BlockNumberChallenged;
            /// @notice The challenger of the L2 block number claim. Should always be `address(0)` if `l2BlockNumberChallenged`
            ///         is `false`. Should be the address of the challenger if `l2BlockNumberChallenged` is `true`.
            address public l2BlockNumberChallenger;
            /// @notice An append-only array of all claims made during the dispute game.
            ClaimData[] public claimData;
            /// @notice Credited balances for winning participants.
            mapping(address => uint256) public credit;
            /// @notice A mapping to allow for constant-time lookups of existing claims.
            mapping(Hash => bool) public claims;
            /// @notice A mapping of subgames rooted at a claim index to other claim indices in the subgame.
            mapping(uint256 => uint256[]) public subgames;
            /// @notice A mapping of resolved subgames rooted at a claim index.
            mapping(uint256 => bool) public resolvedSubgames;
            /// @notice A mapping of claim indices to resolution checkpoints.
            mapping(uint256 => ResolutionCheckpoint) public resolutionCheckpoints;
            /// @notice The latest finalized output root, serving as the anchor for output bisection.
            OutputRoot public startingOutputRoot;
            /// @param _gameType The type ID of the game.
            /// @param _absolutePrestate The absolute prestate of the instruction trace.
            /// @param _maxGameDepth The maximum depth of bisection.
            /// @param _splitDepth The final depth of the output bisection portion of the game.
            /// @param _clockExtension The clock extension to perform when the remaining duration is less than the extension.
            /// @param _maxClockDuration The maximum amount of time that may accumulate on a team's chess clock.
            /// @param _vm An onchain VM that performs single instruction steps on an FPP trace.
            /// @param _weth WETH contract for holding ETH.
            /// @param _anchorStateRegistry The contract that stores the anchor state for each game type.
            /// @param _l2ChainId Chain ID of the L2 network this contract argues about.
            constructor(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId
            ) {
                // The max game depth may not be greater than `LibPosition.MAX_POSITION_BITLEN - 1`.
                if (_maxGameDepth > LibPosition.MAX_POSITION_BITLEN - 1) revert MaxDepthTooLarge();
                // The split depth plus one cannot be greater than or equal to the max game depth. We add
                // an additional depth to the split depth to avoid a bug in trace ancestor lookup. We know
                // that the case where the split depth is the max value for uint256 is equivalent to the
                // second check though we do need to check it explicitly to avoid an overflow.
                if (_splitDepth == type(uint256).max || _splitDepth + 1 >= _maxGameDepth) revert InvalidSplitDepth();
                // The split depth cannot be 0 or 1 to stay in bounds of clock extension arithmetic.
                if (_splitDepth < 2) revert InvalidSplitDepth();
                // The PreimageOracle challenge period must fit into uint64 so we can safely use it here.
                // Runtime check was added instead of changing the ABI since the contract is already
                // deployed in production. We perform the same check within the PreimageOracle for the
                // benefit of developers but also perform this check here defensively.
                if (_vm.oracle().challengePeriod() > type(uint64).max) revert InvalidChallengePeriod();
                // Determine the maximum clock extension which is either the split depth extension or the
                // maximum game depth extension depending on the configuration of these contracts.
                uint256 splitDepthExtension = uint256(_clockExtension.raw()) * 2;
                uint256 maxGameDepthExtension = uint256(_clockExtension.raw()) + uint256(_vm.oracle().challengePeriod());
                uint256 maxClockExtension = Math.max(splitDepthExtension, maxGameDepthExtension);
                // The maximum clock extension must fit into a uint64.
                if (maxClockExtension > type(uint64).max) revert InvalidClockExtension();
                // The maximum clock extension may not be greater than the maximum clock duration.
                if (uint64(maxClockExtension) > _maxClockDuration.raw()) revert InvalidClockExtension();
                // Set up initial game state.
                GAME_TYPE = _gameType;
                ABSOLUTE_PRESTATE = _absolutePrestate;
                MAX_GAME_DEPTH = _maxGameDepth;
                SPLIT_DEPTH = _splitDepth;
                CLOCK_EXTENSION = _clockExtension;
                MAX_CLOCK_DURATION = _maxClockDuration;
                VM = _vm;
                WETH = _weth;
                ANCHOR_STATE_REGISTRY = _anchorStateRegistry;
                L2_CHAIN_ID = _l2ChainId;
            }
            /// @notice Initializes the contract.
            /// @dev This function may only be called once.
            function initialize() public payable virtual {
                // SAFETY: Any revert in this function will bubble up to the DisputeGameFactory and
                // prevent the game from being created.
                //
                // Implicit assumptions:
                // - The `gameStatus` state variable defaults to 0, which is `GameStatus.IN_PROGRESS`
                // - The dispute game factory will enforce the required bond to initialize the game.
                //
                // Explicit checks:
                // - The game must not have already been initialized.
                // - An output root cannot be proposed at or before the starting block number.
                // INVARIANT: The game must not have already been initialized.
                if (initialized) revert AlreadyInitialized();
                // Grab the latest anchor root.
                (Hash root, uint256 rootBlockNumber) = ANCHOR_STATE_REGISTRY.anchors(GAME_TYPE);
                // Should only happen if this is a new game type that hasn't been set up yet.
                if (root.raw() == bytes32(0)) revert AnchorRootNotFound();
                // Set the starting output root.
                startingOutputRoot = OutputRoot({ l2BlockNumber: rootBlockNumber, root: root });
                // Revert if the calldata size is not the expected length.
                //
                // This is to prevent adding extra or omitting bytes from to `extraData` that result in a different game UUID
                // in the factory, but are not used by the game, which would allow for multiple dispute games for the same
                // output proposal to be created.
                //
                // Expected length: 0x7A
                // - 0x04 selector
                // - 0x14 creator address
                // - 0x20 root claim
                // - 0x20 l1 head
                // - 0x20 extraData
                // - 0x02 CWIA bytes
                assembly {
                    if iszero(eq(calldatasize(), 0x7A)) {
                        // Store the selector for `BadExtraData()` & revert
                        mstore(0x00, 0x9824bdab)
                        revert(0x1C, 0x04)
                    }
                }
                // Do not allow the game to be initialized if the root claim corresponds to a block at or before the
                // configured starting block number.
                if (l2BlockNumber() <= rootBlockNumber) revert UnexpectedRootClaim(rootClaim());
                // Set the root claim
                claimData.push(
                    ClaimData({
                        parentIndex: type(uint32).max,
                        counteredBy: address(0),
                        claimant: gameCreator(),
                        bond: uint128(msg.value),
                        claim: rootClaim(),
                        position: ROOT_POSITION,
                        clock: LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp)))
                    })
                );
                // Set the game as initialized.
                initialized = true;
                // Deposit the bond.
                WETH.deposit{ value: msg.value }();
                // Set the game's starting timestamp
                createdAt = Timestamp.wrap(uint64(block.timestamp));
            }
            ////////////////////////////////////////////////////////////////
            //                  `IFaultDisputeGame` impl                  //
            ////////////////////////////////////////////////////////////////
            /// @notice Perform an instruction step via an on-chain fault proof processor.
            /// @dev This function should point to a fault proof processor in order to execute
            ///      a step in the fault proof program on-chain. The interface of the fault proof
            ///      processor contract should adhere to the `IBigStepper` interface.
            /// @param _claimIndex The index of the challenged claim within `claimData`.
            /// @param _isAttack Whether or not the step is an attack or a defense.
            /// @param _stateData The stateData of the step is the preimage of the claim at the given
            ///        prestate, which is at `_stateIndex` if the move is an attack and `_claimIndex` if
            ///        the move is a defense. If the step is an attack on the first instruction, it is
            ///        the absolute prestate of the fault proof VM.
            /// @param _proof Proof to access memory nodes in the VM's merkle state tree.
            function step(
                uint256 _claimIndex,
                bool _isAttack,
                bytes calldata _stateData,
                bytes calldata _proof
            )
                public
                virtual
            {
                // INVARIANT: Steps cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // Get the parent. If it does not exist, the call will revert with OOB.
                ClaimData storage parent = claimData[_claimIndex];
                // Pull the parent position out of storage.
                Position parentPos = parent.position;
                // Determine the position of the step.
                Position stepPos = parentPos.move(_isAttack);
                // INVARIANT: A step cannot be made unless the move position is 1 below the `MAX_GAME_DEPTH`
                if (stepPos.depth() != MAX_GAME_DEPTH + 1) revert InvalidParent();
                // Determine the expected pre & post states of the step.
                Claim preStateClaim;
                ClaimData storage postState;
                if (_isAttack) {
                    // If the step position's index at depth is 0, the prestate is the absolute
                    // prestate.
                    // If the step is an attack at a trace index > 0, the prestate exists elsewhere in
                    // the game state.
                    // NOTE: We localize the `indexAtDepth` for the current execution trace subgame by finding
                    //       the remainder of the index at depth divided by 2 ** (MAX_GAME_DEPTH - SPLIT_DEPTH),
                    //       which is the number of leaves in each execution trace subgame. This is so that we can
                    //       determine whether or not the step position is represents the `ABSOLUTE_PRESTATE`.
                    preStateClaim = (stepPos.indexAtDepth() % (1 << (MAX_GAME_DEPTH - SPLIT_DEPTH))) == 0
                        ? ABSOLUTE_PRESTATE
                        : _findTraceAncestor(Position.wrap(parentPos.raw() - 1), parent.parentIndex, false).claim;
                    // For all attacks, the poststate is the parent claim.
                    postState = parent;
                } else {
                    // If the step is a defense, the poststate exists elsewhere in the game state,
                    // and the parent claim is the expected pre-state.
                    preStateClaim = parent.claim;
                    postState = _findTraceAncestor(Position.wrap(parentPos.raw() + 1), parent.parentIndex, false);
                }
                // INVARIANT: The prestate is always invalid if the passed `_stateData` is not the
                //            preimage of the prestate claim hash.
                //            We ignore the highest order byte of the digest because it is used to
                //            indicate the VM Status and is added after the digest is computed.
                if (keccak256(_stateData) << 8 != preStateClaim.raw() << 8) revert InvalidPrestate();
                // Compute the local preimage context for the step.
                Hash uuid = _findLocalContext(_claimIndex);
                // INVARIANT: If a step is an attack, the poststate is valid if the step produces
                //            the same poststate hash as the parent claim's value.
                //            If a step is a defense:
                //              1. If the parent claim and the found post state agree with each other
                //                 (depth diff % 2 == 0), the step is valid if it produces the same
                //                 state hash as the post state's claim.
                //              2. If the parent claim and the found post state disagree with each other
                //                 (depth diff % 2 != 0), the parent cannot be countered unless the step
                //                 produces the same state hash as `postState.claim`.
                // SAFETY:    While the `attack` path does not need an extra check for the post
                //            state's depth in relation to the parent, we don't need another
                //            branch because (n - n) % 2 == 0.
                bool validStep = VM.step(_stateData, _proof, uuid.raw()) == postState.claim.raw();
                bool parentPostAgree = (parentPos.depth() - postState.position.depth()) % 2 == 0;
                if (parentPostAgree == validStep) revert ValidStep();
                // INVARIANT: A step cannot be made against a claim for a second time.
                if (parent.counteredBy != address(0)) revert DuplicateStep();
                // Set the parent claim as countered. We do not need to append a new claim to the game;
                // instead, we can just set the existing parent as countered.
                parent.counteredBy = msg.sender;
            }
            /// @notice Generic move function, used for both `attack` and `defend` moves.
            /// @param _disputed The disputed `Claim`.
            /// @param _challengeIndex The index of the claim being moved against.
            /// @param _claim The claim at the next logical position in the game.
            /// @param _isAttack Whether or not the move is an attack or defense.
            function move(Claim _disputed, uint256 _challengeIndex, Claim _claim, bool _isAttack) public payable virtual {
                // INVARIANT: Moves cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // Get the parent. If it does not exist, the call will revert with OOB.
                ClaimData memory parent = claimData[_challengeIndex];
                // INVARIANT: The claim at the _challengeIndex must be the disputed claim.
                if (Claim.unwrap(parent.claim) != Claim.unwrap(_disputed)) revert InvalidDisputedClaimIndex();
                // Compute the position that the claim commits to. Because the parent's position is already
                // known, we can compute the next position by moving left or right depending on whether
                // or not the move is an attack or defense.
                Position parentPos = parent.position;
                Position nextPosition = parentPos.move(_isAttack);
                uint256 nextPositionDepth = nextPosition.depth();
                // INVARIANT: A defense can never be made against the root claim of either the output root game or any
                //            of the execution trace bisection subgames. This is because the root claim commits to the
                //            entire state. Therefore, the only valid defense is to do nothing if it is agreed with.
                if ((_challengeIndex == 0 || nextPositionDepth == SPLIT_DEPTH + 2) && !_isAttack) {
                    revert CannotDefendRootClaim();
                }
                // INVARIANT: No moves against the root claim can be made after it has been challenged with
                //            `challengeRootL2Block`.`
                if (l2BlockNumberChallenged && _challengeIndex == 0) revert L2BlockNumberChallenged();
                // INVARIANT: A move can never surpass the `MAX_GAME_DEPTH`. The only option to counter a
                //            claim at this depth is to perform a single instruction step on-chain via
                //            the `step` function to prove that the state transition produces an unexpected
                //            post-state.
                if (nextPositionDepth > MAX_GAME_DEPTH) revert GameDepthExceeded();
                // When the next position surpasses the split depth (i.e., it is the root claim of an execution
                // trace bisection sub-game), we need to perform some extra verification steps.
                if (nextPositionDepth == SPLIT_DEPTH + 1) {
                    _verifyExecBisectionRoot(_claim, _challengeIndex, parentPos, _isAttack);
                }
                // INVARIANT: The `msg.value` must exactly equal the required bond.
                if (getRequiredBond(nextPosition) != msg.value) revert IncorrectBondAmount();
                // Compute the duration of the next clock. This is done by adding the duration of the
                // grandparent claim to the difference between the current block timestamp and the
                // parent's clock timestamp.
                Duration nextDuration = getChallengerDuration(_challengeIndex);
                // INVARIANT: A move can never be made once its clock has exceeded `MAX_CLOCK_DURATION`
                //            seconds of time.
                if (nextDuration.raw() == MAX_CLOCK_DURATION.raw()) revert ClockTimeExceeded();
                // Clock extension is a mechanism that automatically extends the clock for a potential
                // grandchild claim when there would be less than the clock extension time left if a player
                // is forced to inherit another team's clock when countering a freeloader claim. Exact
                // amount of clock extension time depends exactly where we are within the game.
                uint64 actualExtension;
                if (nextPositionDepth == MAX_GAME_DEPTH - 1) {
                    // If the next position is `MAX_GAME_DEPTH - 1` then we're about to execute a step. Our
                    // clock extension must therefore account for the LPP challenge period in addition to
                    // the standard clock extension.
                    actualExtension = CLOCK_EXTENSION.raw() + uint64(VM.oracle().challengePeriod());
                } else if (nextPositionDepth == SPLIT_DEPTH - 1) {
                    // If the next position is `SPLIT_DEPTH - 1` then we're about to begin an execution
                    // trace bisection and we need to give extra time for the off-chain challenge agent to
                    // be able to generate the initial instruction trace on the native FPVM.
                    actualExtension = CLOCK_EXTENSION.raw() * 2;
                } else {
                    // Otherwise, we just use the standard clock extension.
                    actualExtension = CLOCK_EXTENSION.raw();
                }
                // Check if we need to apply the clock extension.
                if (nextDuration.raw() > MAX_CLOCK_DURATION.raw() - actualExtension) {
                    nextDuration = Duration.wrap(MAX_CLOCK_DURATION.raw() - actualExtension);
                }
                // Construct the next clock with the new duration and the current block timestamp.
                Clock nextClock = LibClock.wrap(nextDuration, Timestamp.wrap(uint64(block.timestamp)));
                // INVARIANT: There cannot be multiple identical claims with identical moves on the same challengeIndex. Multiple
                //            claims at the same position may dispute the same challengeIndex. However, they must have different
                //            values.
                Hash claimHash = _claim.hashClaimPos(nextPosition, _challengeIndex);
                if (claims[claimHash]) revert ClaimAlreadyExists();
                claims[claimHash] = true;
                // Create the new claim.
                claimData.push(
                    ClaimData({
                        parentIndex: uint32(_challengeIndex),
                        // This is updated during subgame resolution
                        counteredBy: address(0),
                        claimant: msg.sender,
                        bond: uint128(msg.value),
                        claim: _claim,
                        position: nextPosition,
                        clock: nextClock
                    })
                );
                // Update the subgame rooted at the parent claim.
                subgames[_challengeIndex].push(claimData.length - 1);
                // Deposit the bond.
                WETH.deposit{ value: msg.value }();
                // Emit the appropriate event for the attack or defense.
                emit Move(_challengeIndex, _claim, msg.sender);
            }
            /// @notice Attack a disagreed upon `Claim`.
            /// @param _disputed The `Claim` being attacked.
            /// @param _parentIndex Index of the `Claim` to attack in the `claimData` array. This must match the `_disputed`
            /// claim.
            /// @param _claim The `Claim` at the relative attack position.
            function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
                move(_disputed, _parentIndex, _claim, true);
            }
            /// @notice Defend an agreed upon `Claim`.
            /// @notice _disputed The `Claim` being defended.
            /// @param _parentIndex Index of the claim to defend in the `claimData` array. This must match the `_disputed`
            /// claim.
            /// @param _claim The `Claim` at the relative defense position.
            function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
                move(_disputed, _parentIndex, _claim, false);
            }
            /// @notice Posts the requested local data to the VM's `PreimageOralce`.
            /// @param _ident The local identifier of the data to post.
            /// @param _execLeafIdx The index of the leaf claim in an execution subgame that requires the local data for a step.
            /// @param _partOffset The offset of the data to post.
            function addLocalData(uint256 _ident, uint256 _execLeafIdx, uint256 _partOffset) external {
                // INVARIANT: Local data can only be added if the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                (Claim starting, Position startingPos, Claim disputed, Position disputedPos) =
                    _findStartingAndDisputedOutputs(_execLeafIdx);
                Hash uuid = _computeLocalContext(starting, startingPos, disputed, disputedPos);
                IPreimageOracle oracle = VM.oracle();
                if (_ident == LocalPreimageKey.L1_HEAD_HASH) {
                    // Load the L1 head hash
                    oracle.loadLocalData(_ident, uuid.raw(), l1Head().raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.STARTING_OUTPUT_ROOT) {
                    // Load the starting proposal's output root.
                    oracle.loadLocalData(_ident, uuid.raw(), starting.raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.DISPUTED_OUTPUT_ROOT) {
                    // Load the disputed proposal's output root
                    oracle.loadLocalData(_ident, uuid.raw(), disputed.raw(), 32, _partOffset);
                } else if (_ident == LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER) {
                    // Load the disputed proposal's L2 block number as a big-endian uint64 in the
                    // high order 8 bytes of the word.
                    // We add the index at depth + 1 to the starting block number to get the disputed L2
                    // block number.
                    uint256 l2Number = startingOutputRoot.l2BlockNumber + disputedPos.traceIndex(SPLIT_DEPTH) + 1;
                    // Choose the minimum between the `l2BlockNumber` claim and the bisected-to L2 block number.
                    l2Number = l2Number < l2BlockNumber() ? l2Number : l2BlockNumber();
                    oracle.loadLocalData(_ident, uuid.raw(), bytes32(l2Number << 0xC0), 8, _partOffset);
                } else if (_ident == LocalPreimageKey.CHAIN_ID) {
                    // Load the chain ID as a big-endian uint64 in the high order 8 bytes of the word.
                    oracle.loadLocalData(_ident, uuid.raw(), bytes32(L2_CHAIN_ID << 0xC0), 8, _partOffset);
                } else {
                    revert InvalidLocalIdent();
                }
            }
            /// @notice Returns the number of children that still need to be resolved in order to fully resolve a subgame rooted
            ///         at `_claimIndex`.
            /// @param _claimIndex The subgame root claim's index within `claimData`.
            /// @return numRemainingChildren_ The number of children that still need to be checked to resolve the subgame.
            function getNumToResolve(uint256 _claimIndex) public view returns (uint256 numRemainingChildren_) {
                ResolutionCheckpoint storage checkpoint = resolutionCheckpoints[_claimIndex];
                uint256[] storage challengeIndices = subgames[_claimIndex];
                uint256 challengeIndicesLen = challengeIndices.length;
                numRemainingChildren_ = challengeIndicesLen - checkpoint.subgameIndex;
            }
            /// @notice The l2BlockNumber of the disputed output root in the `L2OutputOracle`.
            function l2BlockNumber() public pure returns (uint256 l2BlockNumber_) {
                l2BlockNumber_ = _getArgUint256(0x54);
            }
            /// @notice Only the starting block number of the game.
            function startingBlockNumber() external view returns (uint256 startingBlockNumber_) {
                startingBlockNumber_ = startingOutputRoot.l2BlockNumber;
            }
            /// @notice Starting output root and block number of the game.
            function startingRootHash() external view returns (Hash startingRootHash_) {
                startingRootHash_ = startingOutputRoot.root;
            }
            /// @notice Challenges the root L2 block number by providing the preimage of the output root and the L2 block header
            ///         and showing that the committed L2 block number is incorrect relative to the claimed L2 block number.
            /// @param _outputRootProof The output root proof.
            /// @param _headerRLP The RLP-encoded L2 block header.
            function challengeRootL2Block(
                Types.OutputRootProof calldata _outputRootProof,
                bytes calldata _headerRLP
            )
                external
            {
                // INVARIANT: Moves cannot be made unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // The root L2 block claim can only be challenged once.
                if (l2BlockNumberChallenged) revert L2BlockNumberChallenged();
                // Verify the output root preimage.
                if (Hashing.hashOutputRootProof(_outputRootProof) != rootClaim().raw()) revert InvalidOutputRootProof();
                // Verify the block hash preimage.
                if (keccak256(_headerRLP) != _outputRootProof.latestBlockhash) revert InvalidHeaderRLP();
                // Decode the header RLP to find the number of the block. In the consensus encoding, the timestamp
                // is the 9th element in the list that represents the block header.
                RLPReader.RLPItem[] memory headerContents = RLPReader.readList(RLPReader.toRLPItem(_headerRLP));
                bytes memory rawBlockNumber = RLPReader.readBytes(headerContents[HEADER_BLOCK_NUMBER_INDEX]);
                // Sanity check the block number string length.
                if (rawBlockNumber.length > 32) revert InvalidHeaderRLP();
                // Convert the raw, left-aligned block number to a uint256 by aligning it as a big-endian
                // number in the low-order bytes of a 32-byte word.
                //
                // SAFETY: The length of `rawBlockNumber` is checked above to ensure it is at most 32 bytes.
                uint256 blockNumber;
                assembly {
                    blockNumber := shr(shl(0x03, sub(0x20, mload(rawBlockNumber))), mload(add(rawBlockNumber, 0x20)))
                }
                // Ensure the block number does not match the block number claimed in the dispute game.
                if (blockNumber == l2BlockNumber()) revert BlockNumberMatches();
                // Issue a special counter to the root claim. This counter will always win the root claim subgame, and receive
                // the bond from the root claimant.
                l2BlockNumberChallenger = msg.sender;
                l2BlockNumberChallenged = true;
            }
            ////////////////////////////////////////////////////////////////
            //                    `IDisputeGame` impl                     //
            ////////////////////////////////////////////////////////////////
            /// @notice If all necessary information has been gathered, this function should mark the game
            ///         status as either `CHALLENGER_WINS` or `DEFENDER_WINS` and return the status of
            ///         the resolved game. It is at this stage that the bonds should be awarded to the
            ///         necessary parties.
            /// @dev May only be called if the `status` is `IN_PROGRESS`.
            /// @return status_ The status of the game after resolution.
            function resolve() external returns (GameStatus status_) {
                // INVARIANT: Resolution cannot occur unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                // INVARIANT: Resolution cannot occur unless the absolute root subgame has been resolved.
                if (!resolvedSubgames[0]) revert OutOfOrderResolution();
                // Update the global game status; The dispute has concluded.
                status_ = claimData[0].counteredBy == address(0) ? GameStatus.DEFENDER_WINS : GameStatus.CHALLENGER_WINS;
                resolvedAt = Timestamp.wrap(uint64(block.timestamp));
                // Update the status and emit the resolved event, note that we're performing an assignment here.
                emit Resolved(status = status_);
                // Try to update the anchor state, this should not revert.
                ANCHOR_STATE_REGISTRY.tryUpdateAnchorState();
            }
            /// @notice Resolves the subgame rooted at the given claim index. `_numToResolve` specifies how many children of
            ///         the subgame will be checked in this call. If `_numToResolve` is less than the number of children, an
            ///         internal cursor will be updated and this function may be called again to complete resolution of the
            ///         subgame.
            /// @dev This function must be called bottom-up in the DAG
            ///      A subgame is a tree of claims that has a maximum depth of 1.
            ///      A subgame root claims is valid if, and only if, all of its child claims are invalid.
            ///      At the deepest level in the DAG, a claim is invalid if there's a successful step against it.
            /// @param _claimIndex The index of the subgame root claim to resolve.
            /// @param _numToResolve The number of subgames to resolve in this call. If the input is `0`, and this is the first
            ///                      page, this function will attempt to check all of the subgame's children at once.
            function resolveClaim(uint256 _claimIndex, uint256 _numToResolve) external {
                // INVARIANT: Resolution cannot occur unless the game is currently in progress.
                if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
                ClaimData storage subgameRootClaim = claimData[_claimIndex];
                Duration challengeClockDuration = getChallengerDuration(_claimIndex);
                // INVARIANT: Cannot resolve a subgame unless the clock of its would-be counter has expired
                // INVARIANT: Assuming ordered subgame resolution, challengeClockDuration is always >= MAX_CLOCK_DURATION if all
                // descendant subgames are resolved
                if (challengeClockDuration.raw() < MAX_CLOCK_DURATION.raw()) revert ClockNotExpired();
                // INVARIANT: Cannot resolve a subgame twice.
                if (resolvedSubgames[_claimIndex]) revert ClaimAlreadyResolved();
                uint256[] storage challengeIndices = subgames[_claimIndex];
                uint256 challengeIndicesLen = challengeIndices.length;
                // Uncontested claims are resolved implicitly unless they are the root claim. Pay out the bond to the claimant
                // and return early.
                if (challengeIndicesLen == 0 && _claimIndex != 0) {
                    // In the event that the parent claim is at the max depth, there will always be 0 subgames. If the
                    // `counteredBy` field is set and there are no subgames, this implies that the parent claim was successfully
                    // stepped against. In this case, we pay out the bond to the party that stepped against the parent claim.
                    // Otherwise, the parent claim is uncontested, and the bond is returned to the claimant.
                    address counteredBy = subgameRootClaim.counteredBy;
                    address recipient = counteredBy == address(0) ? subgameRootClaim.claimant : counteredBy;
                    _distributeBond(recipient, subgameRootClaim);
                    resolvedSubgames[_claimIndex] = true;
                    return;
                }
                // Fetch the resolution checkpoint from storage.
                ResolutionCheckpoint memory checkpoint = resolutionCheckpoints[_claimIndex];
                // If the checkpoint does not currently exist, initialize the current left most position as max u128.
                if (!checkpoint.initialCheckpointComplete) {
                    checkpoint.leftmostPosition = Position.wrap(type(uint128).max);
                    checkpoint.initialCheckpointComplete = true;
                    // If `_numToResolve == 0`, assume that we can check all child subgames in this one callframe.
                    if (_numToResolve == 0) _numToResolve = challengeIndicesLen;
                }
                // Assume parent is honest until proven otherwise
                uint256 lastToResolve = checkpoint.subgameIndex + _numToResolve;
                uint256 finalCursor = lastToResolve > challengeIndicesLen ? challengeIndicesLen : lastToResolve;
                for (uint256 i = checkpoint.subgameIndex; i < finalCursor; i++) {
                    uint256 challengeIndex = challengeIndices[i];
                    // INVARIANT: Cannot resolve a subgame containing an unresolved claim
                    if (!resolvedSubgames[challengeIndex]) revert OutOfOrderResolution();
                    ClaimData storage claim = claimData[challengeIndex];
                    // If the child subgame is uncountered and further left than the current left-most counter,
                    // update the parent subgame's `countered` address and the current `leftmostCounter`.
                    // The left-most correct counter is preferred in bond payouts in order to discourage attackers
                    // from countering invalid subgame roots via an invalid defense position. As such positions
                    // cannot be correctly countered.
                    // Note that correctly positioned defense, but invalid claimes can still be successfully countered.
                    if (claim.counteredBy == address(0) && checkpoint.leftmostPosition.raw() > claim.position.raw()) {
                        checkpoint.counteredBy = claim.claimant;
                        checkpoint.leftmostPosition = claim.position;
                    }
                }
                // Increase the checkpoint's cursor position by the number of children that were checked.
                checkpoint.subgameIndex = uint32(finalCursor);
                // Persist the checkpoint and allow for continuing in a separate transaction, if resolution is not already
                // complete.
                resolutionCheckpoints[_claimIndex] = checkpoint;
                // If all children have been traversed in the above loop, the subgame may be resolved. Otherwise, persist the
                // checkpoint and allow for continuation in a separate transaction.
                if (checkpoint.subgameIndex == challengeIndicesLen) {
                    address countered = checkpoint.counteredBy;
                    // Mark the subgame as resolved.
                    resolvedSubgames[_claimIndex] = true;
                    // Distribute the bond to the appropriate party.
                    if (_claimIndex == 0 && l2BlockNumberChallenged) {
                        // Special case: If the root claim has been challenged with the `challengeRootL2Block` function,
                        // the bond is always paid out to the issuer of that challenge.
                        address challenger = l2BlockNumberChallenger;
                        _distributeBond(challenger, subgameRootClaim);
                        subgameRootClaim.counteredBy = challenger;
                    } else {
                        // If the parent was not successfully countered, pay out the parent's bond to the claimant.
                        // If the parent was successfully countered, pay out the parent's bond to the challenger.
                        _distributeBond(countered == address(0) ? subgameRootClaim.claimant : countered, subgameRootClaim);
                        // Once a subgame is resolved, we percolate the result up the DAG so subsequent calls to
                        // resolveClaim will not need to traverse this subgame.
                        subgameRootClaim.counteredBy = countered;
                    }
                }
            }
            /// @notice Getter for the game type.
            /// @dev The reference impl should be entirely different depending on the type (fault, validity)
            ///      i.e. The game type should indicate the security model.
            /// @return gameType_ The type of proof system being used.
            function gameType() public view returns (GameType gameType_) {
                gameType_ = GAME_TYPE;
            }
            /// @notice Getter for the creator of the dispute game.
            /// @dev `clones-with-immutable-args` argument #1
            /// @return creator_ The creator of the dispute game.
            function gameCreator() public pure returns (address creator_) {
                creator_ = _getArgAddress(0x00);
            }
            /// @notice Getter for the root claim.
            /// @dev `clones-with-immutable-args` argument #2
            /// @return rootClaim_ The root claim of the DisputeGame.
            function rootClaim() public pure returns (Claim rootClaim_) {
                rootClaim_ = Claim.wrap(_getArgBytes32(0x14));
            }
            /// @notice Getter for the parent hash of the L1 block when the dispute game was created.
            /// @dev `clones-with-immutable-args` argument #3
            /// @return l1Head_ The parent hash of the L1 block when the dispute game was created.
            function l1Head() public pure returns (Hash l1Head_) {
                l1Head_ = Hash.wrap(_getArgBytes32(0x34));
            }
            /// @notice Getter for the extra data.
            /// @dev `clones-with-immutable-args` argument #4
            /// @return extraData_ Any extra data supplied to the dispute game contract by the creator.
            function extraData() public pure returns (bytes memory extraData_) {
                // The extra data starts at the second word within the cwia calldata and
                // is 32 bytes long.
                extraData_ = _getArgBytes(0x54, 0x20);
            }
            /// @notice A compliant implementation of this interface should return the components of the
            ///         game UUID's preimage provided in the cwia payload. The preimage of the UUID is
            ///         constructed as `keccak256(gameType . rootClaim . extraData)` where `.` denotes
            ///         concatenation.
            /// @return gameType_ The type of proof system being used.
            /// @return rootClaim_ The root claim of the DisputeGame.
            /// @return extraData_ Any extra data supplied to the dispute game contract by the creator.
            function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_) {
                gameType_ = gameType();
                rootClaim_ = rootClaim();
                extraData_ = extraData();
            }
            ////////////////////////////////////////////////////////////////
            //                       MISC EXTERNAL                        //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the required bond for a given move kind.
            /// @param _position The position of the bonded interaction.
            /// @return requiredBond_ The required ETH bond for the given move, in wei.
            function getRequiredBond(Position _position) public view returns (uint256 requiredBond_) {
                uint256 depth = uint256(_position.depth());
                if (depth > MAX_GAME_DEPTH) revert GameDepthExceeded();
                // Values taken from Big Bonds v1.5 (TM) spec.
                uint256 assumedBaseFee = 200 gwei;
                uint256 baseGasCharged = 400_000;
                uint256 highGasCharged = 300_000_000;
                // Goal here is to compute the fixed multiplier that will be applied to the base gas
                // charged to get the required gas amount for the given depth. We apply this multiplier
                // some `n` times where `n` is the depth of the position. We are looking for some number
                // that, when multiplied by itself `MAX_GAME_DEPTH` times and then multiplied by the base
                // gas charged, will give us the maximum gas that we want to charge.
                // We want to solve for (highGasCharged/baseGasCharged) ** (1/MAX_GAME_DEPTH).
                // We know that a ** (b/c) is equal to e ** (ln(a) * (b/c)).
                // We can compute e ** (ln(a) * (b/c)) quite easily with FixedPointMathLib.
                // Set up a, b, and c.
                uint256 a = highGasCharged / baseGasCharged;
                uint256 b = FixedPointMathLib.WAD;
                uint256 c = MAX_GAME_DEPTH * FixedPointMathLib.WAD;
                // Compute ln(a).
                // slither-disable-next-line divide-before-multiply
                uint256 lnA = uint256(FixedPointMathLib.lnWad(int256(a * FixedPointMathLib.WAD)));
                // Computes (b / c) with full precision using WAD = 1e18.
                uint256 bOverC = FixedPointMathLib.divWad(b, c);
                // Compute e ** (ln(a) * (b/c))
                // sMulWad can be used here since WAD = 1e18 maintains the same precision.
                uint256 numerator = FixedPointMathLib.mulWad(lnA, bOverC);
                int256 base = FixedPointMathLib.expWad(int256(numerator));
                // Compute the required gas amount.
                int256 rawGas = FixedPointMathLib.powWad(base, int256(depth * FixedPointMathLib.WAD));
                uint256 requiredGas = FixedPointMathLib.mulWad(baseGasCharged, uint256(rawGas));
                // Compute the required bond.
                requiredBond_ = assumedBaseFee * requiredGas;
            }
            /// @notice Claim the credit belonging to the recipient address.
            /// @param _recipient The owner and recipient of the credit.
            function claimCredit(address _recipient) external {
                // Remove the credit from the recipient prior to performing the external call.
                uint256 recipientCredit = credit[_recipient];
                credit[_recipient] = 0;
                // Revert if the recipient has no credit to claim.
                if (recipientCredit == 0) revert NoCreditToClaim();
                // Try to withdraw the WETH amount so it can be used here.
                WETH.withdraw(_recipient, recipientCredit);
                // Transfer the credit to the recipient.
                (bool success,) = _recipient.call{ value: recipientCredit }(hex"");
                if (!success) revert BondTransferFailed();
            }
            /// @notice Returns the amount of time elapsed on the potential challenger to `_claimIndex`'s chess clock. Maxes
            ///         out at `MAX_CLOCK_DURATION`.
            /// @param _claimIndex The index of the subgame root claim.
            /// @return duration_ The time elapsed on the potential challenger to `_claimIndex`'s chess clock.
            function getChallengerDuration(uint256 _claimIndex) public view returns (Duration duration_) {
                // INVARIANT: The game must be in progress to query the remaining time to respond to a given claim.
                if (status != GameStatus.IN_PROGRESS) {
                    revert GameNotInProgress();
                }
                // Fetch the subgame root claim.
                ClaimData storage subgameRootClaim = claimData[_claimIndex];
                // Fetch the parent of the subgame root's clock, if it exists.
                Clock parentClock;
                if (subgameRootClaim.parentIndex != type(uint32).max) {
                    parentClock = claimData[subgameRootClaim.parentIndex].clock;
                }
                // Compute the duration elapsed of the potential challenger's clock.
                uint64 challengeDuration =
                    uint64(parentClock.duration().raw() + (block.timestamp - subgameRootClaim.clock.timestamp().raw()));
                duration_ = challengeDuration > MAX_CLOCK_DURATION.raw() ? MAX_CLOCK_DURATION : Duration.wrap(challengeDuration);
            }
            /// @notice Returns the length of the `claimData` array.
            function claimDataLen() external view returns (uint256 len_) {
                len_ = claimData.length;
            }
            ////////////////////////////////////////////////////////////////
            //                     IMMUTABLE GETTERS                      //
            ////////////////////////////////////////////////////////////////
            /// @notice Returns the absolute prestate of the instruction trace.
            function absolutePrestate() external view returns (Claim absolutePrestate_) {
                absolutePrestate_ = ABSOLUTE_PRESTATE;
            }
            /// @notice Returns the max game depth.
            function maxGameDepth() external view returns (uint256 maxGameDepth_) {
                maxGameDepth_ = MAX_GAME_DEPTH;
            }
            /// @notice Returns the split depth.
            function splitDepth() external view returns (uint256 splitDepth_) {
                splitDepth_ = SPLIT_DEPTH;
            }
            /// @notice Returns the max clock duration.
            function maxClockDuration() external view returns (Duration maxClockDuration_) {
                maxClockDuration_ = MAX_CLOCK_DURATION;
            }
            /// @notice Returns the clock extension constant.
            function clockExtension() external view returns (Duration clockExtension_) {
                clockExtension_ = CLOCK_EXTENSION;
            }
            /// @notice Returns the address of the VM.
            function vm() external view returns (IBigStepper vm_) {
                vm_ = VM;
            }
            /// @notice Returns the WETH contract for holding ETH.
            function weth() external view returns (IDelayedWETH weth_) {
                weth_ = WETH;
            }
            /// @notice Returns the anchor state registry contract.
            function anchorStateRegistry() external view returns (IAnchorStateRegistry registry_) {
                registry_ = ANCHOR_STATE_REGISTRY;
            }
            /// @notice Returns the chain ID of the L2 network this contract argues about.
            function l2ChainId() external view returns (uint256 l2ChainId_) {
                l2ChainId_ = L2_CHAIN_ID;
            }
            ////////////////////////////////////////////////////////////////
            //                          HELPERS                           //
            ////////////////////////////////////////////////////////////////
            /// @notice Pays out the bond of a claim to a given recipient.
            /// @param _recipient The recipient of the bond.
            /// @param _bonded The claim to pay out the bond of.
            function _distributeBond(address _recipient, ClaimData storage _bonded) internal {
                // Set all bits in the bond value to indicate that the bond has been paid out.
                uint256 bond = _bonded.bond;
                // Increase the recipient's credit.
                credit[_recipient] += bond;
                // Unlock the bond.
                WETH.unlock(_recipient, bond);
            }
            /// @notice Verifies the integrity of an execution bisection subgame's root claim. Reverts if the claim
            ///         is invalid.
            /// @param _rootClaim The root claim of the execution bisection subgame.
            function _verifyExecBisectionRoot(
                Claim _rootClaim,
                uint256 _parentIdx,
                Position _parentPos,
                bool _isAttack
            )
                internal
                view
            {
                // The root claim of an execution trace bisection sub-game must:
                // 1. Signal that the VM panicked or resulted in an invalid transition if the disputed output root
                //    was made by the opposing party.
                // 2. Signal that the VM resulted in a valid transition if the disputed output root was made by the same party.
                // If the move is a defense, the disputed output could have been made by either party. In this case, we
                // need to search for the parent output to determine what the expected status byte should be.
                Position disputedLeafPos = Position.wrap(_parentPos.raw() + 1);
                ClaimData storage disputed = _findTraceAncestor({ _pos: disputedLeafPos, _start: _parentIdx, _global: true });
                uint8 vmStatus = uint8(_rootClaim.raw()[0]);
                if (_isAttack || disputed.position.depth() % 2 == SPLIT_DEPTH % 2) {
                    // If the move is an attack, the parent output is always deemed to be disputed. In this case, we only need
                    // to check that the root claim signals that the VM panicked or resulted in an invalid transition.
                    // If the move is a defense, and the disputed output and creator of the execution trace subgame disagree,
                    // the root claim should also signal that the VM panicked or resulted in an invalid transition.
                    if (!(vmStatus == VMStatuses.INVALID.raw() || vmStatus == VMStatuses.PANIC.raw())) {
                        revert UnexpectedRootClaim(_rootClaim);
                    }
                } else if (vmStatus != VMStatuses.VALID.raw()) {
                    // The disputed output and the creator of the execution trace subgame agree. The status byte should
                    // have signaled that the VM succeeded.
                    revert UnexpectedRootClaim(_rootClaim);
                }
            }
            /// @notice Finds the trace ancestor of a given position within the DAG.
            /// @param _pos The position to find the trace ancestor claim of.
            /// @param _start The index to start searching from.
            /// @param _global Whether or not to search the entire dag or just within an execution trace subgame. If set to
            ///                `true`, and `_pos` is at or above the split depth, this function will revert.
            /// @return ancestor_ The ancestor claim that commits to the same trace index as `_pos`.
            function _findTraceAncestor(
                Position _pos,
                uint256 _start,
                bool _global
            )
                internal
                view
                returns (ClaimData storage ancestor_)
            {
                // Grab the trace ancestor's expected position.
                Position traceAncestorPos = _global ? _pos.traceAncestor() : _pos.traceAncestorBounded(SPLIT_DEPTH);
                // Walk up the DAG to find a claim that commits to the same trace index as `_pos`. It is
                // guaranteed that such a claim exists.
                ancestor_ = claimData[_start];
                while (ancestor_.position.raw() != traceAncestorPos.raw()) {
                    ancestor_ = claimData[ancestor_.parentIndex];
                }
            }
            /// @notice Finds the starting and disputed output root for a given `ClaimData` within the DAG. This
            ///         `ClaimData` must be below the `SPLIT_DEPTH`.
            /// @param _start The index within `claimData` of the claim to start searching from.
            /// @return startingClaim_ The starting output root claim.
            /// @return startingPos_ The starting output root position.
            /// @return disputedClaim_ The disputed output root claim.
            /// @return disputedPos_ The disputed output root position.
            function _findStartingAndDisputedOutputs(uint256 _start)
                internal
                view
                returns (Claim startingClaim_, Position startingPos_, Claim disputedClaim_, Position disputedPos_)
            {
                // Fatch the starting claim.
                uint256 claimIdx = _start;
                ClaimData storage claim = claimData[claimIdx];
                // If the starting claim's depth is less than or equal to the split depth, we revert as this is UB.
                if (claim.position.depth() <= SPLIT_DEPTH) revert ClaimAboveSplit();
                // We want to:
                // 1. Find the first claim at the split depth.
                // 2. Determine whether it was the starting or disputed output for the exec game.
                // 3. Find the complimentary claim depending on the info from #2 (pre or post).
                // Walk up the DAG until the ancestor's depth is equal to the split depth.
                uint256 currentDepth;
                ClaimData storage execRootClaim = claim;
                while ((currentDepth = claim.position.depth()) > SPLIT_DEPTH) {
                    uint256 parentIndex = claim.parentIndex;
                    // If we're currently at the split depth + 1, we're at the root of the execution sub-game.
                    // We need to keep track of the root claim here to determine whether the execution sub-game was
                    // started with an attack or defense against the output leaf claim.
                    if (currentDepth == SPLIT_DEPTH + 1) execRootClaim = claim;
                    claim = claimData[parentIndex];
                    claimIdx = parentIndex;
                }
                // Determine whether the start of the execution sub-game was an attack or defense to the output root
                // above. This is important because it determines which claim is the starting output root and which
                // is the disputed output root.
                (Position execRootPos, Position outputPos) = (execRootClaim.position, claim.position);
                bool wasAttack = execRootPos.parent().raw() == outputPos.raw();
                // Determine the starting and disputed output root indices.
                // 1. If it was an attack, the disputed output root is `claim`, and the starting output root is
                //    elsewhere in the DAG (it must commit to the block # index at depth of `outputPos - 1`).
                // 2. If it was a defense, the starting output root is `claim`, and the disputed output root is
                //    elsewhere in the DAG (it must commit to the block # index at depth of `outputPos + 1`).
                if (wasAttack) {
                    // If this is an attack on the first output root (the block directly after the starting
                    // block number), the starting claim nor position exists in the tree. We leave these as
                    // 0, which can be easily identified due to 0 being an invalid Gindex.
                    if (outputPos.indexAtDepth() > 0) {
                        ClaimData storage starting = _findTraceAncestor(Position.wrap(outputPos.raw() - 1), claimIdx, true);
                        (startingClaim_, startingPos_) = (starting.claim, starting.position);
                    } else {
                        startingClaim_ = Claim.wrap(startingOutputRoot.root.raw());
                    }
                    (disputedClaim_, disputedPos_) = (claim.claim, claim.position);
                } else {
                    ClaimData storage disputed = _findTraceAncestor(Position.wrap(outputPos.raw() + 1), claimIdx, true);
                    (startingClaim_, startingPos_) = (claim.claim, claim.position);
                    (disputedClaim_, disputedPos_) = (disputed.claim, disputed.position);
                }
            }
            /// @notice Finds the local context hash for a given claim index that is present in an execution trace subgame.
            /// @param _claimIndex The index of the claim to find the local context hash for.
            /// @return uuid_ The local context hash.
            function _findLocalContext(uint256 _claimIndex) internal view returns (Hash uuid_) {
                (Claim starting, Position startingPos, Claim disputed, Position disputedPos) =
                    _findStartingAndDisputedOutputs(_claimIndex);
                uuid_ = _computeLocalContext(starting, startingPos, disputed, disputedPos);
            }
            /// @notice Computes the local context hash for a set of starting/disputed claim values and positions.
            /// @param _starting The starting claim.
            /// @param _startingPos The starting claim's position.
            /// @param _disputed The disputed claim.
            /// @param _disputedPos The disputed claim's position.
            /// @return uuid_ The local context hash.
            function _computeLocalContext(
                Claim _starting,
                Position _startingPos,
                Claim _disputed,
                Position _disputedPos
            )
                internal
                pure
                returns (Hash uuid_)
            {
                // A position of 0 indicates that the starting claim is the absolute prestate. In this special case,
                // we do not include the starting claim within the local context hash.
                uuid_ = _startingPos.raw() == 0
                    ? Hash.wrap(keccak256(abi.encode(_disputed, _disputedPos)))
                    : Hash.wrap(keccak256(abi.encode(_starting, _startingPos, _disputed, _disputedPos)));
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibUDT.sol";
        /// @notice The current status of the dispute game.
        enum GameStatus {
            // The game is currently in progress, and has not been resolved.
            IN_PROGRESS,
            // The game has concluded, and the `rootClaim` was challenged successfully.
            CHALLENGER_WINS,
            // The game has concluded, and the `rootClaim` could not be contested.
            DEFENDER_WINS
        }
        /// @notice Represents an L2 output root and the L2 block number at which it was generated.
        /// @custom:field root The output root.
        /// @custom:field l2BlockNumber The L2 block number at which the output root was generated.
        struct OutputRoot {
            Hash root;
            uint256 l2BlockNumber;
        }
        /// @title GameTypes
        /// @notice A library that defines the IDs of games that can be played.
        library GameTypes {
            /// @dev A dispute game type the uses the cannon vm.
            GameType internal constant CANNON = GameType.wrap(0);
            /// @dev A permissioned dispute game type the uses the cannon vm.
            GameType internal constant PERMISSIONED_CANNON = GameType.wrap(1);
            /// @notice A dispute game type the uses the asterisc VM
            GameType internal constant ASTERISC = GameType.wrap(2);
            /// @notice A dispute game type with short game duration for testing withdrawals.
            ///         Not intended for production use.
            GameType internal constant FAST = GameType.wrap(254);
            /// @notice A dispute game type that uses an alphabet vm.
            ///         Not intended for production use.
            GameType internal constant ALPHABET = GameType.wrap(255);
        }
        /// @title VMStatuses
        /// @notice Named type aliases for the various valid VM status bytes.
        library VMStatuses {
            /// @notice The VM has executed successfully and the outcome is valid.
            VMStatus internal constant VALID = VMStatus.wrap(0);
            /// @notice The VM has executed successfully and the outcome is invalid.
            VMStatus internal constant INVALID = VMStatus.wrap(1);
            /// @notice The VM has paniced.
            VMStatus internal constant PANIC = VMStatus.wrap(2);
            /// @notice The VM execution is still in progress.
            VMStatus internal constant UNFINISHED = VMStatus.wrap(3);
        }
        /// @title LocalPreimageKey
        /// @notice Named type aliases for local `PreimageOracle` key identifiers.
        library LocalPreimageKey {
            /// @notice The identifier for the L1 head hash.
            uint256 internal constant L1_HEAD_HASH = 0x01;
            /// @notice The identifier for the starting output root.
            uint256 internal constant STARTING_OUTPUT_ROOT = 0x02;
            /// @notice The identifier for the disputed output root.
            uint256 internal constant DISPUTED_OUTPUT_ROOT = 0x03;
            /// @notice The identifier for the disputed L2 block number.
            uint256 internal constant DISPUTED_L2_BLOCK_NUMBER = 0x04;
            /// @notice The identifier for the chain ID.
            uint256 internal constant CHAIN_ID = 0x05;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibUDT.sol";
        ////////////////////////////////////////////////////////////////
        //                `DisputeGameFactory` Errors                 //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when a dispute game is attempted to be created with an unsupported game type.
        /// @param gameType The unsupported game type.
        error NoImplementation(GameType gameType);
        /// @notice Thrown when a dispute game that already exists is attempted to be created.
        /// @param uuid The UUID of the dispute game that already exists.
        error GameAlreadyExists(Hash uuid);
        /// @notice Thrown when the root claim has an unexpected VM status.
        ///         Some games can only start with a root-claim with a specific status.
        /// @param rootClaim is the claim that was unexpected.
        error UnexpectedRootClaim(Claim rootClaim);
        ////////////////////////////////////////////////////////////////
        //                 `FaultDisputeGame` Errors                  //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when a dispute game has already been initialized.
        error AlreadyInitialized();
        /// @notice Thrown when a supplied bond is not equal to the required bond amount to cover the cost of the interaction.
        error IncorrectBondAmount();
        /// @notice Thrown when a credit claim is attempted for a value of 0.
        error NoCreditToClaim();
        /// @notice Thrown when the transfer of credit to a recipient account reverts.
        error BondTransferFailed();
        /// @notice Thrown when the `extraData` passed to the CWIA proxy is of improper length, or contains invalid information.
        error BadExtraData();
        /// @notice Thrown when a defense against the root claim is attempted.
        error CannotDefendRootClaim();
        /// @notice Thrown when a claim is attempting to be made that already exists.
        error ClaimAlreadyExists();
        /// @notice Thrown when a disputed claim does not match its index in the game.
        error InvalidDisputedClaimIndex();
        /// @notice Thrown when an action that requires the game to be `IN_PROGRESS` is invoked when
        ///         the game is not in progress.
        error GameNotInProgress();
        /// @notice Thrown when a move is attempted to be made after the clock has timed out.
        error ClockTimeExceeded();
        /// @notice Thrown when the game is attempted to be resolved too early.
        error ClockNotExpired();
        /// @notice Thrown when a move is attempted to be made at or greater than the max depth of the game.
        error GameDepthExceeded();
        /// @notice Thrown when a step is attempted above the maximum game depth.
        error InvalidParent();
        /// @notice Thrown when an invalid prestate is supplied to `step`.
        error InvalidPrestate();
        /// @notice Thrown when a step is made that computes the expected post state correctly.
        error ValidStep();
        /// @notice Thrown when a game is attempted to be initialized with an L1 head that does
        ///         not contain the disputed output root.
        error L1HeadTooOld();
        /// @notice Thrown when an invalid local identifier is passed to the `addLocalData` function.
        error InvalidLocalIdent();
        /// @notice Thrown when resolving claims out of order.
        error OutOfOrderResolution();
        /// @notice Thrown when resolving a claim that has already been resolved.
        error ClaimAlreadyResolved();
        /// @notice Thrown when a parent output root is attempted to be found on a claim that is in
        ///         the output root portion of the tree.
        error ClaimAboveSplit();
        /// @notice Thrown on deployment if the split depth is greater than or equal to the max
        ///         depth of the game.
        error InvalidSplitDepth();
        /// @notice Thrown on deployment if the max clock duration is less than or equal to the clock extension.
        error InvalidClockExtension();
        /// @notice Thrown on deployment if the PreimageOracle challenge period is too high.
        error InvalidChallengePeriod();
        /// @notice Thrown on deployment if the max depth is greater than `LibPosition.`
        error MaxDepthTooLarge();
        /// @notice Thrown when trying to step against a claim for a second time, after it has already been countered with
        ///         an instruction step.
        error DuplicateStep();
        /// @notice Thrown when an anchor root is not found for a given game type.
        error AnchorRootNotFound();
        /// @notice Thrown when an output root proof is invalid.
        error InvalidOutputRootProof();
        /// @notice Thrown when header RLP is invalid with respect to the block hash in an output root proof.
        error InvalidHeaderRLP();
        /// @notice Thrown when there is a match between the block number in the output root proof and the block number
        ///         claimed in the dispute game.
        error BlockNumberMatches();
        /// @notice Thrown when the L2 block number claim has already been challenged.
        error L2BlockNumberChallenged();
        ////////////////////////////////////////////////////////////////
        //              `PermissionedDisputeGame` Errors              //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when an unauthorized address attempts to interact with the game.
        error BadAuth();
        ////////////////////////////////////////////////////////////////
        //              `AnchorStateRegistry` Errors                  //
        ////////////////////////////////////////////////////////////////
        /// @notice Thrown when attempting to set an anchor state using an unregistered game.
        error UnregisteredGame();
        /// @notice Thrown when attempting to set an anchor state using an invalid game result.
        error InvalidGameStatus();
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { ISuperchainConfig } from "src/L1/interfaces/ISuperchainConfig.sol";
        interface IDelayedWETH {
            struct WithdrawalRequest {
                uint256 amount;
                uint256 timestamp;
            }
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            event Initialized(uint8 version);
            event Unwrap(address indexed src, uint256 wad);
            fallback() external payable;
            receive() external payable;
            function config() external view returns (ISuperchainConfig);
            function delay() external view returns (uint256);
            function hold(address _guy, uint256 _wad) external;
            function initialize(address _owner, ISuperchainConfig _config) external;
            function owner() external view returns (address);
            function recover(uint256 _wad) external;
            function transferOwnership(address newOwner) external; // nosemgrep
            function renounceOwnership() external;
            function unlock(address _guy, uint256 _wad) external;
            function withdraw(address _guy, uint256 _wad) external;
            function withdrawals(address, address) external view returns (uint256 amount, uint256 timestamp);
            function version() external view returns (string memory);
            function withdraw(uint256 _wad) external;
            event Approval(address indexed src, address indexed guy, uint256 wad);
            event Transfer(address indexed src, address indexed dst, uint256 wad);
            event Deposit(address indexed dst, uint256 wad);
            event Withdrawal(address indexed src, uint256 wad);
            function name() external view returns (string memory);
            function symbol() external view returns (string memory);
            function decimals() external view returns (uint8);
            function balanceOf(address src) external view returns (uint256);
            function allowance(address owner, address spender) external view returns (uint256);
            function deposit() external payable;
            function totalSupply() external view returns (uint256);
            function approve(address guy, uint256 wad) external returns (bool);
            function transfer(address dst, uint256 wad) external returns (bool);
            function transferFrom(address src, address dst, uint256 wad) external returns (bool);
            function __constructor__(uint256 _delay) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IFaultDisputeGame } from "src/dispute/interfaces/IFaultDisputeGame.sol";
        import { IDisputeGameFactory } from "src/dispute/interfaces/IDisputeGameFactory.sol";
        import { ISuperchainConfig } from "src/L1/interfaces/ISuperchainConfig.sol";
        import "src/dispute/lib/Types.sol";
        interface IAnchorStateRegistry {
            struct StartingAnchorRoot {
                GameType gameType;
                OutputRoot outputRoot;
            }
            error InvalidGameStatus();
            error Unauthorized();
            error UnregisteredGame();
            event Initialized(uint8 version);
            function anchors(GameType) external view returns (Hash root, uint256 l2BlockNumber); // nosemgrep
            function disputeGameFactory() external view returns (IDisputeGameFactory);
            function initialize(
                StartingAnchorRoot[] memory _startingAnchorRoots,
                ISuperchainConfig _superchainConfig
            )
                external;
            function setAnchorState(IFaultDisputeGame _game) external;
            function superchainConfig() external view returns (ISuperchainConfig);
            function tryUpdateAnchorState() external;
            function version() external view returns (string memory);
            function __constructor__(IDisputeGameFactory _disputeGameFactory) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IPreimageOracle } from "src/cannon/interfaces/IPreimageOracle.sol";
        /// @title IBigStepper
        /// @notice Describes a state machine that can perform a single instruction step, provided a prestate and an optional
        ///         proof.
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⠶⢅⠒⢄⢔⣶⡦⣤⡤⠄⣀⠀⠀⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⡏⠀⠀⠈⠢⣙⢯⣄⠀⢨⠯⡺⡘⢄⠀⠀⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣶⡆⠀⠀⠀⠀⠈⠓⠬⡒⠡⣀⢙⡜⡀⠓⠄⠀⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡷⠿⣧⣀⡀⠀⠀⠀⠀⠀⠀⠉⠣⣞⠩⠥⠀⠼⢄⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀⠉⢹⣶⠒⠒⠂⠈⠉⠁⠘⡆⠀⣿⣿⠫⡄⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⢶⣤⣀⡀⠀⠀⢸⡿⠀⠀⠀⠀⠀⢀⠞⠀⠀⢡⢨⢀⡄⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡒⣿⢿⡤⠝⡣⠉⠁⠚⠛⠀⠤⠤⣄⡰⠁⠀⠀⠀⠉⠙⢸⠀⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⢯⡌⡿⡇⠘⡷⠀⠁⠀⠀⢀⣰⠢⠲⠛⣈⣸⠦⠤⠶⠴⢬⣐⣊⡂⠀
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⡪⡗⢫⠞⠀⠆⣀⠻⠤⠴⠐⠚⣉⢀⠦⠂⠋⠁⠀⠁⠀⠀⠀⠀⢋⠉⠇⠀
        /// ⠀⠀⠀⠀⣀⡤⠐⠒⠘⡹⠉⢸⠇⠸⠀⠀⠀⠀⣀⣤⠴⠚⠉⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠀⣾⠀
        /// ⠀⠀⠀⡰⠀⠉⠉⠀⠁⠀⠀⠈⢇⠈⠒⠒⠘⠈⢀⢡⡂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠀⢸⡄
        /// ⠀⠀⠸⣿⣆⠤⢀⡀⠀⠀⠀⠀⢘⡌⠀⠀⣀⣀⣀⡈⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢸⡇
        /// ⠀⠀⢸⣀⠀⠉⠒⠐⠛⠋⠭⠭⠍⠉⠛⠒⠒⠒⠀⠒⠚⠛⠛⠛⠩⠭⠭⠭⠭⠤⠤⠤⠤⠤⠭⠭⠉⠓⡆
        /// ⠀⠀⠘⠿⣷⣶⣤⣤⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣤⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇
        /// ⠀⠀⠀⠀⠀⠉⠙⠛⠛⠻⠿⢿⣿⣿⣷⣶⣶⣶⣤⣤⣀⣁⣛⣃⣒⠿⠿⠿⠤⠠⠄⠤⠤⢤⣛⣓⣂⣻⡇
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠙⠛⠻⠿⠿⠿⢿⣿⣿⣿⣷⣶⣶⣾⣿⣿⣿⣿⠿⠟⠁
        /// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠈⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀
        interface IBigStepper {
            /// @notice Performs the state transition from a given prestate and returns the hash of the post state witness.
            /// @param _stateData The raw opaque prestate data.
            /// @param _proof Opaque proof data, can be used to prove things about the prestate in relation to the state of the
            ///               interface's implementation.
            /// @param _localContext The local key context for the preimage oracle. Optional, can be set as a constant if the
            ///                      implementation only requires one set of local keys.
            /// @return postState_ The hash of the post state witness after the state transition.
            function step(
                bytes calldata _stateData,
                bytes calldata _proof,
                bytes32 _localContext
            )
                external
                returns (bytes32 postState_);
            /// @notice Returns the preimage oracle used by the state machine.
            function oracle() external view returns (IPreimageOracle oracle_);
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Standard math utilities missing in the Solidity language.
         */
        library Math {
            enum Rounding {
                Down, // Toward negative infinity
                Up, // Toward infinity
                Zero // Toward zero
            }
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a >= b ? a : b;
            }
            /**
             * @dev Returns the smallest of two numbers.
             */
            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                return a < b ? a : b;
            }
            /**
             * @dev Returns the average of two numbers. The result is rounded towards
             * zero.
             */
            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b) / 2 can overflow.
                return (a & b) + (a ^ b) / 2;
            }
            /**
             * @dev Returns the ceiling of the division of two numbers.
             *
             * This differs from standard division with `/` in that it rounds up instead
             * of rounding down.
             */
            function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b - 1) / b can overflow on addition, so we distribute.
                return a == 0 ? 0 : (a - 1) / b + 1;
            }
            /**
             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
             * with further edits by Uniswap Labs also under MIT license.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator
            ) internal pure returns (uint256 result) {
                unchecked {
                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                    // variables such that product = prod1 * 2^256 + prod0.
                    uint256 prod0; // Least significant 256 bits of the product
                    uint256 prod1; // Most significant 256 bits of the product
                    assembly {
                        let mm := mulmod(x, y, not(0))
                        prod0 := mul(x, y)
                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                    }
                    // Handle non-overflow cases, 256 by 256 division.
                    if (prod1 == 0) {
                        return prod0 / denominator;
                    }
                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                    require(denominator > prod1);
                    ///////////////////////////////////////////////
                    // 512 by 256 division.
                    ///////////////////////////////////////////////
                    // Make division exact by subtracting the remainder from [prod1 prod0].
                    uint256 remainder;
                    assembly {
                        // Compute remainder using mulmod.
                        remainder := mulmod(x, y, denominator)
                        // Subtract 256 bit number from 512 bit number.
                        prod1 := sub(prod1, gt(remainder, prod0))
                        prod0 := sub(prod0, remainder)
                    }
                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                    // See https://cs.stackexchange.com/q/138556/92363.
                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                    uint256 twos = denominator & (~denominator + 1);
                    assembly {
                        // Divide denominator by twos.
                        denominator := div(denominator, twos)
                        // Divide [prod1 prod0] by twos.
                        prod0 := div(prod0, twos)
                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                        twos := add(div(sub(0, twos), twos), 1)
                    }
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * twos;
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                    // in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                    return result;
                }
            }
            /**
             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator,
                Rounding rounding
            ) internal pure returns (uint256) {
                uint256 result = mulDiv(x, y, denominator);
                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                    result += 1;
                }
                return result;
            }
            /**
             * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
             *
             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
             */
            function sqrt(uint256 a) internal pure returns (uint256) {
                if (a == 0) {
                    return 0;
                }
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                // `msb(a) <= a < 2*msb(a)`.
                // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
                // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
                // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
                // good first aproximation of `sqrt(a)` with at least 1 correct bit.
                uint256 result = 1;
                uint256 x = a;
                if (x >> 128 > 0) {
                    x >>= 128;
                    result <<= 64;
                }
                if (x >> 64 > 0) {
                    x >>= 64;
                    result <<= 32;
                }
                if (x >> 32 > 0) {
                    x >>= 32;
                    result <<= 16;
                }
                if (x >> 16 > 0) {
                    x >>= 16;
                    result <<= 8;
                }
                if (x >> 8 > 0) {
                    x >>= 8;
                    result <<= 4;
                }
                if (x >> 4 > 0) {
                    x >>= 4;
                    result <<= 2;
                }
                if (x >> 2 > 0) {
                    result <<= 1;
                }
                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                // into the expected uint128 result.
                unchecked {
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    return min(result, a / result);
                }
            }
            /**
             * @notice Calculates sqrt(a), following the selected rounding direction.
             */
            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                uint256 result = sqrt(a);
                if (rounding == Rounding.Up && result * result < a) {
                    result += 1;
                }
                return result;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        /// @notice Arithmetic library with operations for fixed-point numbers.
        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
        /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
        library FixedPointMathLib {
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                       CUSTOM ERRORS                        */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
            error ExpOverflow();
            /// @dev The operation failed, as the output exceeds the maximum value of uint256.
            error FactorialOverflow();
            /// @dev The operation failed, due to an overflow.
            error RPowOverflow();
            /// @dev The mantissa is too big to fit.
            error MantissaOverflow();
            /// @dev The operation failed, due to an multiplication overflow.
            error MulWadFailed();
            /// @dev The operation failed, due to an multiplication overflow.
            error SMulWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error DivWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error SDivWadFailed();
            /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
            error MulDivFailed();
            /// @dev The division failed, as the denominator is zero.
            error DivFailed();
            /// @dev The full precision multiply-divide operation failed, either due
            /// to the result being larger than 256 bits, or a division by a zero.
            error FullMulDivFailed();
            /// @dev The output is undefined, as the input is less-than-or-equal to zero.
            error LnWadUndefined();
            /// @dev The input outside the acceptable domain.
            error OutOfDomain();
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                         CONSTANTS                          */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev The scalar of ETH and most ERC20s.
            uint256 internal constant WAD = 1e18;
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*              SIMPLIFIED FIXED POINT OPERATIONS             */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Equivalent to `(x * y) / WAD` rounded down.
            function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                    if mul(y, gt(x, div(not(0), y))) {
                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down.
            function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(x, y)
                    // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
                    if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                        mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := sdiv(z, WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
            function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
            function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(mul(x, y), WAD)
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded up.
            function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
                    if mul(y, gt(x, div(not(0), y))) {
                        mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                }
            }
            /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
            function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down.
            function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down.
            function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(x, WAD)
                    // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
                    if iszero(and(iszero(iszero(y)), eq(sdiv(z, WAD), x))) {
                        mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := sdiv(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
            function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
            function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(mul(x, WAD), y)
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded up.
            function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
                    if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                        mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                }
            }
            /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
            function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
                }
            }
            /// @dev Equivalent to `x` to the power of `y`.
            /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
            function powWad(int256 x, int256 y) internal pure returns (int256) {
                // Using `ln(x)` means `x` must be greater than 0.
                return expWad((lnWad(x) * y) / int256(WAD));
            }
            /// @dev Returns `exp(x)`, denominated in `WAD`.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/exp-ln
            function expWad(int256 x) internal pure returns (int256 r) {
                unchecked {
                    // When the result is less than 0.5 we return zero.
                    // This happens when `x <= floor(log(0.5e18) * 1e18) ≈ -42e18`.
                    if (x <= -41446531673892822313) return r;
                    /// @solidity memory-safe-assembly
                    assembly {
                        // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                        // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                        if iszero(slt(x, 135305999368893231589)) {
                            mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                            revert(0x1c, 0x04)
                        }
                    }
                    // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
                    // for more intermediate precision and a binary basis. This base conversion
                    // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                    x = (x << 78) / 5 ** 18;
                    // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                    // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                    // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                    int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
                    x = x - k * 54916777467707473351141471128;
                    // `k` is in the range `[-61, 195]`.
                    // Evaluate using a (6, 7)-term rational approximation.
                    // `p` is made monic, we'll multiply by a scale factor later.
                    int256 y = x + 1346386616545796478920950773328;
                    y = ((y * x) >> 96) + 57155421227552351082224309758442;
                    int256 p = y + x - 94201549194550492254356042504812;
                    p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                    p = p * x + (4385272521454847904659076985693276 << 96);
                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                    int256 q = x - 2855989394907223263936484059900;
                    q = ((q * x) >> 96) + 50020603652535783019961831881945;
                    q = ((q * x) >> 96) - 533845033583426703283633433725380;
                    q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                    q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                    q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                    /// @solidity memory-safe-assembly
                    assembly {
                        // Div in assembly because solidity adds a zero check despite the unchecked.
                        // The q polynomial won't have zeros in the domain as all its roots are complex.
                        // No scaling is necessary because p is already `2**96` too large.
                        r := sdiv(p, q)
                    }
                    // r should be in the range `(0.09, 0.25) * 2**96`.
                    // We now need to multiply r by:
                    // - The scale factor `s ≈ 6.031367120`.
                    // - The `2**k` factor from the range reduction.
                    // - The `1e18 / 2**96` factor for base conversion.
                    // We do this all at once, with an intermediate result in `2**213`
                    // basis, so the final right shift is always by a positive amount.
                    r = int256(
                        (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
                    );
                }
            }
            /// @dev Returns `ln(x)`, denominated in `WAD`.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/exp-ln
            function lnWad(int256 x) internal pure returns (int256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
                    // We do this by multiplying by `2**96 / 10**18`. But since
                    // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
                    // and add `ln(2**96 / 10**18)` at the end.
                    // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    // We place the check here for more optimal stack operations.
                    if iszero(sgt(x, 0)) {
                        mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                        revert(0x1c, 0x04)
                    }
                    // forgefmt: disable-next-item
                    r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                        0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
                    // Reduce range of x to (1, 2) * 2**96
                    // ln(2^k * x) = k * ln(2) + ln(x)
                    x := shr(159, shl(r, x))
                    // Evaluate using a (8, 8)-term rational approximation.
                    // `p` is made monic, we will multiply by a scale factor later.
                    // forgefmt: disable-next-item
                    let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                        sar(96, mul(add(43456485725739037958740375743393,
                        sar(96, mul(add(24828157081833163892658089445524,
                        sar(96, mul(add(3273285459638523848632254066296,
                            x), x))), x))), x)), 11111509109440967052023855526967)
                    p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
                    p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
                    p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
                    // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
                    // `q` is monic by convention.
                    let q := add(5573035233440673466300451813936, x)
                    q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
                    q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
                    q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
                    q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
                    q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
                    q := add(909429971244387300277376558375, sar(96, mul(x, q)))
                    // `p / q` is in the range `(0, 0.125) * 2**96`.
                    // Finalization, we need to:
                    // - Multiply by the scale factor `s = 5.549…`.
                    // - Add `ln(2**96 / 10**18)`.
                    // - Add `k * ln(2)`.
                    // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
                    // The q polynomial is known not to have zeros in the domain.
                    // No scaling required because p is already `2**96` too large.
                    p := sdiv(p, q)
                    // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
                    p := mul(1677202110996718588342820967067443963516166, p)
                    // Add `ln(2) * k * 5**18 * 2**192`.
                    // forgefmt: disable-next-item
                    p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
                    // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
                    p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
                    // Base conversion: mul `2**18 / 2**192`.
                    r := sar(174, p)
                }
            }
            /// @dev Returns `W_0(x)`, denominated in `WAD`.
            /// See: https://en.wikipedia.org/wiki/Lambert_W_function
            /// a.k.a. Product log function. This is an approximation of the principal branch.
            function lambertW0Wad(int256 x) internal pure returns (int256 w) {
                // forgefmt: disable-next-item
                unchecked {
                    if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
                    int256 wad = int256(WAD);
                    int256 p = x;
                    uint256 c; // Whether we need to avoid catastrophic cancellation.
                    uint256 i = 4; // Number of iterations.
                    if (w <= 0x1ffffffffffff) {
                        if (-0x4000000000000 <= w) {
                            i = 1; // Inputs near zero only take one step to converge.
                        } else if (w <= -0x3ffffffffffffff) {
                            i = 32; // Inputs near `-1/e` take very long to converge.
                        }
                    } else if (w >> 63 == 0) {
                        /// @solidity memory-safe-assembly
                        assembly {
                            // Inline log2 for more performance, since the range is small.
                            let v := shr(49, w)
                            let l := shl(3, lt(0xff, v))
                            l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                                0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                            w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                            c := gt(l, 60)
                            i := add(2, add(gt(l, 53), c))
                        }
                    } else {
                        int256 ll = lnWad(w = lnWad(w));
                        /// @solidity memory-safe-assembly
                        assembly {
                            // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                            w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                            i := add(3, iszero(shr(68, x)))
                            c := iszero(shr(143, x))
                        }
                        if (c == 0) {
                            do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                                int256 e = expWad(w);
                                /// @solidity memory-safe-assembly
                                assembly {
                                    let t := mul(w, div(e, wad))
                                    w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                                }
                                if (p <= w) break;
                                p = w;
                            } while (--i != 0);
                            /// @solidity memory-safe-assembly
                            assembly {
                                w := sub(w, sgt(w, 2))
                            }
                            return w;
                        }
                    }
                    do { // Otherwise, use Halley's for faster convergence.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := add(w, wad)
                            let s := sub(mul(w, e), mul(x, wad))
                            w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != c);
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
                    // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
                    if (c != 0) {
                        int256 t = w | 1;
                        /// @solidity memory-safe-assembly
                        assembly {
                            x := sdiv(mul(x, wad), t)
                        }
                        x = (t * (wad + lnWad(x)));
                        /// @solidity memory-safe-assembly
                        assembly {
                            w := sdiv(x, add(wad, t))
                        }
                    }
                }
            }
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                  GENERAL NUMBER UTILITIES                  */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Calculates `floor(a * b / d)` with full precision.
            /// Throws if result overflows a uint256 or when `d` is zero.
            /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
            function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                /// @solidity memory-safe-assembly
                assembly {
                    for {} 1 {} {
                        // 512-bit multiply `[p1 p0] = x * y`.
                        // Compute the product mod `2**256` and mod `2**256 - 1`
                        // then use the Chinese Remainder Theorem to reconstruct
                        // the 512 bit result. The result is stored in two 256
                        // variables such that `product = p1 * 2**256 + p0`.
                        // Least significant 256 bits of the product.
                        result := mul(x, y) // Temporarily use `result` as `p0` to save gas.
                        let mm := mulmod(x, y, not(0))
                        // Most significant 256 bits of the product.
                        let p1 := sub(mm, add(result, lt(mm, result)))
                        // Handle non-overflow cases, 256 by 256 division.
                        if iszero(p1) {
                            if iszero(d) {
                                mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                                revert(0x1c, 0x04)
                            }
                            result := div(result, d)
                            break
                        }
                        // Make sure the result is less than `2**256`. Also prevents `d == 0`.
                        if iszero(gt(d, p1)) {
                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                            revert(0x1c, 0x04)
                        }
                        /*------------------- 512 by 256 division --------------------*/
                        // Make division exact by subtracting the remainder from `[p1 p0]`.
                        // Compute remainder using mulmod.
                        let r := mulmod(x, y, d)
                        // `t` is the least significant bit of `d`.
                        // Always greater or equal to 1.
                        let t := and(d, sub(0, d))
                        // Divide `d` by `t`, which is a power of two.
                        d := div(d, t)
                        // Invert `d mod 2**256`
                        // Now that `d` is an odd number, it has an inverse
                        // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                        // Compute the inverse by starting with a seed that is correct
                        // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                        let inv := xor(2, mul(3, d))
                        // Now use Newton-Raphson iteration to improve the precision.
                        // Thanks to Hensel's lifting lemma, this also works in modular
                        // arithmetic, doubling the correct bits in each step.
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                        inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                        result :=
                            mul(
                                // Divide [p1 p0] by the factors of two.
                                // Shift in bits from `p1` into `p0`. For this we need
                                // to flip `t` such that it is `2**256 / t`.
                                or(
                                    mul(sub(p1, gt(r, result)), add(div(sub(0, t), t), 1)),
                                    div(sub(result, r), t)
                                ),
                                // inverse mod 2**256
                                mul(inv, sub(2, mul(d, inv)))
                            )
                        break
                    }
                }
            }
            /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
            /// Throws if result overflows a uint256 or when `d` is zero.
            /// Credit to Uniswap-v3-core under MIT license:
            /// https://github.com/Uniswap/v3-core/blob/contracts/libraries/FullMath.sol
            function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
                result = fullMulDiv(x, y, d);
                /// @solidity memory-safe-assembly
                assembly {
                    if mulmod(x, y, d) {
                        result := add(result, 1)
                        if iszero(result) {
                            mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            /// @dev Returns `floor(x * y / d)`.
            /// Reverts if `x * y` overflows, or `d` is zero.
            function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := div(mul(x, y), d)
                }
            }
            /// @dev Returns `ceil(x * y / d)`.
            /// Reverts if `x * y` overflows, or `d` is zero.
            function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
                    if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                        mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
                }
            }
            /// @dev Returns `ceil(x / d)`.
            /// Reverts if `d` is zero.
            function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(d) {
                        mstore(0x00, 0x65244e4e) // `DivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    z := add(iszero(iszero(mod(x, d))), div(x, d))
                }
            }
            /// @dev Returns `max(0, x - y)`.
            function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(gt(x, y), sub(x, y))
                }
            }
            /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
            /// Reverts if the computation overflows.
            function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
                    if x {
                        z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                        let half := shr(1, b) // Divide `b` by 2.
                        // Divide `y` by 2 every iteration.
                        for { y := shr(1, y) } y { y := shr(1, y) } {
                            let xx := mul(x, x) // Store x squared.
                            let xxRound := add(xx, half) // Round to the nearest number.
                            // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                            if or(lt(xxRound, xx), shr(128, x)) {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                            x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                            // If `y` is odd:
                            if and(y, 1) {
                                let zx := mul(z, x) // Compute `z * x`.
                                let zxRound := add(zx, half) // Round to the nearest number.
                                // If `z * x` overflowed or `zx + half` overflowed:
                                if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                                    // Revert if `x` is non-zero.
                                    if iszero(iszero(x)) {
                                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                        revert(0x1c, 0x04)
                                    }
                                }
                                z := div(zxRound, b) // Return properly scaled `zxRound`.
                            }
                        }
                    }
                }
            }
            /// @dev Returns the square root of `x`.
            function sqrt(uint256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
                    z := 181 // The "correct" value is 1, but this saves a multiplication later.
                    // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                    // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                    // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
                    // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffffff, shr(r, x))))
                    z := shl(shr(1, r), z)
                    // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
                    // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
                    // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
                    // That's not possible if `x < 256` but we can just verify those cases exhaustively.
                    // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
                    // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
                    // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
                    // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
                    // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
                    // with largest error when `s = 1` and when `s = 256` or `1/256`.
                    // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
                    // Then we can estimate `sqrt(y)` using
                    // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
                    // There is no overflow risk here since `y < 2**136` after the first branch above.
                    z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
                    // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    // If `x+1` is a perfect square, the Babylonian method cycles between
                    // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
                    // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                    z := sub(z, lt(div(x, z), z))
                }
            }
            /// @dev Returns the cube root of `x`.
            /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
            /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
            function cbrt(uint256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := div(add(add(div(x, mul(z, z)), z), z), 3)
                    z := sub(z, lt(div(x, mul(z, z)), z))
                }
            }
            /// @dev Returns the square root of `x`, denominated in `WAD`.
            function sqrtWad(uint256 x) internal pure returns (uint256 z) {
                unchecked {
                    z = 10 ** 9;
                    if (x <= type(uint256).max / 10 ** 36 - 1) {
                        x *= 10 ** 18;
                        z = 1;
                    }
                    z *= sqrt(x);
                }
            }
            /// @dev Returns the cube root of `x`, denominated in `WAD`.
            function cbrtWad(uint256 x) internal pure returns (uint256 z) {
                unchecked {
                    z = 10 ** 12;
                    if (x <= (type(uint256).max / 10 ** 36) * 10 ** 18 - 1) {
                        if (x >= type(uint256).max / 10 ** 36) {
                            x *= 10 ** 18;
                            z = 10 ** 6;
                        } else {
                            x *= 10 ** 36;
                            z = 1;
                        }
                    }
                    z *= cbrt(x);
                }
            }
            /// @dev Returns the factorial of `x`.
            function factorial(uint256 x) internal pure returns (uint256 result) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(lt(x, 58)) {
                        mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    for { result := 1 } x { x := sub(x, 1) } { result := mul(result, x) }
                }
            }
            /// @dev Returns the log2 of `x`.
            /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
            /// Returns 0 if `x` is zero.
            function log2(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    // forgefmt: disable-next-item
                    r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000))
                }
            }
            /// @dev Returns the log2 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log2Up(uint256 x) internal pure returns (uint256 r) {
                r = log2(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(shl(r, 1), x))
                }
            }
            /// @dev Returns the log10 of `x`.
            /// Returns 0 if `x` is zero.
            function log10(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    if iszero(lt(x, 100000000000000000000000000000000000000)) {
                        x := div(x, 100000000000000000000000000000000000000)
                        r := 38
                    }
                    if iszero(lt(x, 100000000000000000000)) {
                        x := div(x, 100000000000000000000)
                        r := add(r, 20)
                    }
                    if iszero(lt(x, 10000000000)) {
                        x := div(x, 10000000000)
                        r := add(r, 10)
                    }
                    if iszero(lt(x, 100000)) {
                        x := div(x, 100000)
                        r := add(r, 5)
                    }
                    r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
                }
            }
            /// @dev Returns the log10 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log10Up(uint256 x) internal pure returns (uint256 r) {
                r = log10(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(exp(10, r), x))
                }
            }
            /// @dev Returns the log256 of `x`.
            /// Returns 0 if `x` is zero.
            function log256(uint256 x) internal pure returns (uint256 r) {
                /// @solidity memory-safe-assembly
                assembly {
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(shr(3, r), lt(0xff, shr(r, x)))
                }
            }
            /// @dev Returns the log256 of `x`, rounded up.
            /// Returns 0 if `x` is zero.
            function log256Up(uint256 x) internal pure returns (uint256 r) {
                r = log256(x);
                /// @solidity memory-safe-assembly
                assembly {
                    r := add(r, lt(shl(shl(3, r), 1), x))
                }
            }
            /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
            /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
            function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
                /// @solidity memory-safe-assembly
                assembly {
                    mantissa := x
                    if mantissa {
                        if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                            mantissa := div(mantissa, 1000000000000000000000000000000000)
                            exponent := 33
                        }
                        if iszero(mod(mantissa, 10000000000000000000)) {
                            mantissa := div(mantissa, 10000000000000000000)
                            exponent := add(exponent, 19)
                        }
                        if iszero(mod(mantissa, 1000000000000)) {
                            mantissa := div(mantissa, 1000000000000)
                            exponent := add(exponent, 12)
                        }
                        if iszero(mod(mantissa, 1000000)) {
                            mantissa := div(mantissa, 1000000)
                            exponent := add(exponent, 6)
                        }
                        if iszero(mod(mantissa, 10000)) {
                            mantissa := div(mantissa, 10000)
                            exponent := add(exponent, 4)
                        }
                        if iszero(mod(mantissa, 100)) {
                            mantissa := div(mantissa, 100)
                            exponent := add(exponent, 2)
                        }
                        if iszero(mod(mantissa, 10)) {
                            mantissa := div(mantissa, 10)
                            exponent := add(exponent, 1)
                        }
                    }
                }
            }
            /// @dev Convenience function for packing `x` into a smaller number using `sci`.
            /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
            /// The `exponent` will be in bits [0..6] (the lower 7 bits).
            /// Use `SafeCastLib` to safely ensure that the `packed` number is small
            /// enough to fit in the desired unsigned integer type:
            /// ```
            ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
            /// ```
            function packSci(uint256 x) internal pure returns (uint256 packed) {
                (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
                /// @solidity memory-safe-assembly
                assembly {
                    if shr(249, x) {
                        mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    packed := or(shl(7, x), packed)
                }
            }
            /// @dev Convenience function for unpacking a packed number from `packSci`.
            function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
                unchecked {
                    unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
                }
            }
            /// @dev Returns the average of `x` and `y`.
            function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = (x & y) + ((x ^ y) >> 1);
                }
            }
            /// @dev Returns the average of `x` and `y`.
            function avg(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = (x >> 1) + (y >> 1) + (((x & 1) + (y & 1)) >> 1);
                }
            }
            /// @dev Returns the absolute value of `x`.
            function abs(int256 x) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(sub(0, shr(255, x)), add(sub(0, shr(255, x)), x))
                }
            }
            /// @dev Returns the absolute distance between `x` and `y`.
            function dist(int256 x, int256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(mul(xor(sub(y, x), sub(x, y)), sgt(x, y)), sub(y, x))
                }
            }
            /// @dev Returns the minimum of `x` and `y`.
            function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), lt(y, x)))
                }
            }
            /// @dev Returns the minimum of `x` and `y`.
            function min(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), slt(y, x)))
                }
            }
            /// @dev Returns the maximum of `x` and `y`.
            function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), gt(y, x)))
                }
            }
            /// @dev Returns the maximum of `x` and `y`.
            function max(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, y), sgt(y, x)))
                }
            }
            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
            function clamp(uint256 x, uint256 minValue, uint256 maxValue)
                internal
                pure
                returns (uint256 z)
            {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
                    z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
                }
            }
            /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
            function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
                    z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
                }
            }
            /// @dev Returns greatest common divisor of `x` and `y`.
            function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    for { z := x } y {} {
                        let t := y
                        y := mod(z, y)
                        z := t
                    }
                }
            }
            /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
            /*                   RAW NUMBER OPERATIONS                    */
            /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
            /// @dev Returns `x + y`, without checking for overflow.
            function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x + y;
                }
            }
            /// @dev Returns `x + y`, without checking for overflow.
            function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x + y;
                }
            }
            /// @dev Returns `x - y`, without checking for underflow.
            function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x - y;
                }
            }
            /// @dev Returns `x - y`, without checking for underflow.
            function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x - y;
                }
            }
            /// @dev Returns `x * y`, without checking for overflow.
            function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                unchecked {
                    z = x * y;
                }
            }
            /// @dev Returns `x * y`, without checking for overflow.
            function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
                unchecked {
                    z = x * y;
                }
            }
            /// @dev Returns `x / y`, returning 0 if `y` is zero.
            function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := div(x, y)
                }
            }
            /// @dev Returns `x / y`, returning 0 if `y` is zero.
            function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := sdiv(x, y)
                }
            }
            /// @dev Returns `x % y`, returning 0 if `y` is zero.
            function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mod(x, y)
                }
            }
            /// @dev Returns `x % y`, returning 0 if `y` is zero.
            function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := smod(x, y)
                }
            }
            /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
            function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := addmod(x, y, d)
                }
            }
            /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
            function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
                /// @solidity memory-safe-assembly
                assembly {
                    z := mulmod(x, y, d)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.4;
        /// @notice Class with helper read functions for clone with immutable args.
        /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Clone.sol)
        /// @author Adapted from clones with immutable args by zefram.eth, Saw-mon & Natalie
        /// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args)
        abstract contract Clone {
            /// @dev Reads all of the immutable args.
            function _getArgBytes() internal pure returns (bytes memory arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    let length := sub(calldatasize(), add(2, offset)) // 2 bytes are used for the length.
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), offset, length)
                    let o := add(add(arg, 0x20), length)
                    mstore(o, 0) // Zeroize the slot after the bytes.
                    mstore(0x40, add(o, 0x20)) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type bytes.
            function _getArgBytes(uint256 argOffset, uint256 length)
                internal
                pure
                returns (bytes memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), length)
                    let o := add(add(arg, 0x20), length)
                    mstore(o, 0) // Zeroize the slot after the bytes.
                    mstore(0x40, add(o, 0x20)) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type address.
            function _getArgAddress(uint256 argOffset) internal pure returns (address arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(96, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads a uint256 array stored in the immutable args.
            function _getArgUint256Array(uint256 argOffset, uint256 length)
                internal
                pure
                returns (uint256[] memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), shl(5, length))
                    mstore(0x40, add(add(arg, 0x20), shl(5, length))) // Allocate the memory.
                }
            }
            /// @dev Reads a bytes32 array stored in the immutable args.
            function _getArgBytes32Array(uint256 argOffset, uint256 length)
                internal
                pure
                returns (bytes32[] memory arg)
            {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := mload(0x40)
                    mstore(arg, length) // Store the length.
                    calldatacopy(add(arg, 0x20), add(offset, argOffset), shl(5, length))
                    mstore(0x40, add(add(arg, 0x20), shl(5, length))) // Allocate the memory.
                }
            }
            /// @dev Reads an immutable arg with type bytes32.
            function _getArgBytes32(uint256 argOffset) internal pure returns (bytes32 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := calldataload(add(offset, argOffset))
                }
            }
            /// @dev Reads an immutable arg with type uint256.
            function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := calldataload(add(offset, argOffset))
                }
            }
            /// @dev Reads an immutable arg with type uint248.
            function _getArgUint248(uint256 argOffset) internal pure returns (uint248 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(8, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint240.
            function _getArgUint240(uint256 argOffset) internal pure returns (uint240 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(16, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint232.
            function _getArgUint232(uint256 argOffset) internal pure returns (uint232 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(24, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint224.
            function _getArgUint224(uint256 argOffset) internal pure returns (uint224 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(0x20, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint216.
            function _getArgUint216(uint256 argOffset) internal pure returns (uint216 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(40, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint208.
            function _getArgUint208(uint256 argOffset) internal pure returns (uint208 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(48, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint200.
            function _getArgUint200(uint256 argOffset) internal pure returns (uint200 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(56, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint192.
            function _getArgUint192(uint256 argOffset) internal pure returns (uint192 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(64, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint184.
            function _getArgUint184(uint256 argOffset) internal pure returns (uint184 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(72, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint176.
            function _getArgUint176(uint256 argOffset) internal pure returns (uint176 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(80, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint168.
            function _getArgUint168(uint256 argOffset) internal pure returns (uint168 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(88, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint160.
            function _getArgUint160(uint256 argOffset) internal pure returns (uint160 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(96, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint152.
            function _getArgUint152(uint256 argOffset) internal pure returns (uint152 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(104, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint144.
            function _getArgUint144(uint256 argOffset) internal pure returns (uint144 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(112, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint136.
            function _getArgUint136(uint256 argOffset) internal pure returns (uint136 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(120, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint128.
            function _getArgUint128(uint256 argOffset) internal pure returns (uint128 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(128, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint120.
            function _getArgUint120(uint256 argOffset) internal pure returns (uint120 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(136, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint112.
            function _getArgUint112(uint256 argOffset) internal pure returns (uint112 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(144, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint104.
            function _getArgUint104(uint256 argOffset) internal pure returns (uint104 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(152, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint96.
            function _getArgUint96(uint256 argOffset) internal pure returns (uint96 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(160, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint88.
            function _getArgUint88(uint256 argOffset) internal pure returns (uint88 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(168, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint80.
            function _getArgUint80(uint256 argOffset) internal pure returns (uint80 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(176, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint72.
            function _getArgUint72(uint256 argOffset) internal pure returns (uint72 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(184, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint64.
            function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(192, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint56.
            function _getArgUint56(uint256 argOffset) internal pure returns (uint56 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(200, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint48.
            function _getArgUint48(uint256 argOffset) internal pure returns (uint48 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(208, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint40.
            function _getArgUint40(uint256 argOffset) internal pure returns (uint40 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(216, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint32.
            function _getArgUint32(uint256 argOffset) internal pure returns (uint32 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(224, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint24.
            function _getArgUint24(uint256 argOffset) internal pure returns (uint24 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(232, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint16.
            function _getArgUint16(uint256 argOffset) internal pure returns (uint16 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(240, calldataload(add(offset, argOffset)))
                }
            }
            /// @dev Reads an immutable arg with type uint8.
            function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
                uint256 offset = _getImmutableArgsOffset();
                /// @solidity memory-safe-assembly
                assembly {
                    arg := shr(248, calldataload(add(offset, argOffset)))
                }
            }
            /// @return offset The offset of the packed immutable args in calldata.
            function _getImmutableArgsOffset() internal pure returns (uint256 offset) {
                /// @solidity memory-safe-assembly
                assembly {
                    offset := sub(calldatasize(), shr(240, calldataload(sub(calldatasize(), 2))))
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title Types
        /// @notice Contains various types used throughout the Optimism contract system.
        library Types {
            /// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
            ///         timestamp that the output root is posted. This timestamp is used to verify that the
            ///         finalization period has passed since the output root was submitted.
            /// @custom:field outputRoot    Hash of the L2 output.
            /// @custom:field timestamp     Timestamp of the L1 block that the output root was submitted in.
            /// @custom:field l2BlockNumber L2 block number that the output corresponds to.
            struct OutputProposal {
                bytes32 outputRoot;
                uint128 timestamp;
                uint128 l2BlockNumber;
            }
            /// @notice Struct representing the elements that are hashed together to generate an output root
            ///         which itself represents a snapshot of the L2 state.
            /// @custom:field version                  Version of the output root.
            /// @custom:field stateRoot                Root of the state trie at the block of this output.
            /// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
            /// @custom:field latestBlockhash          Hash of the block this output was generated from.
            struct OutputRootProof {
                bytes32 version;
                bytes32 stateRoot;
                bytes32 messagePasserStorageRoot;
                bytes32 latestBlockhash;
            }
            /// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
            ///         user (as opposed to a system deposit transaction generated by the system).
            /// @custom:field from        Address of the sender of the transaction.
            /// @custom:field to          Address of the recipient of the transaction.
            /// @custom:field isCreation  True if the transaction is a contract creation.
            /// @custom:field value       Value to send to the recipient.
            /// @custom:field mint        Amount of ETH to mint.
            /// @custom:field gasLimit    Gas limit of the transaction.
            /// @custom:field data        Data of the transaction.
            /// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
            /// @custom:field logIndex    Index of the log in the block the transaction was submitted in.
            struct UserDepositTransaction {
                address from;
                address to;
                bool isCreation;
                uint256 value;
                uint256 mint;
                uint64 gasLimit;
                bytes data;
                bytes32 l1BlockHash;
                uint256 logIndex;
            }
            /// @notice Struct representing a withdrawal transaction.
            /// @custom:field nonce    Nonce of the withdrawal transaction
            /// @custom:field sender   Address of the sender of the transaction.
            /// @custom:field target   Address of the recipient of the transaction.
            /// @custom:field value    Value to send to the recipient.
            /// @custom:field gasLimit Gas limit of the transaction.
            /// @custom:field data     Data of the transaction.
            struct WithdrawalTransaction {
                uint256 nonce;
                address sender;
                address target;
                uint256 value;
                uint256 gasLimit;
                bytes data;
            }
            /// @notice Enum representing where the FeeVault withdraws funds to.
            /// @custom:value L1 FeeVault withdraws funds to L1.
            /// @custom:value L2 FeeVault withdraws funds to L2.
            enum WithdrawalNetwork {
                L1,
                L2
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { Types } from "src/libraries/Types.sol";
        import { Encoding } from "src/libraries/Encoding.sol";
        /// @title Hashing
        /// @notice Hashing handles Optimism's various different hashing schemes.
        library Hashing {
            /// @notice Computes the hash of the RLP encoded L2 transaction that would be generated when a
            ///         given deposit is sent to the L2 system. Useful for searching for a deposit in the L2
            ///         system.
            /// @param _tx User deposit transaction to hash.
            /// @return Hash of the RLP encoded L2 deposit transaction.
            function hashDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes32) {
                return keccak256(Encoding.encodeDepositTransaction(_tx));
            }
            /// @notice Computes the deposit transaction's "source hash", a value that guarantees the hash
            ///         of the L2 transaction that corresponds to a deposit is unique and is
            ///         deterministically generated from L1 transaction data.
            /// @param _l1BlockHash Hash of the L1 block where the deposit was included.
            /// @param _logIndex    The index of the log that created the deposit transaction.
            /// @return Hash of the deposit transaction's "source hash".
            function hashDepositSource(bytes32 _l1BlockHash, uint256 _logIndex) internal pure returns (bytes32) {
                bytes32 depositId = keccak256(abi.encode(_l1BlockHash, _logIndex));
                return keccak256(abi.encode(bytes32(0), depositId));
            }
            /// @notice Hashes the cross domain message based on the version that is encoded into the
            ///         message nonce.
            /// @param _nonce    Message nonce with version encoded into the first two bytes.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessage(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes32)
            {
                (, uint16 version) = Encoding.decodeVersionedNonce(_nonce);
                if (version == 0) {
                    return hashCrossDomainMessageV0(_target, _sender, _data, _nonce);
                } else if (version == 1) {
                    return hashCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);
                } else {
                    revert("Hashing: unknown cross domain message version");
                }
            }
            /// @notice Hashes a cross domain message based on the V0 (legacy) encoding.
            /// @param _target Address of the target of the message.
            /// @param _sender Address of the sender of the message.
            /// @param _data   Data to send with the message.
            /// @param _nonce  Message nonce.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessageV0(
                address _target,
                address _sender,
                bytes memory _data,
                uint256 _nonce
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(Encoding.encodeCrossDomainMessageV0(_target, _sender, _data, _nonce));
            }
            /// @notice Hashes a cross domain message based on the V1 (current) encoding.
            /// @param _nonce    Message nonce.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Hashed cross domain message.
            function hashCrossDomainMessageV1(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(Encoding.encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data));
            }
            /// @notice Derives the withdrawal hash according to the encoding in the L2 Withdrawer contract
            /// @param _tx Withdrawal transaction to hash.
            /// @return Hashed withdrawal transaction.
            function hashWithdrawal(Types.WithdrawalTransaction memory _tx) internal pure returns (bytes32) {
                return keccak256(abi.encode(_tx.nonce, _tx.sender, _tx.target, _tx.value, _tx.gasLimit, _tx.data));
            }
            /// @notice Hashes the various elements of an output root proof into an output root hash which
            ///         can be used to check if the proof is valid.
            /// @param _outputRootProof Output root proof which should hash to an output root.
            /// @return Hashed output root proof.
            function hashOutputRootProof(Types.OutputRootProof memory _outputRootProof) internal pure returns (bytes32) {
                return keccak256(
                    abi.encode(
                        _outputRootProof.version,
                        _outputRootProof.stateRoot,
                        _outputRootProof.messagePasserStorageRoot,
                        _outputRootProof.latestBlockhash
                    )
                );
            }
            /// @notice Generates a unique hash for cross l2 messages. This hash is used to identify
            ///         the message and ensure it is not relayed more than once.
            /// @param _destination Chain ID of the destination chain.
            /// @param _source Chain ID of the source chain.
            /// @param _nonce Unique nonce associated with the message to prevent replay attacks.
            /// @param _sender Address of the user who originally sent the message.
            /// @param _target Address of the contract or wallet that the message is targeting on the destination chain.
            /// @param _message The message payload to be relayed to the target on the destination chain.
            /// @return Hash of the encoded message parameters, used to uniquely identify the message.
            function hashL2toL2CrossDomainMessage(
                uint256 _destination,
                uint256 _source,
                uint256 _nonce,
                address _sender,
                address _target,
                bytes memory _message
            )
                internal
                pure
                returns (bytes32)
            {
                return keccak256(abi.encode(_destination, _source, _nonce, _sender, _target, _message));
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.8;
        import "./RLPErrors.sol";
        /// @custom:attribution https://github.com/hamdiallam/Solidity-RLP
        /// @title RLPReader
        /// @notice RLPReader is a library for parsing RLP-encoded byte arrays into Solidity types. Adapted
        ///         from Solidity-RLP (https://github.com/hamdiallam/Solidity-RLP) by Hamdi Allam with
        ///         various tweaks to improve readability.
        library RLPReader {
            /// @notice Custom pointer type to avoid confusion between pointers and uint256s.
            type MemoryPointer is uint256;
            /// @notice RLP item types.
            /// @custom:value DATA_ITEM Represents an RLP data item (NOT a list).
            /// @custom:value LIST_ITEM Represents an RLP list item.
            enum RLPItemType {
                DATA_ITEM,
                LIST_ITEM
            }
            /// @notice Struct representing an RLP item.
            /// @custom:field length Length of the RLP item.
            /// @custom:field ptr    Pointer to the RLP item in memory.
            struct RLPItem {
                uint256 length;
                MemoryPointer ptr;
            }
            /// @notice Max list length that this library will accept.
            uint256 internal constant MAX_LIST_LENGTH = 32;
            /// @notice Converts bytes to a reference to memory position and length.
            /// @param _in Input bytes to convert.
            /// @return out_ Output memory reference.
            function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory out_) {
                // Empty arrays are not RLP items.
                if (_in.length == 0) revert EmptyItem();
                MemoryPointer ptr;
                assembly {
                    ptr := add(_in, 32)
                }
                out_ = RLPItem({ length: _in.length, ptr: ptr });
            }
            /// @notice Reads an RLP list value into a list of RLP items.
            /// @param _in RLP list value.
            /// @return out_ Decoded RLP list items.
            function readList(RLPItem memory _in) internal pure returns (RLPItem[] memory out_) {
                (uint256 listOffset, uint256 listLength, RLPItemType itemType) = _decodeLength(_in);
                if (itemType != RLPItemType.LIST_ITEM) revert UnexpectedString();
                if (listOffset + listLength != _in.length) revert InvalidDataRemainder();
                // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
                // writing to the length. Since we can't know the number of RLP items without looping over
                // the entire input, we'd have to loop twice to accurately size this array. It's easier to
                // simply set a reasonable maximum list length and decrease the size before we finish.
                out_ = new RLPItem[](MAX_LIST_LENGTH);
                uint256 itemCount = 0;
                uint256 offset = listOffset;
                while (offset < _in.length) {
                    (uint256 itemOffset, uint256 itemLength,) = _decodeLength(
                        RLPItem({ length: _in.length - offset, ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset) })
                    );
                    // We don't need to check itemCount < out.length explicitly because Solidity already
                    // handles this check on our behalf, we'd just be wasting gas.
                    out_[itemCount] = RLPItem({
                        length: itemLength + itemOffset,
                        ptr: MemoryPointer.wrap(MemoryPointer.unwrap(_in.ptr) + offset)
                    });
                    itemCount += 1;
                    offset += itemOffset + itemLength;
                }
                // Decrease the array size to match the actual item count.
                assembly {
                    mstore(out_, itemCount)
                }
            }
            /// @notice Reads an RLP list value into a list of RLP items.
            /// @param _in RLP list value.
            /// @return out_ Decoded RLP list items.
            function readList(bytes memory _in) internal pure returns (RLPItem[] memory out_) {
                out_ = readList(toRLPItem(_in));
            }
            /// @notice Reads an RLP bytes value into bytes.
            /// @param _in RLP bytes value.
            /// @return out_ Decoded bytes.
            function readBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
                (uint256 itemOffset, uint256 itemLength, RLPItemType itemType) = _decodeLength(_in);
                if (itemType != RLPItemType.DATA_ITEM) revert UnexpectedList();
                if (_in.length != itemOffset + itemLength) revert InvalidDataRemainder();
                out_ = _copy(_in.ptr, itemOffset, itemLength);
            }
            /// @notice Reads an RLP bytes value into bytes.
            /// @param _in RLP bytes value.
            /// @return out_ Decoded bytes.
            function readBytes(bytes memory _in) internal pure returns (bytes memory out_) {
                out_ = readBytes(toRLPItem(_in));
            }
            /// @notice Reads the raw bytes of an RLP item.
            /// @param _in RLP item to read.
            /// @return out_ Raw RLP bytes.
            function readRawBytes(RLPItem memory _in) internal pure returns (bytes memory out_) {
                out_ = _copy(_in.ptr, 0, _in.length);
            }
            /// @notice Decodes the length of an RLP item.
            /// @param _in RLP item to decode.
            /// @return offset_ Offset of the encoded data.
            /// @return length_ Length of the encoded data.
            /// @return type_ RLP item type (LIST_ITEM or DATA_ITEM).
            function _decodeLength(RLPItem memory _in)
                private
                pure
                returns (uint256 offset_, uint256 length_, RLPItemType type_)
            {
                // Short-circuit if there's nothing to decode, note that we perform this check when
                // the user creates an RLP item via toRLPItem, but it's always possible for them to bypass
                // that function and create an RLP item directly. So we need to check this anyway.
                if (_in.length == 0) revert EmptyItem();
                MemoryPointer ptr = _in.ptr;
                uint256 prefix;
                assembly {
                    prefix := byte(0, mload(ptr))
                }
                if (prefix <= 0x7f) {
                    // Single byte.
                    return (0, 1, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xb7) {
                    // Short string.
                    // slither-disable-next-line variable-scope
                    uint256 strLen = prefix - 0x80;
                    if (_in.length <= strLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (strLen == 1 && firstByteOfContent < 0x80) revert InvalidHeader();
                    return (1, strLen, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xbf) {
                    // Long string.
                    uint256 lenOfStrLen = prefix - 0xb7;
                    if (_in.length <= lenOfStrLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (firstByteOfContent == 0x00) revert InvalidHeader();
                    uint256 strLen;
                    assembly {
                        strLen := shr(sub(256, mul(8, lenOfStrLen)), mload(add(ptr, 1)))
                    }
                    if (strLen <= 55) revert InvalidHeader();
                    if (_in.length <= lenOfStrLen + strLen) revert ContentLengthMismatch();
                    return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
                } else if (prefix <= 0xf7) {
                    // Short list.
                    // slither-disable-next-line variable-scope
                    uint256 listLen = prefix - 0xc0;
                    if (_in.length <= listLen) revert ContentLengthMismatch();
                    return (1, listLen, RLPItemType.LIST_ITEM);
                } else {
                    // Long list.
                    uint256 lenOfListLen = prefix - 0xf7;
                    if (_in.length <= lenOfListLen) revert ContentLengthMismatch();
                    bytes1 firstByteOfContent;
                    assembly {
                        firstByteOfContent := and(mload(add(ptr, 1)), shl(248, 0xff))
                    }
                    if (firstByteOfContent == 0x00) revert InvalidHeader();
                    uint256 listLen;
                    assembly {
                        listLen := shr(sub(256, mul(8, lenOfListLen)), mload(add(ptr, 1)))
                    }
                    if (listLen <= 55) revert InvalidHeader();
                    if (_in.length <= lenOfListLen + listLen) revert ContentLengthMismatch();
                    return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
                }
            }
            /// @notice Copies the bytes from a memory location.
            /// @param _src    Pointer to the location to read from.
            /// @param _offset Offset to start reading from.
            /// @param _length Number of bytes to read.
            /// @return out_ Copied bytes.
            function _copy(MemoryPointer _src, uint256 _offset, uint256 _length) private pure returns (bytes memory out_) {
                out_ = new bytes(_length);
                if (_length == 0) {
                    return out_;
                }
                // Mostly based on Solidity's copy_memory_to_memory:
                // https://github.com/ethereum/solidity/blob/34dd30d71b4da730488be72ff6af7083cf2a91f6/libsolidity/codegen/YulUtilFunctions.cpp#L102-L114
                uint256 src = MemoryPointer.unwrap(_src) + _offset;
                assembly {
                    let dest := add(out_, 32)
                    let i := 0
                    for { } lt(i, _length) { i := add(i, 32) } { mstore(add(dest, i), mload(add(src, i))) }
                    if gt(i, _length) { mstore(add(dest, _length), 0) }
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title ISemver
        /// @notice ISemver is a simple contract for ensuring that contracts are
        ///         versioned using semantic versioning.
        interface ISemver {
            /// @notice Getter for the semantic version of the contract. This is not
            ///         meant to be used onchain but instead meant to be used by offchain
            ///         tooling.
            /// @return Semver contract version as a string.
            function version() external view returns (string memory);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        import "src/dispute/lib/LibPosition.sol";
        using LibClaim for Claim global;
        using LibHash for Hash global;
        using LibDuration for Duration global;
        using LibClock for Clock global;
        using LibGameId for GameId global;
        using LibTimestamp for Timestamp global;
        using LibVMStatus for VMStatus global;
        using LibGameType for GameType global;
        /// @notice A `Clock` represents a packed `Duration` and `Timestamp`
        /// @dev The packed layout of this type is as follows:
        /// ┌────────────┬────────────────┐
        /// │    Bits    │     Value      │
        /// ├────────────┼────────────────┤
        /// │ [0, 64)    │ Duration       │
        /// │ [64, 128)  │ Timestamp      │
        /// └────────────┴────────────────┘
        type Clock is uint128;
        /// @title LibClock
        /// @notice This library contains helper functions for working with the `Clock` type.
        library LibClock {
            /// @notice Packs a `Duration` and `Timestamp` into a `Clock` type.
            /// @param _duration The `Duration` to pack into the `Clock` type.
            /// @param _timestamp The `Timestamp` to pack into the `Clock` type.
            /// @return clock_ The `Clock` containing the `_duration` and `_timestamp`.
            function wrap(Duration _duration, Timestamp _timestamp) internal pure returns (Clock clock_) {
                assembly {
                    clock_ := or(shl(0x40, _duration), _timestamp)
                }
            }
            /// @notice Pull the `Duration` out of a `Clock` type.
            /// @param _clock The `Clock` type to pull the `Duration` out of.
            /// @return duration_ The `Duration` pulled out of `_clock`.
            function duration(Clock _clock) internal pure returns (Duration duration_) {
                // Shift the high-order 64 bits into the low-order 64 bits, leaving only the `duration`.
                assembly {
                    duration_ := shr(0x40, _clock)
                }
            }
            /// @notice Pull the `Timestamp` out of a `Clock` type.
            /// @param _clock The `Clock` type to pull the `Timestamp` out of.
            /// @return timestamp_ The `Timestamp` pulled out of `_clock`.
            function timestamp(Clock _clock) internal pure returns (Timestamp timestamp_) {
                // Clean the high-order 192 bits by shifting the clock left and then right again, leaving
                // only the `timestamp`.
                assembly {
                    timestamp_ := shr(0xC0, shl(0xC0, _clock))
                }
            }
            /// @notice Get the value of a `Clock` type in the form of the underlying uint128.
            /// @param _clock The `Clock` type to get the value of.
            /// @return clock_ The value of the `Clock` type as a uint128 type.
            function raw(Clock _clock) internal pure returns (uint128 clock_) {
                assembly {
                    clock_ := _clock
                }
            }
        }
        /// @notice A `GameId` represents a packed 4 byte game ID, a 8 byte timestamp, and a 20 byte address.
        /// @dev The packed layout of this type is as follows:
        /// ┌───────────┬───────────┐
        /// │   Bits    │   Value   │
        /// ├───────────┼───────────┤
        /// │ [0, 32)   │ Game Type │
        /// │ [32, 96)  │ Timestamp │
        /// │ [96, 256) │ Address   │
        /// └───────────┴───────────┘
        type GameId is bytes32;
        /// @title LibGameId
        /// @notice Utility functions for packing and unpacking GameIds.
        library LibGameId {
            /// @notice Packs values into a 32 byte GameId type.
            /// @param _gameType The game type.
            /// @param _timestamp The timestamp of the game's creation.
            /// @param _gameProxy The game proxy address.
            /// @return gameId_ The packed GameId.
            function pack(
                GameType _gameType,
                Timestamp _timestamp,
                address _gameProxy
            )
                internal
                pure
                returns (GameId gameId_)
            {
                assembly {
                    gameId_ := or(or(shl(224, _gameType), shl(160, _timestamp)), _gameProxy)
                }
            }
            /// @notice Unpacks values from a 32 byte GameId type.
            /// @param _gameId The packed GameId.
            /// @return gameType_ The game type.
            /// @return timestamp_ The timestamp of the game's creation.
            /// @return gameProxy_ The game proxy address.
            function unpack(GameId _gameId)
                internal
                pure
                returns (GameType gameType_, Timestamp timestamp_, address gameProxy_)
            {
                assembly {
                    gameType_ := shr(224, _gameId)
                    timestamp_ := and(shr(160, _gameId), 0xFFFFFFFFFFFFFFFF)
                    gameProxy_ := and(_gameId, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
                }
            }
        }
        /// @notice A claim represents an MPT root representing the state of the fault proof program.
        type Claim is bytes32;
        /// @title LibClaim
        /// @notice This library contains helper functions for working with the `Claim` type.
        library LibClaim {
            /// @notice Get the value of a `Claim` type in the form of the underlying bytes32.
            /// @param _claim The `Claim` type to get the value of.
            /// @return claim_ The value of the `Claim` type as a bytes32 type.
            function raw(Claim _claim) internal pure returns (bytes32 claim_) {
                assembly {
                    claim_ := _claim
                }
            }
            /// @notice Hashes a claim and a position together.
            /// @param _claim A Claim type.
            /// @param _position The position of `claim`.
            /// @param _challengeIndex The index of the claim being moved against.
            /// @return claimHash_ A hash of abi.encodePacked(claim, position|challengeIndex);
            function hashClaimPos(
                Claim _claim,
                Position _position,
                uint256 _challengeIndex
            )
                internal
                pure
                returns (Hash claimHash_)
            {
                assembly {
                    mstore(0x00, _claim)
                    mstore(0x20, or(shl(128, _position), and(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, _challengeIndex)))
                    claimHash_ := keccak256(0x00, 0x40)
                }
            }
        }
        /// @notice A dedicated duration type.
        /// @dev Unit: seconds
        type Duration is uint64;
        /// @title LibDuration
        /// @notice This library contains helper functions for working with the `Duration` type.
        library LibDuration {
            /// @notice Get the value of a `Duration` type in the form of the underlying uint64.
            /// @param _duration The `Duration` type to get the value of.
            /// @return duration_ The value of the `Duration` type as a uint64 type.
            function raw(Duration _duration) internal pure returns (uint64 duration_) {
                assembly {
                    duration_ := _duration
                }
            }
        }
        /// @notice A custom type for a generic hash.
        type Hash is bytes32;
        /// @title LibHash
        /// @notice This library contains helper functions for working with the `Hash` type.
        library LibHash {
            /// @notice Get the value of a `Hash` type in the form of the underlying bytes32.
            /// @param _hash The `Hash` type to get the value of.
            /// @return hash_ The value of the `Hash` type as a bytes32 type.
            function raw(Hash _hash) internal pure returns (bytes32 hash_) {
                assembly {
                    hash_ := _hash
                }
            }
        }
        /// @notice A dedicated timestamp type.
        type Timestamp is uint64;
        /// @title LibTimestamp
        /// @notice This library contains helper functions for working with the `Timestamp` type.
        library LibTimestamp {
            /// @notice Get the value of a `Timestamp` type in the form of the underlying uint64.
            /// @param _timestamp The `Timestamp` type to get the value of.
            /// @return timestamp_ The value of the `Timestamp` type as a uint64 type.
            function raw(Timestamp _timestamp) internal pure returns (uint64 timestamp_) {
                assembly {
                    timestamp_ := _timestamp
                }
            }
        }
        /// @notice A `VMStatus` represents the status of a VM execution.
        type VMStatus is uint8;
        /// @title LibVMStatus
        /// @notice This library contains helper functions for working with the `VMStatus` type.
        library LibVMStatus {
            /// @notice Get the value of a `VMStatus` type in the form of the underlying uint8.
            /// @param _vmstatus The `VMStatus` type to get the value of.
            /// @return vmstatus_ The value of the `VMStatus` type as a uint8 type.
            function raw(VMStatus _vmstatus) internal pure returns (uint8 vmstatus_) {
                assembly {
                    vmstatus_ := _vmstatus
                }
            }
        }
        /// @notice A `GameType` represents the type of game being played.
        type GameType is uint32;
        /// @title LibGameType
        /// @notice This library contains helper functions for working with the `GameType` type.
        library LibGameType {
            /// @notice Get the value of a `GameType` type in the form of the underlying uint32.
            /// @param _gametype The `GameType` type to get the value of.
            /// @return gametype_ The value of the `GameType` type as a uint32 type.
            function raw(GameType _gametype) internal pure returns (uint32 gametype_) {
                assembly {
                    gametype_ := _gametype
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface ISuperchainConfig {
            enum UpdateType {
                GUARDIAN
            }
            event ConfigUpdate(UpdateType indexed updateType, bytes data);
            event Initialized(uint8 version);
            event Paused(string identifier);
            event Unpaused();
            function GUARDIAN_SLOT() external view returns (bytes32);
            function PAUSED_SLOT() external view returns (bytes32);
            function guardian() external view returns (address guardian_);
            function initialize(address _guardian, bool _paused) external;
            function pause(string memory _identifier) external;
            function paused() external view returns (bool paused_);
            function unpause() external;
            function version() external view returns (string memory);
            function __constructor__() external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol";
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
        import { IBigStepper } from "src/dispute/interfaces/IBigStepper.sol";
        import { Types } from "src/libraries/Types.sol";
        import "src/dispute/lib/Types.sol";
        interface IFaultDisputeGame is IDisputeGame {
            struct ClaimData {
                uint32 parentIndex;
                address counteredBy;
                address claimant;
                uint128 bond;
                Claim claim;
                Position position;
                Clock clock;
            }
            struct ResolutionCheckpoint {
                bool initialCheckpointComplete;
                uint32 subgameIndex;
                Position leftmostPosition;
                address counteredBy;
            }
            error AlreadyInitialized();
            error AnchorRootNotFound();
            error BlockNumberMatches();
            error BondTransferFailed();
            error CannotDefendRootClaim();
            error ClaimAboveSplit();
            error ClaimAlreadyExists();
            error ClaimAlreadyResolved();
            error ClockNotExpired();
            error ClockTimeExceeded();
            error ContentLengthMismatch();
            error DuplicateStep();
            error EmptyItem();
            error GameDepthExceeded();
            error GameNotInProgress();
            error IncorrectBondAmount();
            error InvalidChallengePeriod();
            error InvalidClockExtension();
            error InvalidDataRemainder();
            error InvalidDisputedClaimIndex();
            error InvalidHeader();
            error InvalidHeaderRLP();
            error InvalidLocalIdent();
            error InvalidOutputRootProof();
            error InvalidParent();
            error InvalidPrestate();
            error InvalidSplitDepth();
            error L2BlockNumberChallenged();
            error MaxDepthTooLarge();
            error NoCreditToClaim();
            error OutOfOrderResolution();
            error UnexpectedList();
            error UnexpectedRootClaim(Claim rootClaim);
            error UnexpectedString();
            error ValidStep();
            event Move(uint256 indexed parentIndex, Claim indexed claim, address indexed claimant);
            function absolutePrestate() external view returns (Claim absolutePrestate_);
            function addLocalData(uint256 _ident, uint256 _execLeafIdx, uint256 _partOffset) external;
            function anchorStateRegistry() external view returns (IAnchorStateRegistry registry_);
            function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable;
            function challengeRootL2Block(Types.OutputRootProof memory _outputRootProof, bytes memory _headerRLP) external;
            function claimCredit(address _recipient) external;
            function claimData(uint256)
                external
                view // nosemgrep
                returns (
                    uint32 parentIndex,
                    address counteredBy,
                    address claimant,
                    uint128 bond,
                    Claim claim,
                    Position position,
                    Clock clock
                );
            function claimDataLen() external view returns (uint256 len_);
            function claims(Hash) external view returns (bool);
            function clockExtension() external view returns (Duration clockExtension_);
            function credit(address) external view returns (uint256);
            function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable;
            function getChallengerDuration(uint256 _claimIndex) external view returns (Duration duration_);
            function getNumToResolve(uint256 _claimIndex) external view returns (uint256 numRemainingChildren_);
            function getRequiredBond(Position _position) external view returns (uint256 requiredBond_);
            function l2BlockNumber() external pure returns (uint256 l2BlockNumber_);
            function l2BlockNumberChallenged() external view returns (bool);
            function l2BlockNumberChallenger() external view returns (address);
            function l2ChainId() external view returns (uint256 l2ChainId_);
            function maxClockDuration() external view returns (Duration maxClockDuration_);
            function maxGameDepth() external view returns (uint256 maxGameDepth_);
            function move(Claim _disputed, uint256 _challengeIndex, Claim _claim, bool _isAttack) external payable;
            function resolutionCheckpoints(uint256)
                external
                view
                returns (bool initialCheckpointComplete, uint32 subgameIndex, Position leftmostPosition, address counteredBy); // nosemgrep
            function resolveClaim(uint256 _claimIndex, uint256 _numToResolve) external;
            function resolvedSubgames(uint256) external view returns (bool);
            function splitDepth() external view returns (uint256 splitDepth_);
            function startingBlockNumber() external view returns (uint256 startingBlockNumber_);
            function startingOutputRoot() external view returns (Hash root, uint256 l2BlockNumber); // nosemgrep
            function startingRootHash() external view returns (Hash startingRootHash_);
            function step(uint256 _claimIndex, bool _isAttack, bytes memory _stateData, bytes memory _proof) external;
            function subgames(uint256, uint256) external view returns (uint256);
            function version() external view returns (string memory);
            function vm() external view returns (IBigStepper vm_);
            function weth() external view returns (IDelayedWETH weth_);
            function __constructor__(
                GameType _gameType,
                Claim _absolutePrestate,
                uint256 _maxGameDepth,
                uint256 _splitDepth,
                Duration _clockExtension,
                Duration _maxClockDuration,
                IBigStepper _vm,
                IDelayedWETH _weth,
                IAnchorStateRegistry _anchorStateRegistry,
                uint256 _l2ChainId
            )
                external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol";
        import "src/dispute/lib/Types.sol";
        interface IDisputeGameFactory {
            struct GameSearchResult {
                uint256 index;
                GameId metadata;
                Timestamp timestamp;
                Claim rootClaim;
                bytes extraData;
            }
            error GameAlreadyExists(Hash uuid);
            error IncorrectBondAmount();
            error NoImplementation(GameType gameType);
            event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim);
            event ImplementationSet(address indexed impl, GameType indexed gameType);
            event InitBondUpdated(GameType indexed gameType, uint256 indexed newBond);
            event Initialized(uint8 version);
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            function create(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                payable
                returns (IDisputeGame proxy_);
            function findLatestGames(
                GameType _gameType,
                uint256 _start,
                uint256 _n
            )
                external
                view
                returns (GameSearchResult[] memory games_);
            function gameAtIndex(uint256 _index)
                external
                view
                returns (GameType gameType_, Timestamp timestamp_, IDisputeGame proxy_);
            function gameCount() external view returns (uint256 gameCount_);
            function gameImpls(GameType) external view returns (IDisputeGame);
            function games(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                view
                returns (IDisputeGame proxy_, Timestamp timestamp_);
            function getGameUUID(
                GameType _gameType,
                Claim _rootClaim,
                bytes memory _extraData
            )
                external
                pure
                returns (Hash uuid_);
            function initBonds(GameType) external view returns (uint256);
            function initialize(address _owner) external;
            function owner() external view returns (address);
            function renounceOwnership() external;
            function setImplementation(GameType _gameType, IDisputeGame _impl) external;
            function setInitBond(GameType _gameType, uint256 _initBond) external;
            function transferOwnership(address newOwner) external; // nosemgrep
            function version() external view returns (string memory);
            function __constructor__() external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { LibKeccak } from "@lib-keccak/LibKeccak.sol";
        import { LPPMetaData } from "src/cannon/libraries/CannonTypes.sol";
        interface IPreimageOracle {
            struct Leaf {
                bytes input;
                uint256 index;
                bytes32 stateCommitment;
            }
            error ActiveProposal();
            error AlreadyFinalized();
            error AlreadyInitialized();
            error BadProposal();
            error BondTransferFailed();
            error InsufficientBond();
            error InvalidInputSize();
            error InvalidPreimage();
            error InvalidProof();
            error NotEOA();
            error NotInitialized();
            error PartOffsetOOB();
            error PostStateMatches();
            error StatesNotContiguous();
            error TreeSizeOverflow();
            error WrongStartingBlock();
            function KECCAK_TREE_DEPTH() external view returns (uint256);
            function MAX_LEAF_COUNT() external view returns (uint256);
            function MIN_BOND_SIZE() external view returns (uint256);
            function PRECOMPILE_CALL_RESERVED_GAS() external view returns (uint256);
            function addLeavesLPP(
                uint256 _uuid,
                uint256 _inputStartBlock,
                bytes memory _input,
                bytes32[] memory _stateCommitments,
                bool _finalize
            )
                external;
            function challengeFirstLPP(
                address _claimant,
                uint256 _uuid,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function challengeLPP(
                address _claimant,
                uint256 _uuid,
                LibKeccak.StateMatrix memory _stateMatrix,
                Leaf memory _preState,
                bytes32[] memory _preStateProof,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function challengePeriod() external view returns (uint256 challengePeriod_);
            function getTreeRootLPP(address _owner, uint256 _uuid) external view returns (bytes32 treeRoot_);
            function initLPP(uint256 _uuid, uint32 _partOffset, uint32 _claimedSize) external payable;
            function loadBlobPreimagePart(
                uint256 _z,
                uint256 _y,
                bytes memory _commitment,
                bytes memory _proof,
                uint256 _partOffset
            )
                external;
            function loadKeccak256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
            function loadLocalData(
                uint256 _ident,
                bytes32 _localContext,
                bytes32 _word,
                uint256 _size,
                uint256 _partOffset
            )
                external
                returns (bytes32 key_);
            function loadPrecompilePreimagePart(
                uint256 _partOffset,
                address _precompile,
                uint64 _requiredGas,
                bytes memory _input
            )
                external;
            function loadSha256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
            function minProposalSize() external view returns (uint256 minProposalSize_);
            function preimageLengths(bytes32) external view returns (uint256);
            function preimagePartOk(bytes32, uint256) external view returns (bool);
            function preimageParts(bytes32, uint256) external view returns (bytes32);
            function proposalBlocks(address, uint256, uint256) external view returns (uint64);
            function proposalBlocksLen(address _claimant, uint256 _uuid) external view returns (uint256 len_);
            function proposalBonds(address, uint256) external view returns (uint256);
            function proposalBranches(address, uint256, uint256) external view returns (bytes32);
            function proposalCount() external view returns (uint256 count_);
            function proposalMetadata(address, uint256) external view returns (LPPMetaData);
            function proposalParts(address, uint256) external view returns (bytes32);
            function proposals(uint256) external view returns (address claimant, uint256 uuid); // nosemgrep:
                // sol-style-return-arg-fmt
            function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_);
            function squeezeLPP(
                address _claimant,
                uint256 _uuid,
                LibKeccak.StateMatrix memory _stateMatrix,
                Leaf memory _preState,
                bytes32[] memory _preStateProof,
                Leaf memory _postState,
                bytes32[] memory _postStateProof
            )
                external;
            function version() external view returns (string memory);
            function zeroHashes(uint256) external view returns (bytes32);
            function __constructor__(uint256 _minProposalSize, uint256 _challengePeriod) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { Types } from "src/libraries/Types.sol";
        import { Hashing } from "src/libraries/Hashing.sol";
        import { RLPWriter } from "src/libraries/rlp/RLPWriter.sol";
        /// @title Encoding
        /// @notice Encoding handles Optimism's various different encoding schemes.
        library Encoding {
            /// @notice RLP encodes the L2 transaction that would be generated when a given deposit is sent
            ///         to the L2 system. Useful for searching for a deposit in the L2 system. The
            ///         transaction is prefixed with 0x7e to identify its EIP-2718 type.
            /// @param _tx User deposit transaction to encode.
            /// @return RLP encoded L2 deposit transaction.
            function encodeDepositTransaction(Types.UserDepositTransaction memory _tx) internal pure returns (bytes memory) {
                bytes32 source = Hashing.hashDepositSource(_tx.l1BlockHash, _tx.logIndex);
                bytes[] memory raw = new bytes[](8);
                raw[0] = RLPWriter.writeBytes(abi.encodePacked(source));
                raw[1] = RLPWriter.writeAddress(_tx.from);
                raw[2] = _tx.isCreation ? RLPWriter.writeBytes("") : RLPWriter.writeAddress(_tx.to);
                raw[3] = RLPWriter.writeUint(_tx.mint);
                raw[4] = RLPWriter.writeUint(_tx.value);
                raw[5] = RLPWriter.writeUint(uint256(_tx.gasLimit));
                raw[6] = RLPWriter.writeBool(false);
                raw[7] = RLPWriter.writeBytes(_tx.data);
                return abi.encodePacked(uint8(0x7e), RLPWriter.writeList(raw));
            }
            /// @notice Encodes the cross domain message based on the version that is encoded into the
            ///         message nonce.
            /// @param _nonce    Message nonce with version encoded into the first two bytes.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessage(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes memory)
            {
                (, uint16 version) = decodeVersionedNonce(_nonce);
                if (version == 0) {
                    return encodeCrossDomainMessageV0(_target, _sender, _data, _nonce);
                } else if (version == 1) {
                    return encodeCrossDomainMessageV1(_nonce, _sender, _target, _value, _gasLimit, _data);
                } else {
                    revert("Encoding: unknown cross domain message version");
                }
            }
            /// @notice Encodes a cross domain message based on the V0 (legacy) encoding.
            /// @param _target Address of the target of the message.
            /// @param _sender Address of the sender of the message.
            /// @param _data   Data to send with the message.
            /// @param _nonce  Message nonce.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessageV0(
                address _target,
                address _sender,
                bytes memory _data,
                uint256 _nonce
            )
                internal
                pure
                returns (bytes memory)
            {
                // nosemgrep: sol-style-use-abi-encodecall
                return abi.encodeWithSignature("relayMessage(address,address,bytes,uint256)", _target, _sender, _data, _nonce);
            }
            /// @notice Encodes a cross domain message based on the V1 (current) encoding.
            /// @param _nonce    Message nonce.
            /// @param _sender   Address of the sender of the message.
            /// @param _target   Address of the target of the message.
            /// @param _value    ETH value to send to the target.
            /// @param _gasLimit Gas limit to use for the message.
            /// @param _data     Data to send with the message.
            /// @return Encoded cross domain message.
            function encodeCrossDomainMessageV1(
                uint256 _nonce,
                address _sender,
                address _target,
                uint256 _value,
                uint256 _gasLimit,
                bytes memory _data
            )
                internal
                pure
                returns (bytes memory)
            {
                // nosemgrep: sol-style-use-abi-encodecall
                return abi.encodeWithSignature(
                    "relayMessage(uint256,address,address,uint256,uint256,bytes)",
                    _nonce,
                    _sender,
                    _target,
                    _value,
                    _gasLimit,
                    _data
                );
            }
            /// @notice Adds a version number into the first two bytes of a message nonce.
            /// @param _nonce   Message nonce to encode into.
            /// @param _version Version number to encode into the message nonce.
            /// @return Message nonce with version encoded into the first two bytes.
            function encodeVersionedNonce(uint240 _nonce, uint16 _version) internal pure returns (uint256) {
                uint256 nonce;
                assembly {
                    nonce := or(shl(240, _version), _nonce)
                }
                return nonce;
            }
            /// @notice Pulls the version out of a version-encoded nonce.
            /// @param _nonce Message nonce with version encoded into the first two bytes.
            /// @return Nonce without encoded version.
            /// @return Version of the message.
            function decodeVersionedNonce(uint256 _nonce) internal pure returns (uint240, uint16) {
                uint240 nonce;
                uint16 version;
                assembly {
                    nonce := and(_nonce, 0x0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                    version := shr(240, _nonce)
                }
                return (nonce, version);
            }
            /// @notice Returns an appropriately encoded call to L1Block.setL1BlockValuesEcotone
            /// @param _baseFeeScalar       L1 base fee Scalar
            /// @param _blobBaseFeeScalar   L1 blob base fee Scalar
            /// @param _sequenceNumber      Number of L2 blocks since epoch start.
            /// @param _timestamp           L1 timestamp.
            /// @param _number              L1 blocknumber.
            /// @param _baseFee             L1 base fee.
            /// @param _blobBaseFee         L1 blob base fee.
            /// @param _hash                L1 blockhash.
            /// @param _batcherHash         Versioned hash to authenticate batcher by.
            function encodeSetL1BlockValuesEcotone(
                uint32 _baseFeeScalar,
                uint32 _blobBaseFeeScalar,
                uint64 _sequenceNumber,
                uint64 _timestamp,
                uint64 _number,
                uint256 _baseFee,
                uint256 _blobBaseFee,
                bytes32 _hash,
                bytes32 _batcherHash
            )
                internal
                pure
                returns (bytes memory)
            {
                bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesEcotone()"));
                return abi.encodePacked(
                    functionSignature,
                    _baseFeeScalar,
                    _blobBaseFeeScalar,
                    _sequenceNumber,
                    _timestamp,
                    _number,
                    _baseFee,
                    _blobBaseFee,
                    _hash,
                    _batcherHash
                );
            }
            /// @notice Returns an appropriately encoded call to L1Block.setL1BlockValuesInterop
            /// @param _baseFeeScalar       L1 base fee Scalar
            /// @param _blobBaseFeeScalar   L1 blob base fee Scalar
            /// @param _sequenceNumber      Number of L2 blocks since epoch start.
            /// @param _timestamp           L1 timestamp.
            /// @param _number              L1 blocknumber.
            /// @param _baseFee             L1 base fee.
            /// @param _blobBaseFee         L1 blob base fee.
            /// @param _hash                L1 blockhash.
            /// @param _batcherHash         Versioned hash to authenticate batcher by.
            function encodeSetL1BlockValuesInterop(
                uint32 _baseFeeScalar,
                uint32 _blobBaseFeeScalar,
                uint64 _sequenceNumber,
                uint64 _timestamp,
                uint64 _number,
                uint256 _baseFee,
                uint256 _blobBaseFee,
                bytes32 _hash,
                bytes32 _batcherHash
            )
                internal
                pure
                returns (bytes memory)
            {
                bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesInterop()"));
                return abi.encodePacked(
                    functionSignature,
                    _baseFeeScalar,
                    _blobBaseFeeScalar,
                    _sequenceNumber,
                    _timestamp,
                    _number,
                    _baseFee,
                    _blobBaseFee,
                    _hash,
                    _batcherHash
                );
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @notice The length of an RLP item must be greater than zero to be decodable
        error EmptyItem();
        /// @notice The decoded item type for list is not a list item
        error UnexpectedString();
        /// @notice The RLP item has an invalid data remainder
        error InvalidDataRemainder();
        /// @notice Decoded item type for bytes is not a string item
        error UnexpectedList();
        /// @notice The length of the content must be greater than the RLP item length
        error ContentLengthMismatch();
        /// @notice Invalid RLP header for RLP item
        error InvalidHeader();
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.15;
        using LibPosition for Position global;
        /// @notice A `Position` represents a position of a claim within the game tree.
        /// @dev This is represented as a "generalized index" where the high-order bit
        /// is the level in the tree and the remaining bits is a unique bit pattern, allowing
        /// a unique identifier for each node in the tree. Mathematically, it is calculated
        /// as 2^{depth} + indexAtDepth.
        type Position is uint128;
        /// @title LibPosition
        /// @notice This library contains helper functions for working with the `Position` type.
        library LibPosition {
            /// @notice the `MAX_POSITION_BITLEN` is the number of bits that the `Position` type, and the implementation of
            ///         its behavior within this library, can safely support.
            uint8 internal constant MAX_POSITION_BITLEN = 126;
            /// @notice Computes a generalized index (2^{depth} + indexAtDepth).
            /// @param _depth The depth of the position.
            /// @param _indexAtDepth The index at the depth of the position.
            /// @return position_ The computed generalized index.
            function wrap(uint8 _depth, uint128 _indexAtDepth) internal pure returns (Position position_) {
                assembly {
                    // gindex = 2^{_depth} + _indexAtDepth
                    position_ := add(shl(_depth, 1), _indexAtDepth)
                }
            }
            /// @notice Pulls the `depth` out of a `Position` type.
            /// @param _position The generalized index to get the `depth` of.
            /// @return depth_ The `depth` of the `position` gindex.
            /// @custom:attribution Solady <https://github.com/Vectorized/Solady>
            function depth(Position _position) internal pure returns (uint8 depth_) {
                // Return the most significant bit offset, which signifies the depth of the gindex.
                assembly {
                    depth_ := or(depth_, shl(6, lt(0xffffffffffffffff, shr(depth_, _position))))
                    depth_ := or(depth_, shl(5, lt(0xffffffff, shr(depth_, _position))))
                    // For the remaining 32 bits, use a De Bruijn lookup.
                    _position := shr(depth_, _position)
                    _position := or(_position, shr(1, _position))
                    _position := or(_position, shr(2, _position))
                    _position := or(_position, shr(4, _position))
                    _position := or(_position, shr(8, _position))
                    _position := or(_position, shr(16, _position))
                    depth_ :=
                        or(
                            depth_,
                            byte(
                                shr(251, mul(_position, shl(224, 0x07c4acdd))),
                                0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
                            )
                        )
                }
            }
            /// @notice Pulls the `indexAtDepth` out of a `Position` type.
            ///         The `indexAtDepth` is the left/right index of a position at a specific depth within
            ///         the binary tree, starting from index 0. For example, at gindex 2, the `depth` = 1
            ///         and the `indexAtDepth` = 0.
            /// @param _position The generalized index to get the `indexAtDepth` of.
            /// @return indexAtDepth_ The `indexAtDepth` of the `position` gindex.
            function indexAtDepth(Position _position) internal pure returns (uint128 indexAtDepth_) {
                // Return bits p_{msb-1}...p_{0}. This effectively pulls the 2^{depth} out of the gindex,
                // leaving only the `indexAtDepth`.
                uint256 msb = depth(_position);
                assembly {
                    indexAtDepth_ := sub(_position, shl(msb, 1))
                }
            }
            /// @notice Get the left child of `_position`.
            /// @param _position The position to get the left position of.
            /// @return left_ The position to the left of `position`.
            function left(Position _position) internal pure returns (Position left_) {
                assembly {
                    left_ := shl(1, _position)
                }
            }
            /// @notice Get the right child of `_position`
            /// @param _position The position to get the right position of.
            /// @return right_ The position to the right of `position`.
            function right(Position _position) internal pure returns (Position right_) {
                assembly {
                    right_ := or(1, shl(1, _position))
                }
            }
            /// @notice Get the parent position of `_position`.
            /// @param _position The position to get the parent position of.
            /// @return parent_ The parent position of `position`.
            function parent(Position _position) internal pure returns (Position parent_) {
                assembly {
                    parent_ := shr(1, _position)
                }
            }
            /// @notice Get the deepest, right most gindex relative to the `position`. This is equivalent to
            ///         calling `right` on a position until the maximum depth is reached.
            /// @param _position The position to get the relative deepest, right most gindex of.
            /// @param _maxDepth The maximum depth of the game.
            /// @return rightIndex_ The deepest, right most gindex relative to the `position`.
            function rightIndex(Position _position, uint256 _maxDepth) internal pure returns (Position rightIndex_) {
                uint256 msb = depth(_position);
                assembly {
                    let remaining := sub(_maxDepth, msb)
                    rightIndex_ := or(shl(remaining, _position), sub(shl(remaining, 1), 1))
                }
            }
            /// @notice Get the deepest, right most trace index relative to the `position`. This is
            ///         equivalent to calling `right` on a position until the maximum depth is reached and
            ///         then finding its index at depth.
            /// @param _position The position to get the relative trace index of.
            /// @param _maxDepth The maximum depth of the game.
            /// @return traceIndex_ The trace index relative to the `position`.
            function traceIndex(Position _position, uint256 _maxDepth) internal pure returns (uint256 traceIndex_) {
                uint256 msb = depth(_position);
                assembly {
                    let remaining := sub(_maxDepth, msb)
                    traceIndex_ := sub(or(shl(remaining, _position), sub(shl(remaining, 1), 1)), shl(_maxDepth, 1))
                }
            }
            /// @notice Gets the position of the highest ancestor of `_position` that commits to the same
            ///         trace index.
            /// @param _position The position to get the highest ancestor of.
            /// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
            function traceAncestor(Position _position) internal pure returns (Position ancestor_) {
                // Create a field with only the lowest unset bit of `_position` set.
                Position lsb;
                assembly {
                    lsb := and(not(_position), add(_position, 1))
                }
                // Find the index of the lowest unset bit within the field.
                uint256 msb = depth(lsb);
                // The highest ancestor that commits to the same trace index is the original position
                // shifted right by the index of the lowest unset bit.
                assembly {
                    let a := shr(msb, _position)
                    // Bound the ancestor to the minimum gindex, 1.
                    ancestor_ := or(a, iszero(a))
                }
            }
            /// @notice Gets the position of the highest ancestor of `_position` that commits to the same
            ///         trace index, while still being below `_upperBoundExclusive`.
            /// @param _position The position to get the highest ancestor of.
            /// @param _upperBoundExclusive The exclusive upper depth bound, used to inform where to stop in order
            ///                             to not escape a sub-tree.
            /// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
            function traceAncestorBounded(
                Position _position,
                uint256 _upperBoundExclusive
            )
                internal
                pure
                returns (Position ancestor_)
            {
                // This function only works for positions that are below the upper bound.
                if (_position.depth() <= _upperBoundExclusive) {
                    assembly {
                        // Revert with `ClaimAboveSplit()`
                        mstore(0x00, 0xb34b5c22)
                        revert(0x1C, 0x04)
                    }
                }
                // Grab the global trace ancestor.
                ancestor_ = traceAncestor(_position);
                // If the ancestor is above or at the upper bound, shift it to be below the upper bound.
                // This should be a special case that only covers positions that commit to the final leaf
                // in a sub-tree.
                if (ancestor_.depth() <= _upperBoundExclusive) {
                    ancestor_ = ancestor_.rightIndex(_upperBoundExclusive + 1);
                }
            }
            /// @notice Get the move position of `_position`, which is the left child of:
            ///         1. `_position` if `_isAttack` is true.
            ///         2. `_position | 1` if `_isAttack` is false.
            /// @param _position The position to get the relative attack/defense position of.
            /// @param _isAttack Whether or not the move is an attack move.
            /// @return move_ The move position relative to `position`.
            function move(Position _position, bool _isAttack) internal pure returns (Position move_) {
                assembly {
                    move_ := shl(1, or(iszero(_isAttack), _position))
                }
            }
            /// @notice Get the value of a `Position` type in the form of the underlying uint128.
            /// @param _position The position to get the value of.
            /// @return raw_ The value of the `position` as a uint128 type.
            function raw(Position _position) internal pure returns (uint128 raw_) {
                assembly {
                    raw_ := _position
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IInitializable } from "src/dispute/interfaces/IInitializable.sol";
        import "src/dispute/lib/Types.sol";
        interface IDisputeGame is IInitializable {
            event Resolved(GameStatus indexed status);
            function createdAt() external view returns (Timestamp);
            function resolvedAt() external view returns (Timestamp);
            function status() external view returns (GameStatus);
            function gameType() external view returns (GameType gameType_);
            function gameCreator() external pure returns (address creator_);
            function rootClaim() external pure returns (Claim rootClaim_);
            function l1Head() external pure returns (Hash l1Head_);
            function extraData() external pure returns (bytes memory extraData_);
            function resolve() external returns (GameStatus status_);
            function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        /// @title LibKeccak
        /// @notice An EVM implementation of the Keccak-f[1600] permutation.
        /// @author clabby <https://github.com/clabby>
        /// @custom:attribution geohot <https://github.com/geohot>
        library LibKeccak {
            /// @notice The block size of the Keccak-f[1600] permutation, 1088 bits (136 bytes).
            uint256 internal constant BLOCK_SIZE_BYTES = 136;
            /// @notice The round constants for the keccak256 hash function. Packed in memory for efficient reading during the
            ///         permutation.
            bytes internal constant ROUND_CONSTANTS = abi.encode(
                0x00000000000000010000000000008082800000000000808a8000000080008000, // r1,r2,r3,r4
                0x000000000000808b000000008000000180000000800080818000000000008009, // r5,r6,r7,r8
                0x000000000000008a00000000000000880000000080008009000000008000000a, // r9,r10,r11,r12
                0x000000008000808b800000000000008b80000000000080898000000000008003, // r13,r14,r15,r16
                0x80000000000080028000000000000080000000000000800a800000008000000a, // r17,r18,r19,r20
                0x8000000080008081800000000000808000000000800000018000000080008008 // r21,r22,r23,r24
            );
            /// @notice A mask for 64-bit values.
            uint64 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
            /// @notice The 5x5 state matrix for the keccak-f[1600] permutation.
            struct StateMatrix {
                uint64[25] state;
            }
            /// @notice Performs the Keccak-f[1600] permutation on the given 5x5 state matrix.
            function permutation(StateMatrix memory _stateMatrix) internal pure {
                // Pull the round constants into memory to avoid reallocation in the unrolled permutation loop.
                bytes memory roundConstants = ROUND_CONSTANTS;
                assembly {
                    // Add 32 to the state matrix pointer to skip the data location field.
                    let stateMatrixPtr := add(_stateMatrix, 0x20)
                    let rcPtr := add(roundConstants, 0x20)
                    // set a state element in the passed `StateMatrix` struct memory ptr.
                    function setStateElem(ptr, idx, data) {
                        mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    // 64 bit logical shift
                    function shl64(a, b) -> val {
                        val := and(shl(a, b), U64_MASK)
                    }
                    // Performs an indivudual rho + pi computation, to be used in the full `thetaRhoPi` chain.
                    function rhoPi(ptr, destIdx, srcIdx, fact, dt) {
                        let xs1 := xor(stateElem(ptr, srcIdx), dt)
                        let res := xor(shl(fact, xs1), shr(sub(64, fact), xs1))
                        setStateElem(ptr, destIdx, res)
                    }
                    // xor a column in the state matrix
                    function xorColumn(ptr, col) -> val {
                        val :=
                            xor(
                                xor(xor(stateElem(ptr, col), stateElem(ptr, add(col, 5))), stateElem(ptr, add(col, 10))),
                                xor(stateElem(ptr, add(col, 15)), stateElem(ptr, add(col, 20)))
                            )
                    }
                    // Performs the `theta`, `rho`, and `pi` steps of the Keccak-f[1600] permutation on
                    // the passed `StateMatrix` struct memory ptr.
                    function thetaRhoPi(ptr) {
                        // Theta
                        let C0 := xorColumn(ptr, 0)
                        let C1 := xorColumn(ptr, 1)
                        let C2 := xorColumn(ptr, 2)
                        let C3 := xorColumn(ptr, 3)
                        let C4 := xorColumn(ptr, 4)
                        let D0 := xor(xor(shl64(1, C1), shr(63, C1)), C4)
                        let D1 := xor(xor(shl64(1, C2), shr(63, C2)), C0)
                        let D2 := xor(xor(shl64(1, C3), shr(63, C3)), C1)
                        let D3 := xor(xor(shl64(1, C4), shr(63, C4)), C2)
                        let D4 := xor(xor(shl64(1, C0), shr(63, C0)), C3)
                        let xs1 := xor(stateElem(ptr, 1), D1)
                        let A1 := xor(shl(1, xs1), shr(63, xs1))
                        setStateElem(ptr, 0, xor(stateElem(ptr, 0), D0))
                        rhoPi(ptr, 1, 6, 44, D1)
                        rhoPi(ptr, 6, 9, 20, D4)
                        rhoPi(ptr, 9, 22, 61, D2)
                        rhoPi(ptr, 22, 14, 39, D4)
                        rhoPi(ptr, 14, 20, 18, D0)
                        rhoPi(ptr, 20, 2, 62, D2)
                        rhoPi(ptr, 2, 12, 43, D2)
                        rhoPi(ptr, 12, 13, 25, D3)
                        rhoPi(ptr, 13, 19, 8, D4)
                        rhoPi(ptr, 19, 23, 56, D3)
                        rhoPi(ptr, 23, 15, 41, D0)
                        rhoPi(ptr, 15, 4, 27, D4)
                        rhoPi(ptr, 4, 24, 14, D4)
                        rhoPi(ptr, 24, 21, 2, D1)
                        rhoPi(ptr, 21, 8, 55, D3)
                        rhoPi(ptr, 8, 16, 45, D1)
                        rhoPi(ptr, 16, 5, 36, D0)
                        rhoPi(ptr, 5, 3, 28, D3)
                        rhoPi(ptr, 3, 18, 21, D3)
                        rhoPi(ptr, 18, 17, 15, D2)
                        rhoPi(ptr, 17, 11, 10, D1)
                        rhoPi(ptr, 11, 7, 6, D2)
                        rhoPi(ptr, 7, 10, 3, D0)
                        setStateElem(ptr, 10, A1)
                    }
                    // Inner `chi` function, unrolled in `chi` for performance.
                    function innerChi(ptr, start) {
                        let A0 := stateElem(ptr, start)
                        let A1 := stateElem(ptr, add(start, 1))
                        let A2 := stateElem(ptr, add(start, 2))
                        let A3 := stateElem(ptr, add(start, 3))
                        let A4 := stateElem(ptr, add(start, 4))
                        setStateElem(ptr, start, xor(A0, and(not(A1), A2)))
                        setStateElem(ptr, add(start, 1), xor(A1, and(not(A2), A3)))
                        setStateElem(ptr, add(start, 2), xor(A2, and(not(A3), A4)))
                        setStateElem(ptr, add(start, 3), xor(A3, and(not(A4), A0)))
                        setStateElem(ptr, add(start, 4), xor(A4, and(not(A0), A1)))
                    }
                    // Performs the `chi` step of the Keccak-f[1600] permutation on the passed `StateMatrix` struct memory ptr
                    function chi(ptr) {
                        innerChi(ptr, 0)
                        innerChi(ptr, 5)
                        innerChi(ptr, 10)
                        innerChi(ptr, 15)
                        innerChi(ptr, 20)
                    }
                    // Perform the full Keccak-f[1600] permutation on a `StateMatrix` struct memory ptr for a given round.
                    function permute(ptr, roundsPtr, round) {
                        // Theta, Rho, Pi, Chi
                        thetaRhoPi(ptr)
                        chi(ptr)
                        // Iota
                        let roundConst := shr(192, mload(add(roundsPtr, shl(0x03, round))))
                        setStateElem(ptr, 0, xor(stateElem(ptr, 0), roundConst))
                    }
                    // Unroll the permutation loop.
                    permute(stateMatrixPtr, rcPtr, 0)
                    permute(stateMatrixPtr, rcPtr, 1)
                    permute(stateMatrixPtr, rcPtr, 2)
                    permute(stateMatrixPtr, rcPtr, 3)
                    permute(stateMatrixPtr, rcPtr, 4)
                    permute(stateMatrixPtr, rcPtr, 5)
                    permute(stateMatrixPtr, rcPtr, 6)
                    permute(stateMatrixPtr, rcPtr, 7)
                    permute(stateMatrixPtr, rcPtr, 8)
                    permute(stateMatrixPtr, rcPtr, 9)
                    permute(stateMatrixPtr, rcPtr, 10)
                    permute(stateMatrixPtr, rcPtr, 11)
                    permute(stateMatrixPtr, rcPtr, 12)
                    permute(stateMatrixPtr, rcPtr, 13)
                    permute(stateMatrixPtr, rcPtr, 14)
                    permute(stateMatrixPtr, rcPtr, 15)
                    permute(stateMatrixPtr, rcPtr, 16)
                    permute(stateMatrixPtr, rcPtr, 17)
                    permute(stateMatrixPtr, rcPtr, 18)
                    permute(stateMatrixPtr, rcPtr, 19)
                    permute(stateMatrixPtr, rcPtr, 20)
                    permute(stateMatrixPtr, rcPtr, 21)
                    permute(stateMatrixPtr, rcPtr, 22)
                    permute(stateMatrixPtr, rcPtr, 23)
                }
            }
            /// @notice Absorb a fixed-sized block into the sponge.
            function absorb(StateMatrix memory _stateMatrix, bytes memory _input) internal pure {
                assembly {
                    // The input must be 1088 bits long.
                    if iszero(eq(mload(_input), 136)) { revert(0, 0) }
                    let dataPtr := add(_input, 0x20)
                    let statePtr := add(_stateMatrix, 0x20)
                    // set a state element in the passed `StateMatrix` struct memory ptr.
                    function setStateElem(ptr, idx, data) {
                        mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    // Inner sha3 absorb XOR function
                    function absorbInner(stateMatrixPtr, inputPtr, idx) {
                        let boWord := mload(add(inputPtr, shl(3, idx)))
                        let res :=
                            or(
                                or(
                                    or(shl(56, byte(7, boWord)), shl(48, byte(6, boWord))),
                                    or(shl(40, byte(5, boWord)), shl(32, byte(4, boWord)))
                                ),
                                or(
                                    or(shl(24, byte(3, boWord)), shl(16, byte(2, boWord))),
                                    or(shl(8, byte(1, boWord)), byte(0, boWord))
                                )
                            )
                        setStateElem(stateMatrixPtr, idx, xor(stateElem(stateMatrixPtr, idx), res))
                    }
                    // Unroll the input XOR loop.
                    absorbInner(statePtr, dataPtr, 0)
                    absorbInner(statePtr, dataPtr, 1)
                    absorbInner(statePtr, dataPtr, 2)
                    absorbInner(statePtr, dataPtr, 3)
                    absorbInner(statePtr, dataPtr, 4)
                    absorbInner(statePtr, dataPtr, 5)
                    absorbInner(statePtr, dataPtr, 6)
                    absorbInner(statePtr, dataPtr, 7)
                    absorbInner(statePtr, dataPtr, 8)
                    absorbInner(statePtr, dataPtr, 9)
                    absorbInner(statePtr, dataPtr, 10)
                    absorbInner(statePtr, dataPtr, 11)
                    absorbInner(statePtr, dataPtr, 12)
                    absorbInner(statePtr, dataPtr, 13)
                    absorbInner(statePtr, dataPtr, 14)
                    absorbInner(statePtr, dataPtr, 15)
                    absorbInner(statePtr, dataPtr, 16)
                }
            }
            /// @notice Squeezes the final keccak256 digest from the passed `StateMatrix`.
            function squeeze(StateMatrix memory _stateMatrix) internal pure returns (bytes32 hash_) {
                assembly {
                    // 64 bit logical shift
                    function shl64(a, b) -> val {
                        val := and(shl(a, b), U64_MASK)
                    }
                    // convert a big endian 64-bit value to a little endian 64-bit value.
                    function toLE(beVal) -> leVal {
                        beVal := or(and(shl64(8, beVal), 0xFF00FF00FF00FF00), and(shr(8, beVal), 0x00FF00FF00FF00FF))
                        beVal := or(and(shl64(16, beVal), 0xFFFF0000FFFF0000), and(shr(16, beVal), 0x0000FFFF0000FFFF))
                        leVal := or(shl64(32, beVal), shr(32, beVal))
                    }
                    // fetch a state element from the passed `StateMatrix` struct memory ptr.
                    function stateElem(ptr, idx) -> elem {
                        elem := mload(add(ptr, shl(0x05, idx)))
                    }
                    let stateMatrixPtr := add(_stateMatrix, 0x20)
                    hash_ :=
                        or(
                            or(shl(192, toLE(stateElem(stateMatrixPtr, 0))), shl(128, toLE(stateElem(stateMatrixPtr, 1)))),
                            or(shl(64, toLE(stateElem(stateMatrixPtr, 2))), toLE(stateElem(stateMatrixPtr, 3)))
                        )
                }
            }
            /// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
            function pad(bytes calldata _data) internal pure returns (bytes memory padded_) {
                assembly {
                    padded_ := mload(0x40)
                    // Grab the original length of `_data`
                    let len := _data.length
                    let dataPtr := add(padded_, 0x20)
                    let endPtr := add(dataPtr, len)
                    // Copy the data into memory.
                    calldatacopy(dataPtr, _data.offset, len)
                    let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
                    switch modBlockSize
                    case false {
                        // Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
                        // not update the free memory pointer when allocating memory, for example with external calls. To do
                        // this, we read out-of-bounds from the calldata, which will always return 0 bytes.
                        calldatacopy(endPtr, calldatasize(), 0x88)
                        // If the input is a perfect multiple of the block size, then we add a full extra block of padding.
                        mstore8(endPtr, 0x01)
                        mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
                        // Update the length of the data to include the padding.
                        mstore(padded_, add(len, BLOCK_SIZE_BYTES))
                    }
                    default {
                        // If the input is not a perfect multiple of the block size, then we add a partial block of padding.
                        // This should entail a set bit after the input, followed by as many zero bits as necessary to fill
                        // the block, followed by a single 1 bit in the lowest-order bit of the final block.
                        let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
                        let newLen := add(len, remaining)
                        let paddedEndPtr := add(dataPtr, newLen)
                        // Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
                        // possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
                        // when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
                        // calldata, which will always return 0 bytes.
                        let partialRemainder := sub(paddedEndPtr, endPtr)
                        calldatacopy(endPtr, calldatasize(), partialRemainder)
                        // Store the padding bits.
                        mstore8(sub(paddedEndPtr, 0x01), 0x80)
                        mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
                        // Update the length of the data to include the padding. The length should be a multiple of the
                        // block size after this.
                        mstore(padded_, newLen)
                    }
                    // Update the free memory pointer.
                    mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
                }
            }
            /// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
            function padMemory(bytes memory _data) internal pure returns (bytes memory padded_) {
                assembly {
                    padded_ := mload(0x40)
                    // Grab the original length of `_data`
                    let len := mload(_data)
                    let dataPtr := add(padded_, 0x20)
                    let endPtr := add(dataPtr, len)
                    // Copy the data.
                    let originalDataPtr := add(_data, 0x20)
                    for { let i := 0x00 } lt(i, len) { i := add(i, 0x20) } {
                        mstore(add(dataPtr, i), mload(add(originalDataPtr, i)))
                    }
                    let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
                    switch modBlockSize
                    case false {
                        // Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
                        // not update the free memory pointer when allocating memory, for example with external calls. To do
                        // this, we read out-of-bounds from the calldata, which will always return 0 bytes.
                        calldatacopy(endPtr, calldatasize(), 0x88)
                        // If the input is a perfect multiple of the block size, then we add a full extra block of padding.
                        mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
                        mstore8(endPtr, 0x01)
                        // Update the length of the data to include the padding.
                        mstore(padded_, add(len, BLOCK_SIZE_BYTES))
                    }
                    default {
                        // If the input is not a perfect multiple of the block size, then we add a partial block of padding.
                        // This should entail a set bit after the input, followed by as many zero bits as necessary to fill
                        // the block, followed by a single 1 bit in the lowest-order bit of the final block.
                        let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
                        let newLen := add(len, remaining)
                        let paddedEndPtr := add(dataPtr, newLen)
                        // Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
                        // possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
                        // when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
                        // calldata, which will always return 0 bytes.
                        let partialRemainder := sub(paddedEndPtr, endPtr)
                        calldatacopy(endPtr, calldatasize(), partialRemainder)
                        // Store the padding bits.
                        mstore8(sub(paddedEndPtr, 0x01), 0x80)
                        mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
                        // Update the length of the data to include the padding. The length should be a multiple of the
                        // block size after this.
                        mstore(padded_, newLen)
                    }
                    // Update the free memory pointer.
                    mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        using LPPMetadataLib for LPPMetaData global;
        /// @notice Packed LPP metadata.
        /// ┌─────────────┬────────────────────────────────────────────┐
        /// │ Bit Offsets │                Description                 │
        /// ├─────────────┼────────────────────────────────────────────┤
        /// │ [0, 64)     │ Timestamp (Finalized - All data available) │
        /// │ [64, 96)    │ Part Offset                                │
        /// │ [96, 128)   │ Claimed Size                               │
        /// │ [128, 160)  │ Blocks Processed (Inclusive of Padding)    │
        /// │ [160, 192)  │ Bytes Processed (Non-inclusive of Padding) │
        /// │ [192, 256)  │ Countered                                  │
        /// └─────────────┴────────────────────────────────────────────┘
        type LPPMetaData is bytes32;
        /// @notice LPP metadata UDT extension functions.
        library LPPMetadataLib {
            uint256 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
            uint256 private constant U32_MASK = 0xFFFFFFFF;
            function setTimestamp(LPPMetaData _self, uint64 _timestamp) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(192, _timestamp), and(_self, not(shl(192, U64_MASK))))
                }
            }
            function setPartOffset(LPPMetaData _self, uint32 _partOffset) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(160, _partOffset), and(_self, not(shl(160, U32_MASK))))
                }
            }
            function setClaimedSize(LPPMetaData _self, uint32 _claimedSize) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(128, _claimedSize), and(_self, not(shl(128, U32_MASK))))
                }
            }
            function setBlocksProcessed(LPPMetaData _self, uint32 _blocksProcessed) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(96, _blocksProcessed), and(_self, not(shl(96, U32_MASK))))
                }
            }
            function setBytesProcessed(LPPMetaData _self, uint32 _bytesProcessed) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(shl(64, _bytesProcessed), and(_self, not(shl(64, U32_MASK))))
                }
            }
            function setCountered(LPPMetaData _self, bool _countered) internal pure returns (LPPMetaData self_) {
                assembly {
                    self_ := or(_countered, and(_self, not(U64_MASK)))
                }
            }
            function timestamp(LPPMetaData _self) internal pure returns (uint64 timestamp_) {
                assembly {
                    timestamp_ := shr(192, _self)
                }
            }
            function partOffset(LPPMetaData _self) internal pure returns (uint64 partOffset_) {
                assembly {
                    partOffset_ := and(shr(160, _self), U32_MASK)
                }
            }
            function claimedSize(LPPMetaData _self) internal pure returns (uint32 claimedSize_) {
                assembly {
                    claimedSize_ := and(shr(128, _self), U32_MASK)
                }
            }
            function blocksProcessed(LPPMetaData _self) internal pure returns (uint32 blocksProcessed_) {
                assembly {
                    blocksProcessed_ := and(shr(96, _self), U32_MASK)
                }
            }
            function bytesProcessed(LPPMetaData _self) internal pure returns (uint32 bytesProcessed_) {
                assembly {
                    bytesProcessed_ := and(shr(64, _self), U32_MASK)
                }
            }
            function countered(LPPMetaData _self) internal pure returns (bool countered_) {
                assembly {
                    countered_ := and(_self, U64_MASK)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @custom:attribution https://github.com/bakaoh/solidity-rlp-encode
        /// @title RLPWriter
        /// @author RLPWriter is a library for encoding Solidity types to RLP bytes. Adapted from Bakaoh's
        ///         RLPEncode library (https://github.com/bakaoh/solidity-rlp-encode) with minor
        ///         modifications to improve legibility.
        library RLPWriter {
            /// @notice RLP encodes a byte string.
            /// @param _in The byte string to encode.
            /// @return out_ The RLP encoded string in bytes.
            function writeBytes(bytes memory _in) internal pure returns (bytes memory out_) {
                if (_in.length == 1 && uint8(_in[0]) < 128) {
                    out_ = _in;
                } else {
                    out_ = abi.encodePacked(_writeLength(_in.length, 128), _in);
                }
            }
            /// @notice RLP encodes a list of RLP encoded byte byte strings.
            /// @param _in The list of RLP encoded byte strings.
            /// @return list_ The RLP encoded list of items in bytes.
            function writeList(bytes[] memory _in) internal pure returns (bytes memory list_) {
                list_ = _flatten(_in);
                list_ = abi.encodePacked(_writeLength(list_.length, 192), list_);
            }
            /// @notice RLP encodes a string.
            /// @param _in The string to encode.
            /// @return out_ The RLP encoded string in bytes.
            function writeString(string memory _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(bytes(_in));
            }
            /// @notice RLP encodes an address.
            /// @param _in The address to encode.
            /// @return out_ The RLP encoded address in bytes.
            function writeAddress(address _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(abi.encodePacked(_in));
            }
            /// @notice RLP encodes a uint.
            /// @param _in The uint256 to encode.
            /// @return out_ The RLP encoded uint256 in bytes.
            function writeUint(uint256 _in) internal pure returns (bytes memory out_) {
                out_ = writeBytes(_toBinary(_in));
            }
            /// @notice RLP encodes a bool.
            /// @param _in The bool to encode.
            /// @return out_ The RLP encoded bool in bytes.
            function writeBool(bool _in) internal pure returns (bytes memory out_) {
                out_ = new bytes(1);
                out_[0] = (_in ? bytes1(0x01) : bytes1(0x80));
            }
            /// @notice Encode the first byte and then the `len` in binary form if `length` is more than 55.
            /// @param _len    The length of the string or the payload.
            /// @param _offset 128 if item is string, 192 if item is list.
            /// @return out_ RLP encoded bytes.
            function _writeLength(uint256 _len, uint256 _offset) private pure returns (bytes memory out_) {
                if (_len < 56) {
                    out_ = new bytes(1);
                    out_[0] = bytes1(uint8(_len) + uint8(_offset));
                } else {
                    uint256 lenLen;
                    uint256 i = 1;
                    while (_len / i != 0) {
                        lenLen++;
                        i *= 256;
                    }
                    out_ = new bytes(lenLen + 1);
                    out_[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
                    for (i = 1; i <= lenLen; i++) {
                        out_[i] = bytes1(uint8((_len / (256 ** (lenLen - i))) % 256));
                    }
                }
            }
            /// @notice Encode integer in big endian binary form with no leading zeroes.
            /// @param _x The integer to encode.
            /// @return out_ RLP encoded bytes.
            function _toBinary(uint256 _x) private pure returns (bytes memory out_) {
                bytes memory b = abi.encodePacked(_x);
                uint256 i = 0;
                for (; i < 32; i++) {
                    if (b[i] != 0) {
                        break;
                    }
                }
                out_ = new bytes(32 - i);
                for (uint256 j = 0; j < out_.length; j++) {
                    out_[j] = b[i++];
                }
            }
            /// @custom:attribution https://github.com/Arachnid/solidity-stringutils
            /// @notice Copies a piece of memory to another location.
            /// @param _dest Destination location.
            /// @param _src  Source location.
            /// @param _len  Length of memory to copy.
            function _memcpy(uint256 _dest, uint256 _src, uint256 _len) private pure {
                uint256 dest = _dest;
                uint256 src = _src;
                uint256 len = _len;
                for (; len >= 32; len -= 32) {
                    assembly {
                        mstore(dest, mload(src))
                    }
                    dest += 32;
                    src += 32;
                }
                uint256 mask;
                unchecked {
                    mask = 256 ** (32 - len) - 1;
                }
                assembly {
                    let srcpart := and(mload(src), not(mask))
                    let destpart := and(mload(dest), mask)
                    mstore(dest, or(destpart, srcpart))
                }
            }
            /// @custom:attribution https://github.com/sammayo/solidity-rlp-encoder
            /// @notice Flattens a list of byte strings into one byte string.
            /// @param _list List of byte strings to flatten.
            /// @return out_ The flattened byte string.
            function _flatten(bytes[] memory _list) private pure returns (bytes memory out_) {
                if (_list.length == 0) {
                    return new bytes(0);
                }
                uint256 len;
                uint256 i = 0;
                for (; i < _list.length; i++) {
                    len += _list[i].length;
                }
                out_ = new bytes(len);
                uint256 flattenedPtr;
                assembly {
                    flattenedPtr := add(out_, 0x20)
                }
                for (i = 0; i < _list.length; i++) {
                    bytes memory item = _list[i];
                    uint256 listPtr;
                    assembly {
                        listPtr := add(item, 0x20)
                    }
                    _memcpy(flattenedPtr, listPtr, item.length);
                    flattenedPtr += _list[i].length;
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        interface IInitializable {
            function initialize() external payable;
        }
        

        File 3 of 4: Proxy
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        import { Constants } from "../libraries/Constants.sol";
        /// @title Proxy
        /// @notice Proxy is a transparent proxy that passes through the call if the caller is the owner or
        ///         if the caller is address(0), meaning that the call originated from an off-chain
        ///         simulation.
        contract Proxy {
            /// @notice An event that is emitted each time the implementation is changed. This event is part
            ///         of the EIP-1967 specification.
            /// @param implementation The address of the implementation contract
            event Upgraded(address indexed implementation);
            /// @notice An event that is emitted each time the owner is upgraded. This event is part of the
            ///         EIP-1967 specification.
            /// @param previousAdmin The previous owner of the contract
            /// @param newAdmin      The new owner of the contract
            event AdminChanged(address previousAdmin, address newAdmin);
            /// @notice A modifier that reverts if not called by the owner or by address(0) to allow
            ///         eth_call to interact with this proxy without needing to use low-level storage
            ///         inspection. We assume that nobody is able to trigger calls from address(0) during
            ///         normal EVM execution.
            modifier proxyCallIfNotAdmin() {
                if (msg.sender == _getAdmin() || msg.sender == address(0)) {
                    _;
                } else {
                    // This WILL halt the call frame on completion.
                    _doProxyCall();
                }
            }
            /// @notice Sets the initial admin during contract deployment. Admin address is stored at the
            ///         EIP-1967 admin storage slot so that accidental storage collision with the
            ///         implementation is not possible.
            /// @param _admin Address of the initial contract admin. Admin as the ability to access the
            ///               transparent proxy interface.
            constructor(address _admin) {
                _changeAdmin(_admin);
            }
            // slither-disable-next-line locked-ether
            receive() external payable {
                // Proxy call by default.
                _doProxyCall();
            }
            // slither-disable-next-line locked-ether
            fallback() external payable {
                // Proxy call by default.
                _doProxyCall();
            }
            /// @notice Set the implementation contract address. The code at the given address will execute
            ///         when this contract is called.
            /// @param _implementation Address of the implementation contract.
            function upgradeTo(address _implementation) public virtual proxyCallIfNotAdmin {
                _setImplementation(_implementation);
            }
            /// @notice Set the implementation and call a function in a single transaction. Useful to ensure
            ///         atomic execution of initialization-based upgrades.
            /// @param _implementation Address of the implementation contract.
            /// @param _data           Calldata to delegatecall the new implementation with.
            function upgradeToAndCall(
                address _implementation,
                bytes calldata _data
            )
                public
                payable
                virtual
                proxyCallIfNotAdmin
                returns (bytes memory)
            {
                _setImplementation(_implementation);
                (bool success, bytes memory returndata) = _implementation.delegatecall(_data);
                require(success, "Proxy: delegatecall to new implementation contract failed");
                return returndata;
            }
            /// @notice Changes the owner of the proxy contract. Only callable by the owner.
            /// @param _admin New owner of the proxy contract.
            function changeAdmin(address _admin) public virtual proxyCallIfNotAdmin {
                _changeAdmin(_admin);
            }
            /// @notice Gets the owner of the proxy contract.
            /// @return Owner address.
            function admin() public virtual proxyCallIfNotAdmin returns (address) {
                return _getAdmin();
            }
            //// @notice Queries the implementation address.
            /// @return Implementation address.
            function implementation() public virtual proxyCallIfNotAdmin returns (address) {
                return _getImplementation();
            }
            /// @notice Sets the implementation address.
            /// @param _implementation New implementation address.
            function _setImplementation(address _implementation) internal {
                bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS;
                assembly {
                    sstore(proxyImplementation, _implementation)
                }
                emit Upgraded(_implementation);
            }
            /// @notice Changes the owner of the proxy contract.
            /// @param _admin New owner of the proxy contract.
            function _changeAdmin(address _admin) internal {
                address previous = _getAdmin();
                bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS;
                assembly {
                    sstore(proxyOwner, _admin)
                }
                emit AdminChanged(previous, _admin);
            }
            /// @notice Performs the proxy call via a delegatecall.
            function _doProxyCall() internal {
                address impl = _getImplementation();
                require(impl != address(0), "Proxy: implementation not initialized");
                assembly {
                    // Copy calldata into memory at 0x0....calldatasize.
                    calldatacopy(0x0, 0x0, calldatasize())
                    // Perform the delegatecall, make sure to pass all available gas.
                    let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0)
                    // Copy returndata into memory at 0x0....returndatasize. Note that this *will*
                    // overwrite the calldata that we just copied into memory but that doesn't really
                    // matter because we'll be returning in a second anyway.
                    returndatacopy(0x0, 0x0, returndatasize())
                    // Success == 0 means a revert. We'll revert too and pass the data up.
                    if iszero(success) { revert(0x0, returndatasize()) }
                    // Otherwise we'll just return and pass the data up.
                    return(0x0, returndatasize())
                }
            }
            /// @notice Queries the implementation address.
            /// @return Implementation address.
            function _getImplementation() internal view returns (address) {
                address impl;
                bytes32 proxyImplementation = Constants.PROXY_IMPLEMENTATION_ADDRESS;
                assembly {
                    impl := sload(proxyImplementation)
                }
                return impl;
            }
            /// @notice Queries the owner of the proxy contract.
            /// @return Owner address.
            function _getAdmin() internal view returns (address) {
                address owner;
                bytes32 proxyOwner = Constants.PROXY_OWNER_ADDRESS;
                assembly {
                    owner := sload(proxyOwner)
                }
                return owner;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { ResourceMetering } from "../L1/ResourceMetering.sol";
        /// @title Constants
        /// @notice Constants is a library for storing constants. Simple! Don't put everything in here, just
        ///         the stuff used in multiple contracts. Constants that only apply to a single contract
        ///         should be defined in that contract instead.
        library Constants {
            /// @notice Special address to be used as the tx origin for gas estimation calls in the
            ///         OptimismPortal and CrossDomainMessenger calls. You only need to use this address if
            ///         the minimum gas limit specified by the user is not actually enough to execute the
            ///         given message and you're attempting to estimate the actual necessary gas limit. We
            ///         use address(1) because it's the ecrecover precompile and therefore guaranteed to
            ///         never have any code on any EVM chain.
            address internal constant ESTIMATION_ADDRESS = address(1);
            /// @notice Value used for the L2 sender storage slot in both the OptimismPortal and the
            ///         CrossDomainMessenger contracts before an actual sender is set. This value is
            ///         non-zero to reduce the gas cost of message passing transactions.
            address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD;
            /// @notice The storage slot that holds the address of a proxy implementation.
            /// @dev `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`
            bytes32 internal constant PROXY_IMPLEMENTATION_ADDRESS =
                0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
            /// @notice The storage slot that holds the address of the owner.
            /// @dev `bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)`
            bytes32 internal constant PROXY_OWNER_ADDRESS = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
            /// @notice Returns the default values for the ResourceConfig. These are the recommended values
            ///         for a production network.
            function DEFAULT_RESOURCE_CONFIG() internal pure returns (ResourceMetering.ResourceConfig memory) {
                ResourceMetering.ResourceConfig memory config = ResourceMetering.ResourceConfig({
                    maxResourceLimit: 20_000_000,
                    elasticityMultiplier: 10,
                    baseFeeMaxChangeDenominator: 8,
                    minimumBaseFee: 1 gwei,
                    systemTxMaxGas: 1_000_000,
                    maximumBaseFee: type(uint128).max
                });
                return config;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
        import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
        import { Burn } from "../libraries/Burn.sol";
        import { Arithmetic } from "../libraries/Arithmetic.sol";
        /// @custom:upgradeable
        /// @title ResourceMetering
        /// @notice ResourceMetering implements an EIP-1559 style resource metering system where pricing
        ///         updates automatically based on current demand.
        abstract contract ResourceMetering is Initializable {
            /// @notice Represents the various parameters that control the way in which resources are
            ///         metered. Corresponds to the EIP-1559 resource metering system.
            /// @custom:field prevBaseFee   Base fee from the previous block(s).
            /// @custom:field prevBoughtGas Amount of gas bought so far in the current block.
            /// @custom:field prevBlockNum  Last block number that the base fee was updated.
            struct ResourceParams {
                uint128 prevBaseFee;
                uint64 prevBoughtGas;
                uint64 prevBlockNum;
            }
            /// @notice Represents the configuration for the EIP-1559 based curve for the deposit gas
            ///         market. These values should be set with care as it is possible to set them in
            ///         a way that breaks the deposit gas market. The target resource limit is defined as
            ///         maxResourceLimit / elasticityMultiplier. This struct was designed to fit within a
            ///         single word. There is additional space for additions in the future.
            /// @custom:field maxResourceLimit             Represents the maximum amount of deposit gas that
            ///                                            can be purchased per block.
            /// @custom:field elasticityMultiplier         Determines the target resource limit along with
            ///                                            the resource limit.
            /// @custom:field baseFeeMaxChangeDenominator  Determines max change on fee per block.
            /// @custom:field minimumBaseFee               The min deposit base fee, it is clamped to this
            ///                                            value.
            /// @custom:field systemTxMaxGas               The amount of gas supplied to the system
            ///                                            transaction. This should be set to the same
            ///                                            number that the op-node sets as the gas limit
            ///                                            for the system transaction.
            /// @custom:field maximumBaseFee               The max deposit base fee, it is clamped to this
            ///                                            value.
            struct ResourceConfig {
                uint32 maxResourceLimit;
                uint8 elasticityMultiplier;
                uint8 baseFeeMaxChangeDenominator;
                uint32 minimumBaseFee;
                uint32 systemTxMaxGas;
                uint128 maximumBaseFee;
            }
            /// @notice EIP-1559 style gas parameters.
            ResourceParams public params;
            /// @notice Reserve extra slots (to a total of 50) in the storage layout for future upgrades.
            uint256[48] private __gap;
            /// @notice Meters access to a function based an amount of a requested resource.
            /// @param _amount Amount of the resource requested.
            modifier metered(uint64 _amount) {
                // Record initial gas amount so we can refund for it later.
                uint256 initialGas = gasleft();
                // Run the underlying function.
                _;
                // Run the metering function.
                _metered(_amount, initialGas);
            }
            /// @notice An internal function that holds all of the logic for metering a resource.
            /// @param _amount     Amount of the resource requested.
            /// @param _initialGas The amount of gas before any modifier execution.
            function _metered(uint64 _amount, uint256 _initialGas) internal {
                // Update block number and base fee if necessary.
                uint256 blockDiff = block.number - params.prevBlockNum;
                ResourceConfig memory config = _resourceConfig();
                int256 targetResourceLimit =
                    int256(uint256(config.maxResourceLimit)) / int256(uint256(config.elasticityMultiplier));
                if (blockDiff > 0) {
                    // Handle updating EIP-1559 style gas parameters. We use EIP-1559 to restrict the rate
                    // at which deposits can be created and therefore limit the potential for deposits to
                    // spam the L2 system. Fee scheme is very similar to EIP-1559 with minor changes.
                    int256 gasUsedDelta = int256(uint256(params.prevBoughtGas)) - targetResourceLimit;
                    int256 baseFeeDelta = (int256(uint256(params.prevBaseFee)) * gasUsedDelta)
                        / (targetResourceLimit * int256(uint256(config.baseFeeMaxChangeDenominator)));
                    // Update base fee by adding the base fee delta and clamp the resulting value between
                    // min and max.
                    int256 newBaseFee = Arithmetic.clamp({
                        _value: int256(uint256(params.prevBaseFee)) + baseFeeDelta,
                        _min: int256(uint256(config.minimumBaseFee)),
                        _max: int256(uint256(config.maximumBaseFee))
                    });
                    // If we skipped more than one block, we also need to account for every empty block.
                    // Empty block means there was no demand for deposits in that block, so we should
                    // reflect this lack of demand in the fee.
                    if (blockDiff > 1) {
                        // Update the base fee by repeatedly applying the exponent 1-(1/change_denominator)
                        // blockDiff - 1 times. Simulates multiple empty blocks. Clamp the resulting value
                        // between min and max.
                        newBaseFee = Arithmetic.clamp({
                            _value: Arithmetic.cdexp({
                                _coefficient: newBaseFee,
                                _denominator: int256(uint256(config.baseFeeMaxChangeDenominator)),
                                _exponent: int256(blockDiff - 1)
                            }),
                            _min: int256(uint256(config.minimumBaseFee)),
                            _max: int256(uint256(config.maximumBaseFee))
                        });
                    }
                    // Update new base fee, reset bought gas, and update block number.
                    params.prevBaseFee = uint128(uint256(newBaseFee));
                    params.prevBoughtGas = 0;
                    params.prevBlockNum = uint64(block.number);
                }
                // Make sure we can actually buy the resource amount requested by the user.
                params.prevBoughtGas += _amount;
                require(
                    int256(uint256(params.prevBoughtGas)) <= int256(uint256(config.maxResourceLimit)),
                    "ResourceMetering: cannot buy more gas than available gas limit"
                );
                // Determine the amount of ETH to be paid.
                uint256 resourceCost = uint256(_amount) * uint256(params.prevBaseFee);
                // We currently charge for this ETH amount as an L1 gas burn, so we convert the ETH amount
                // into gas by dividing by the L1 base fee. We assume a minimum base fee of 1 gwei to avoid
                // division by zero for L1s that don't support 1559 or to avoid excessive gas burns during
                // periods of extremely low L1 demand. One-day average gas fee hasn't dipped below 1 gwei
                // during any 1 day period in the last 5 years, so should be fine.
                uint256 gasCost = resourceCost / Math.max(block.basefee, 1 gwei);
                // Give the user a refund based on the amount of gas they used to do all of the work up to
                // this point. Since we're at the end of the modifier, this should be pretty accurate. Acts
                // effectively like a dynamic stipend (with a minimum value).
                uint256 usedGas = _initialGas - gasleft();
                if (gasCost > usedGas) {
                    Burn.gas(gasCost - usedGas);
                }
            }
            /// @notice Virtual function that returns the resource config.
            ///         Contracts that inherit this contract must implement this function.
            /// @return ResourceConfig
            function _resourceConfig() internal virtual returns (ResourceConfig memory);
            /// @notice Sets initial resource parameter values.
            ///         This function must either be called by the initializer function of an upgradeable
            ///         child contract.
            // solhint-disable-next-line func-name-mixedcase
            function __ResourceMetering_init() internal onlyInitializing {
                params = ResourceParams({ prevBaseFee: 1 gwei, prevBoughtGas: 0, prevBlockNum: uint64(block.number) });
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/Address.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
             * initialization step. This is essential to configure modules that are added through upgrades and that require
             * initialization.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized < type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Standard math utilities missing in the Solidity language.
         */
        library Math {
            enum Rounding {
                Down, // Toward negative infinity
                Up, // Toward infinity
                Zero // Toward zero
            }
            /**
             * @dev Returns the largest of two numbers.
             */
            function max(uint256 a, uint256 b) internal pure returns (uint256) {
                return a >= b ? a : b;
            }
            /**
             * @dev Returns the smallest of two numbers.
             */
            function min(uint256 a, uint256 b) internal pure returns (uint256) {
                return a < b ? a : b;
            }
            /**
             * @dev Returns the average of two numbers. The result is rounded towards
             * zero.
             */
            function average(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b) / 2 can overflow.
                return (a & b) + (a ^ b) / 2;
            }
            /**
             * @dev Returns the ceiling of the division of two numbers.
             *
             * This differs from standard division with `/` in that it rounds up instead
             * of rounding down.
             */
            function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                // (a + b - 1) / b can overflow on addition, so we distribute.
                return a == 0 ? 0 : (a - 1) / b + 1;
            }
            /**
             * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
             * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
             * with further edits by Uniswap Labs also under MIT license.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator
            ) internal pure returns (uint256 result) {
                unchecked {
                    // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                    // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                    // variables such that product = prod1 * 2^256 + prod0.
                    uint256 prod0; // Least significant 256 bits of the product
                    uint256 prod1; // Most significant 256 bits of the product
                    assembly {
                        let mm := mulmod(x, y, not(0))
                        prod0 := mul(x, y)
                        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                    }
                    // Handle non-overflow cases, 256 by 256 division.
                    if (prod1 == 0) {
                        return prod0 / denominator;
                    }
                    // Make sure the result is less than 2^256. Also prevents denominator == 0.
                    require(denominator > prod1);
                    ///////////////////////////////////////////////
                    // 512 by 256 division.
                    ///////////////////////////////////////////////
                    // Make division exact by subtracting the remainder from [prod1 prod0].
                    uint256 remainder;
                    assembly {
                        // Compute remainder using mulmod.
                        remainder := mulmod(x, y, denominator)
                        // Subtract 256 bit number from 512 bit number.
                        prod1 := sub(prod1, gt(remainder, prod0))
                        prod0 := sub(prod0, remainder)
                    }
                    // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                    // See https://cs.stackexchange.com/q/138556/92363.
                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                    uint256 twos = denominator & (~denominator + 1);
                    assembly {
                        // Divide denominator by twos.
                        denominator := div(denominator, twos)
                        // Divide [prod1 prod0] by twos.
                        prod0 := div(prod0, twos)
                        // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                        twos := add(div(sub(0, twos), twos), 1)
                    }
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * twos;
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                    // in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                    return result;
                }
            }
            /**
             * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
             */
            function mulDiv(
                uint256 x,
                uint256 y,
                uint256 denominator,
                Rounding rounding
            ) internal pure returns (uint256) {
                uint256 result = mulDiv(x, y, denominator);
                if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                    result += 1;
                }
                return result;
            }
            /**
             * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
             *
             * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
             */
            function sqrt(uint256 a) internal pure returns (uint256) {
                if (a == 0) {
                    return 0;
                }
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                // `msb(a) <= a < 2*msb(a)`.
                // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
                // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
                // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
                // good first aproximation of `sqrt(a)` with at least 1 correct bit.
                uint256 result = 1;
                uint256 x = a;
                if (x >> 128 > 0) {
                    x >>= 128;
                    result <<= 64;
                }
                if (x >> 64 > 0) {
                    x >>= 64;
                    result <<= 32;
                }
                if (x >> 32 > 0) {
                    x >>= 32;
                    result <<= 16;
                }
                if (x >> 16 > 0) {
                    x >>= 16;
                    result <<= 8;
                }
                if (x >> 8 > 0) {
                    x >>= 8;
                    result <<= 4;
                }
                if (x >> 4 > 0) {
                    x >>= 4;
                    result <<= 2;
                }
                if (x >> 2 > 0) {
                    result <<= 1;
                }
                // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                // into the expected uint128 result.
                unchecked {
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    result = (result + a / result) >> 1;
                    return min(result, a / result);
                }
            }
            /**
             * @notice Calculates sqrt(a), following the selected rounding direction.
             */
            function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                uint256 result = sqrt(a);
                if (rounding == Rounding.Up && result * result < a) {
                    result += 1;
                }
                return result;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        /// @title Burn
        /// @notice Utilities for burning stuff.
        library Burn {
            /// @notice Burns a given amount of ETH.
            /// @param _amount Amount of ETH to burn.
            function eth(uint256 _amount) internal {
                new Burner{ value: _amount }();
            }
            /// @notice Burns a given amount of gas.
            /// @param _amount Amount of gas to burn.
            function gas(uint256 _amount) internal view {
                uint256 i = 0;
                uint256 initialGas = gasleft();
                while (initialGas - gasleft() < _amount) {
                    ++i;
                }
            }
        }
        /// @title Burner
        /// @notice Burner self-destructs on creation and sends all ETH to itself, removing all ETH given to
        ///         the contract from the circulating supply. Self-destructing is the only way to remove ETH
        ///         from the circulating supply.
        contract Burner {
            constructor() payable {
                selfdestruct(payable(address(this)));
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
        import { FixedPointMathLib } from "@rari-capital/solmate/src/utils/FixedPointMathLib.sol";
        /// @title Arithmetic
        /// @notice Even more math than before.
        library Arithmetic {
            /// @notice Clamps a value between a minimum and maximum.
            /// @param _value The value to clamp.
            /// @param _min   The minimum value.
            /// @param _max   The maximum value.
            /// @return The clamped value.
            function clamp(int256 _value, int256 _min, int256 _max) internal pure returns (int256) {
                return SignedMath.min(SignedMath.max(_value, _min), _max);
            }
            /// @notice (c)oefficient (d)enominator (exp)onentiation function.
            ///         Returns the result of: c * (1 - 1/d)^exp.
            /// @param _coefficient Coefficient of the function.
            /// @param _denominator Fractional denominator.
            /// @param _exponent    Power function exponent.
            /// @return Result of c * (1 - 1/d)^exp.
            function cdexp(int256 _coefficient, int256 _denominator, int256 _exponent) internal pure returns (int256) {
                return (_coefficient * (FixedPointMathLib.powWad(1e18 - (1e18 / _denominator), _exponent * 1e18))) / 1e18;
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCall(target, data, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                require(isContract(target), "Address: call to non-contract");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                require(isContract(target), "Address: static call to non-contract");
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(isContract(target), "Address: delegate call to non-contract");
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.5.0) (utils/math/SignedMath.sol)
        pragma solidity ^0.8.0;
        /**
         * @dev Standard signed math utilities missing in the Solidity language.
         */
        library SignedMath {
            /**
             * @dev Returns the largest of two signed numbers.
             */
            function max(int256 a, int256 b) internal pure returns (int256) {
                return a >= b ? a : b;
            }
            /**
             * @dev Returns the smallest of two signed numbers.
             */
            function min(int256 a, int256 b) internal pure returns (int256) {
                return a < b ? a : b;
            }
            /**
             * @dev Returns the average of two signed numbers without overflow.
             * The result is rounded towards zero.
             */
            function average(int256 a, int256 b) internal pure returns (int256) {
                // Formula from the book "Hacker's Delight"
                int256 x = (a & b) + ((a ^ b) >> 1);
                return x + (int256(uint256(x) >> 255) & (a ^ b));
            }
            /**
             * @dev Returns the absolute unsigned value of a signed value.
             */
            function abs(int256 n) internal pure returns (uint256) {
                unchecked {
                    // must be unchecked in order to support `n = type(int256).min`
                    return uint256(n >= 0 ? n : -n);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.8.0;
        /// @notice Arithmetic library with operations for fixed-point numbers.
        /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
        library FixedPointMathLib {
            /*//////////////////////////////////////////////////////////////
                            SIMPLIFIED FIXED POINT OPERATIONS
            //////////////////////////////////////////////////////////////*/
            uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
            function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
                return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
            }
            function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
                return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
            }
            function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
                return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
            }
            function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
                return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
            }
            function powWad(int256 x, int256 y) internal pure returns (int256) {
                // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)
                return expWad((lnWad(x) * y) / int256(WAD)); // Using ln(x) means x must be greater than 0.
            }
            function expWad(int256 x) internal pure returns (int256 r) {
                unchecked {
                    // When the result is < 0.5 we return zero. This happens when
                    // x <= floor(log(0.5e18) * 1e18) ~ -42e18
                    if (x <= -42139678854452767551) return 0;
                    // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
                    // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
                    if (x >= 135305999368893231589) revert("EXP_OVERFLOW");
                    // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
                    // for more intermediate precision and a binary basis. This base conversion
                    // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
                    x = (x << 78) / 5**18;
                    // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
                    // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
                    // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
                    int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;
                    x = x - k * 54916777467707473351141471128;
                    // k is in the range [-61, 195].
                    // Evaluate using a (6, 7)-term rational approximation.
                    // p is made monic, we'll multiply by a scale factor later.
                    int256 y = x + 1346386616545796478920950773328;
                    y = ((y * x) >> 96) + 57155421227552351082224309758442;
                    int256 p = y + x - 94201549194550492254356042504812;
                    p = ((p * y) >> 96) + 28719021644029726153956944680412240;
                    p = p * x + (4385272521454847904659076985693276 << 96);
                    // We leave p in 2**192 basis so we don't need to scale it back up for the division.
                    int256 q = x - 2855989394907223263936484059900;
                    q = ((q * x) >> 96) + 50020603652535783019961831881945;
                    q = ((q * x) >> 96) - 533845033583426703283633433725380;
                    q = ((q * x) >> 96) + 3604857256930695427073651918091429;
                    q = ((q * x) >> 96) - 14423608567350463180887372962807573;
                    q = ((q * x) >> 96) + 26449188498355588339934803723976023;
                    assembly {
                        // Div in assembly because solidity adds a zero check despite the unchecked.
                        // The q polynomial won't have zeros in the domain as all its roots are complex.
                        // No scaling is necessary because p is already 2**96 too large.
                        r := sdiv(p, q)
                    }
                    // r should be in the range (0.09, 0.25) * 2**96.
                    // We now need to multiply r by:
                    // * the scale factor s = ~6.031367120.
                    // * the 2**k factor from the range reduction.
                    // * the 1e18 / 2**96 factor for base conversion.
                    // We do this all at once, with an intermediate result in 2**213
                    // basis, so the final right shift is always by a positive amount.
                    r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
                }
            }
            function lnWad(int256 x) internal pure returns (int256 r) {
                unchecked {
                    require(x > 0, "UNDEFINED");
                    // We want to convert x from 10**18 fixed point to 2**96 fixed point.
                    // We do this by multiplying by 2**96 / 10**18. But since
                    // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
                    // and add ln(2**96 / 10**18) at the end.
                    // Reduce range of x to (1, 2) * 2**96
                    // ln(2^k * x) = k * ln(2) + ln(x)
                    int256 k = int256(log2(uint256(x))) - 96;
                    x <<= uint256(159 - k);
                    x = int256(uint256(x) >> 159);
                    // Evaluate using a (8, 8)-term rational approximation.
                    // p is made monic, we will multiply by a scale factor later.
                    int256 p = x + 3273285459638523848632254066296;
                    p = ((p * x) >> 96) + 24828157081833163892658089445524;
                    p = ((p * x) >> 96) + 43456485725739037958740375743393;
                    p = ((p * x) >> 96) - 11111509109440967052023855526967;
                    p = ((p * x) >> 96) - 45023709667254063763336534515857;
                    p = ((p * x) >> 96) - 14706773417378608786704636184526;
                    p = p * x - (795164235651350426258249787498 << 96);
                    // We leave p in 2**192 basis so we don't need to scale it back up for the division.
                    // q is monic by convention.
                    int256 q = x + 5573035233440673466300451813936;
                    q = ((q * x) >> 96) + 71694874799317883764090561454958;
                    q = ((q * x) >> 96) + 283447036172924575727196451306956;
                    q = ((q * x) >> 96) + 401686690394027663651624208769553;
                    q = ((q * x) >> 96) + 204048457590392012362485061816622;
                    q = ((q * x) >> 96) + 31853899698501571402653359427138;
                    q = ((q * x) >> 96) + 909429971244387300277376558375;
                    assembly {
                        // Div in assembly because solidity adds a zero check despite the unchecked.
                        // The q polynomial is known not to have zeros in the domain.
                        // No scaling required because p is already 2**96 too large.
                        r := sdiv(p, q)
                    }
                    // r is in the range (0, 0.125) * 2**96
                    // Finalization, we need to:
                    // * multiply by the scale factor s = 5.549…
                    // * add ln(2**96 / 10**18)
                    // * add k * ln(2)
                    // * multiply by 10**18 / 2**96 = 5**18 >> 78
                    // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
                    r *= 1677202110996718588342820967067443963516166;
                    // add ln(2) * k * 5e18 * 2**192
                    r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
                    // add ln(2**96 / 10**18) * 5e18 * 2**192
                    r += 600920179829731861736702779321621459595472258049074101567377883020018308;
                    // base conversion: mul 2**18 / 2**192
                    r >>= 174;
                }
            }
            /*//////////////////////////////////////////////////////////////
                            LOW LEVEL FIXED POINT OPERATIONS
            //////////////////////////////////////////////////////////////*/
            function mulDivDown(
                uint256 x,
                uint256 y,
                uint256 denominator
            ) internal pure returns (uint256 z) {
                assembly {
                    // Store x * y in z for now.
                    z := mul(x, y)
                    // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
                    if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                        revert(0, 0)
                    }
                    // Divide z by the denominator.
                    z := div(z, denominator)
                }
            }
            function mulDivUp(
                uint256 x,
                uint256 y,
                uint256 denominator
            ) internal pure returns (uint256 z) {
                assembly {
                    // Store x * y in z for now.
                    z := mul(x, y)
                    // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
                    if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                        revert(0, 0)
                    }
                    // First, divide z - 1 by the denominator and add 1.
                    // We allow z - 1 to underflow if z is 0, because we multiply the
                    // end result by 0 if z is zero, ensuring we return 0 if z is zero.
                    z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
                }
            }
            function rpow(
                uint256 x,
                uint256 n,
                uint256 scalar
            ) internal pure returns (uint256 z) {
                assembly {
                    switch x
                    case 0 {
                        switch n
                        case 0 {
                            // 0 ** 0 = 1
                            z := scalar
                        }
                        default {
                            // 0 ** n = 0
                            z := 0
                        }
                    }
                    default {
                        switch mod(n, 2)
                        case 0 {
                            // If n is even, store scalar in z for now.
                            z := scalar
                        }
                        default {
                            // If n is odd, store x in z for now.
                            z := x
                        }
                        // Shifting right by 1 is like dividing by 2.
                        let half := shr(1, scalar)
                        for {
                            // Shift n right by 1 before looping to halve it.
                            n := shr(1, n)
                        } n {
                            // Shift n right by 1 each iteration to halve it.
                            n := shr(1, n)
                        } {
                            // Revert immediately if x ** 2 would overflow.
                            // Equivalent to iszero(eq(div(xx, x), x)) here.
                            if shr(128, x) {
                                revert(0, 0)
                            }
                            // Store x squared.
                            let xx := mul(x, x)
                            // Round to the nearest number.
                            let xxRound := add(xx, half)
                            // Revert if xx + half overflowed.
                            if lt(xxRound, xx) {
                                revert(0, 0)
                            }
                            // Set x to scaled xxRound.
                            x := div(xxRound, scalar)
                            // If n is even:
                            if mod(n, 2) {
                                // Compute z * x.
                                let zx := mul(z, x)
                                // If z * x overflowed:
                                if iszero(eq(div(zx, x), z)) {
                                    // Revert if x is non-zero.
                                    if iszero(iszero(x)) {
                                        revert(0, 0)
                                    }
                                }
                                // Round to the nearest number.
                                let zxRound := add(zx, half)
                                // Revert if zx + half overflowed.
                                if lt(zxRound, zx) {
                                    revert(0, 0)
                                }
                                // Return properly scaled zxRound.
                                z := div(zxRound, scalar)
                            }
                        }
                    }
                }
            }
            /*//////////////////////////////////////////////////////////////
                                GENERAL NUMBER UTILITIES
            //////////////////////////////////////////////////////////////*/
            function sqrt(uint256 x) internal pure returns (uint256 z) {
                assembly {
                    let y := x // We start y at x, which will help us make our initial estimate.
                    z := 181 // The "correct" value is 1, but this saves a multiplication later.
                    // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                    // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                    // We check y >= 2^(k + 8) but shift right by k bits
                    // each branch to ensure that if x >= 256, then y >= 256.
                    if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                        y := shr(128, y)
                        z := shl(64, z)
                    }
                    if iszero(lt(y, 0x1000000000000000000)) {
                        y := shr(64, y)
                        z := shl(32, z)
                    }
                    if iszero(lt(y, 0x10000000000)) {
                        y := shr(32, y)
                        z := shl(16, z)
                    }
                    if iszero(lt(y, 0x1000000)) {
                        y := shr(16, y)
                        z := shl(8, z)
                    }
                    // Goal was to get z*z*y within a small factor of x. More iterations could
                    // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
                    // We ensured y >= 256 so that the relative difference between y and y+1 is small.
                    // That's not possible if x < 256 but we can just verify those cases exhaustively.
                    // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
                    // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
                    // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
                    // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
                    // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
                    // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
                    // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
                    // There is no overflow risk here since y < 2^136 after the first branch above.
                    z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
                    // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    z := shr(1, add(z, div(x, z)))
                    // If x+1 is a perfect square, the Babylonian method cycles between
                    // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
                    // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                    // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
                    // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
                    z := sub(z, lt(div(x, z), z))
                }
            }
            function log2(uint256 x) internal pure returns (uint256 r) {
                require(x > 0, "UNDEFINED");
                assembly {
                    r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
                    r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
                    r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
                    r := or(r, shl(4, lt(0xffff, shr(r, x))))
                    r := or(r, shl(3, lt(0xff, shr(r, x))))
                    r := or(r, shl(2, lt(0xf, shr(r, x))))
                    r := or(r, shl(1, lt(0x3, shr(r, x))))
                    r := or(r, lt(0x1, shr(r, x)))
                }
            }
        }
        

        File 4 of 4: DelayedWETH
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
        import { ISemver } from "src/universal/ISemver.sol";
        import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
        import { IWETH } from "src/dispute/interfaces/IWETH.sol";
        import { WETH98 } from "src/dispute/weth/WETH98.sol";
        import { SuperchainConfig } from "src/L1/SuperchainConfig.sol";
        /// @title DelayedWETH
        /// @notice DelayedWETH is an extension to WETH9 that allows for delayed withdrawals. Accounts must trigger an unlock
        ///         function before they can withdraw WETH. Accounts must trigger unlock by specifying a sub-account and an
        ///         amount of WETH to unlock. Accounts can trigger the unlock function at any time, but must wait a delay
        ///         period before they can withdraw after the unlock function is triggered. DelayedWETH is designed to be used
        ///         by the DisputeGame contracts where unlock will only be triggered after a dispute is resolved. DelayedWETH
        ///         is meant to sit behind a proxy contract and has an owner address that can pull WETH from any account and
        ///         can recover ETH from the contract itself. Variable and function naming vaguely follows the vibe of WETH9.
        ///         Not the prettiest contract in the world, but it gets the job done.
        contract DelayedWETH is OwnableUpgradeable, WETH98, IDelayedWETH, ISemver {
            /// @notice Semantic version.
            /// @custom:semver 1.1.0
            string public constant version = "1.1.0";
            /// @inheritdoc IDelayedWETH
            mapping(address => mapping(address => WithdrawalRequest)) public withdrawals;
            /// @notice Withdrawal delay in seconds.
            uint256 internal immutable DELAY_SECONDS;
            /// @notice Address of the SuperchainConfig contract.
            SuperchainConfig public config;
            /// @param _delay The delay for withdrawals in seconds.
            constructor(uint256 _delay) {
                DELAY_SECONDS = _delay;
                initialize({ _owner: address(0), _config: SuperchainConfig(address(0)) });
            }
            /// @notice Initializes the contract.
            /// @param _owner The address of the owner.
            /// @param _config Address of the SuperchainConfig contract.
            function initialize(address _owner, SuperchainConfig _config) public initializer {
                __Ownable_init();
                _transferOwnership(_owner);
                config = _config;
            }
            /// @inheritdoc IDelayedWETH
            function delay() external view returns (uint256) {
                return DELAY_SECONDS;
            }
            /// @inheritdoc IDelayedWETH
            function unlock(address _guy, uint256 _wad) external {
                // Note that the unlock function can be called by any address, but the actual unlocking capability still only
                // gives the msg.sender the ability to withdraw from the account. As long as the unlock and withdraw functions
                // are called with the proper recipient addresses, this will be safe. Could be made safer by having external
                // accounts execute withdrawals themselves but that would have added extra complexity and made DelayedWETH a
                // leaky abstraction, so we chose this instead.
                WithdrawalRequest storage wd = withdrawals[msg.sender][_guy];
                wd.timestamp = block.timestamp;
                wd.amount += _wad;
            }
            /// @inheritdoc IWETH
            function withdraw(uint256 _wad) public override(WETH98, IWETH) {
                withdraw(msg.sender, _wad);
            }
            /// @inheritdoc IDelayedWETH
            function withdraw(address _guy, uint256 _wad) public {
                require(!config.paused(), "DelayedWETH: contract is paused");
                WithdrawalRequest storage wd = withdrawals[msg.sender][_guy];
                require(wd.amount >= _wad, "DelayedWETH: insufficient unlocked withdrawal");
                require(wd.timestamp > 0, "DelayedWETH: withdrawal not unlocked");
                require(wd.timestamp + DELAY_SECONDS <= block.timestamp, "DelayedWETH: withdrawal delay not met");
                wd.amount -= _wad;
                super.withdraw(_wad);
            }
            /// @inheritdoc IDelayedWETH
            function recover(uint256 _wad) external {
                require(msg.sender == owner(), "DelayedWETH: not owner");
                uint256 amount = _wad < address(this).balance ? _wad : address(this).balance;
                (bool success,) = payable(msg.sender).call{ value: amount }(hex"");
                require(success, "DelayedWETH: recover failed");
            }
            /// @inheritdoc IDelayedWETH
            function hold(address _guy, uint256 _wad) external {
                require(msg.sender == owner(), "DelayedWETH: not owner");
                allowance[_guy][msg.sender] = _wad;
                emit Approval(_guy, msg.sender, _wad);
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
        pragma solidity ^0.8.0;
        import "../utils/ContextUpgradeable.sol";
        import "../proxy/utils/Initializable.sol";
        /**
         * @dev Contract module which provides a basic access control mechanism, where
         * there is an account (an owner) that can be granted exclusive access to
         * specific functions.
         *
         * By default, the owner account will be the one that deploys the contract. This
         * can later be changed with {transferOwnership}.
         *
         * This module is used through inheritance. It will make available the modifier
         * `onlyOwner`, which can be applied to your functions to restrict their use to
         * the owner.
         */
        abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
            address private _owner;
            event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
            /**
             * @dev Initializes the contract setting the deployer as the initial owner.
             */
            function __Ownable_init() internal onlyInitializing {
                __Ownable_init_unchained();
            }
            function __Ownable_init_unchained() internal onlyInitializing {
                _transferOwnership(_msgSender());
            }
            /**
             * @dev Throws if called by any account other than the owner.
             */
            modifier onlyOwner() {
                _checkOwner();
                _;
            }
            /**
             * @dev Returns the address of the current owner.
             */
            function owner() public view virtual returns (address) {
                return _owner;
            }
            /**
             * @dev Throws if the sender is not the owner.
             */
            function _checkOwner() internal view virtual {
                require(owner() == _msgSender(), "Ownable: caller is not the owner");
            }
            /**
             * @dev Leaves the contract without owner. It will not be possible to call
             * `onlyOwner` functions anymore. Can only be called by the current owner.
             *
             * NOTE: Renouncing ownership will leave the contract without an owner,
             * thereby removing any functionality that is only available to the owner.
             */
            function renounceOwnership() public virtual onlyOwner {
                _transferOwnership(address(0));
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Can only be called by the current owner.
             */
            function transferOwnership(address newOwner) public virtual onlyOwner {
                require(newOwner != address(0), "Ownable: new owner is the zero address");
                _transferOwnership(newOwner);
            }
            /**
             * @dev Transfers ownership of the contract to a new account (`newOwner`).
             * Internal function without access restriction.
             */
            function _transferOwnership(address newOwner) internal virtual {
                address oldOwner = _owner;
                _owner = newOwner;
                emit OwnershipTransferred(oldOwner, newOwner);
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[49] private __gap;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title ISemver
        /// @notice ISemver is a simple contract for ensuring that contracts are
        ///         versioned using semantic versioning.
        interface ISemver {
            /// @notice Getter for the semantic version of the contract. This is not
            ///         meant to be used onchain but instead meant to be used by offchain
            ///         tooling.
            /// @return Semver contract version as a string.
            function version() external view returns (string memory);
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        import { IWETH } from "src/dispute/interfaces/IWETH.sol";
        /// @title IDelayedWETH
        /// @notice Interface for the DelayedWETH contract.
        interface IDelayedWETH is IWETH {
            /// @notice Represents a withdrawal request.
            struct WithdrawalRequest {
                uint256 amount;
                uint256 timestamp;
            }
            /// @notice Emitted when an unwrap is started.
            /// @param src The address that started the unwrap.
            /// @param wad The amount of WETH that was unwrapped.
            event Unwrap(address indexed src, uint256 wad);
            /// @notice Returns the withdrawal delay in seconds.
            /// @return The withdrawal delay in seconds.
            function delay() external view returns (uint256);
            /// @notice Returns a withdrawal request for the given address.
            /// @param _owner The address to query the withdrawal request of.
            /// @param _guy Sub-account to query the withdrawal request of.
            /// @return The withdrawal request for the given address-subaccount pair.
            function withdrawals(address _owner, address _guy) external view returns (uint256, uint256);
            /// @notice Unlocks withdrawals for the sender's account, after a time delay.
            /// @param _guy Sub-account to unlock.
            /// @param _wad The amount of WETH to unlock.
            function unlock(address _guy, uint256 _wad) external;
            /// @notice Extension to withdrawal, must provide a sub-account to withdraw from.
            /// @param _guy Sub-account to withdraw from.
            /// @param _wad The amount of WETH to withdraw.
            function withdraw(address _guy, uint256 _wad) external;
            /// @notice Allows the owner to recover from error cases by pulling ETH out of the contract.
            /// @param _wad The amount of WETH to recover.
            function recover(uint256 _wad) external;
            /// @notice Allows the owner to recover from error cases by pulling ETH from a specific owner.
            /// @param _guy The address to recover the WETH from.
            /// @param _wad The amount of WETH to recover.
            function hold(address _guy, uint256 _wad) external;
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title IWETH
        /// @notice Interface for WETH9.
        interface IWETH {
            /// @notice Emitted when an approval is made.
            /// @param src The address that approved the transfer.
            /// @param guy The address that was approved to transfer.
            /// @param wad The amount that was approved to transfer.
            event Approval(address indexed src, address indexed guy, uint256 wad);
            /// @notice Emitted when a transfer is made.
            /// @param src The address that transferred the WETH.
            /// @param dst The address that received the WETH.
            /// @param wad The amount of WETH that was transferred.
            event Transfer(address indexed src, address indexed dst, uint256 wad);
            /// @notice Emitted when a deposit is made.
            /// @param dst The address that deposited the WETH.
            /// @param wad The amount of WETH that was deposited.
            event Deposit(address indexed dst, uint256 wad);
            /// @notice Emitted when a withdrawal is made.
            /// @param src The address that withdrew the WETH.
            /// @param wad The amount of WETH that was withdrawn.
            event Withdrawal(address indexed src, uint256 wad);
            /// @notice Returns the name of the token.
            /// @return The name of the token.
            function name() external view returns (string memory);
            /// @notice Returns the symbol of the token.
            /// @return The symbol of the token.
            function symbol() external view returns (string memory);
            /// @notice Returns the number of decimals the token uses.
            /// @return The number of decimals the token uses.
            function decimals() external pure returns (uint8);
            /// @notice Returns the balance of the given address.
            /// @param owner The address to query the balance of.
            /// @return The balance of the given address.
            function balanceOf(address owner) external view returns (uint256);
            /// @notice Returns the amount of WETH that the spender can transfer on behalf of the owner.
            /// @param owner The address that owns the WETH.
            /// @param spender The address that is approved to transfer the WETH.
            /// @return The amount of WETH that the spender can transfer on behalf of the owner.
            function allowance(address owner, address spender) external view returns (uint256);
            /// @notice Allows WETH to be deposited by sending ether to the contract.
            function deposit() external payable;
            /// @notice Withdraws an amount of ETH.
            /// @param wad The amount of ETH to withdraw.
            function withdraw(uint256 wad) external;
            /// @notice Returns the total supply of WETH.
            /// @return The total supply of WETH.
            function totalSupply() external view returns (uint256);
            /// @notice Approves the given address to transfer the WETH on behalf of the caller.
            /// @param guy The address that is approved to transfer the WETH.
            /// @param wad The amount that is approved to transfer.
            /// @return True if the approval was successful.
            function approve(address guy, uint256 wad) external returns (bool);
            /// @notice Transfers the given amount of WETH to the given address.
            /// @param dst The address to transfer the WETH to.
            /// @param wad The amount of WETH to transfer.
            /// @return True if the transfer was successful.
            function transfer(address dst, uint256 wad) external returns (bool);
            /// @notice Transfers the given amount of WETH from the given address to the given address.
            /// @param src The address to transfer the WETH from.
            /// @param dst The address to transfer the WETH to.
            /// @param wad The amount of WETH to transfer.
            /// @return True if the transfer was successful.
            function transferFrom(address src, address dst, uint256 wad) external returns (bool);
        }
        // SPDX-License-Identifier: GPL-3.0
        // Copyright (C) 2015, 2016, 2017 Dapphub
        // This program is free software: you can redistribute it and/or modify
        // it under the terms of the GNU General Public License as published by
        // the Free Software Foundation, either version 3 of the License, or
        // (at your option) any later version.
        // This program is distributed in the hope that it will be useful,
        // but WITHOUT ANY WARRANTY; without even the implied warranty of
        // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        // GNU General Public License for more details.
        // You should have received a copy of the GNU General Public License
        // along with this program.  If not, see <http://www.gnu.org/licenses/>.
        // Based on WETH9 by Dapphub.
        // Modified by OP Labs.
        pragma solidity 0.8.15;
        import { IWETH } from "src/dispute/interfaces/IWETH.sol";
        /// @title WETH98
        /// @notice WETH98 is a version of WETH9 upgraded for Solidity 0.8.x.
        contract WETH98 is IWETH {
            uint8 public constant decimals = 18;
            mapping(address => uint256) public balanceOf;
            mapping(address => mapping(address => uint256)) public allowance;
            /// @notice Pipes to deposit.
            receive() external payable {
                deposit();
            }
            /// @notice Pipes to deposit.
            fallback() external payable {
                deposit();
            }
            /// @inheritdoc IWETH
            function name() external view virtual override returns (string memory) {
                return "Wrapped Ether";
            }
            /// @inheritdoc IWETH
            function symbol() external view virtual override returns (string memory) {
                return "WETH";
            }
            /// @inheritdoc IWETH
            function deposit() public payable virtual {
                balanceOf[msg.sender] += msg.value;
                emit Deposit(msg.sender, msg.value);
            }
            /// @inheritdoc IWETH
            function withdraw(uint256 wad) public virtual {
                require(balanceOf[msg.sender] >= wad);
                balanceOf[msg.sender] -= wad;
                payable(msg.sender).transfer(wad);
                emit Withdrawal(msg.sender, wad);
            }
            /// @inheritdoc IWETH
            function totalSupply() external view returns (uint256) {
                return address(this).balance;
            }
            /// @inheritdoc IWETH
            function approve(address guy, uint256 wad) external returns (bool) {
                allowance[msg.sender][guy] = wad;
                emit Approval(msg.sender, guy, wad);
                return true;
            }
            /// @inheritdoc IWETH
            function transfer(address dst, uint256 wad) external returns (bool) {
                return transferFrom(msg.sender, dst, wad);
            }
            /// @inheritdoc IWETH
            function transferFrom(address src, address dst, uint256 wad) public returns (bool) {
                require(balanceOf[src] >= wad);
                if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) {
                    require(allowance[src][msg.sender] >= wad);
                    allowance[src][msg.sender] -= wad;
                }
                balanceOf[src] -= wad;
                balanceOf[dst] += wad;
                emit Transfer(src, dst, wad);
                return true;
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity 0.8.15;
        import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
        import { ISemver } from "src/universal/ISemver.sol";
        import { Storage } from "src/libraries/Storage.sol";
        /// @custom:audit none This contracts is not yet audited.
        /// @title SuperchainConfig
        /// @notice The SuperchainConfig contract is used to manage configuration of global superchain values.
        contract SuperchainConfig is Initializable, ISemver {
            /// @notice Enum representing different types of updates.
            /// @custom:value GUARDIAN            Represents an update to the guardian.
            enum UpdateType {
                GUARDIAN
            }
            /// @notice Whether or not the Superchain is paused.
            bytes32 public constant PAUSED_SLOT = bytes32(uint256(keccak256("superchainConfig.paused")) - 1);
            /// @notice The address of the guardian, which can pause withdrawals from the System.
            ///         It can only be modified by an upgrade.
            bytes32 public constant GUARDIAN_SLOT = bytes32(uint256(keccak256("superchainConfig.guardian")) - 1);
            /// @notice Emitted when the pause is triggered.
            /// @param identifier A string helping to identify provenance of the pause transaction.
            event Paused(string identifier);
            /// @notice Emitted when the pause is lifted.
            event Unpaused();
            /// @notice Emitted when configuration is updated.
            /// @param updateType Type of update.
            /// @param data       Encoded update data.
            event ConfigUpdate(UpdateType indexed updateType, bytes data);
            /// @notice Semantic version.
            /// @custom:semver 1.1.0
            string public constant version = "1.1.0";
            /// @notice Constructs the SuperchainConfig contract.
            constructor() {
                initialize({ _guardian: address(0), _paused: false });
            }
            /// @notice Initializer.
            /// @param _guardian    Address of the guardian, can pause the OptimismPortal.
            /// @param _paused      Initial paused status.
            function initialize(address _guardian, bool _paused) public initializer {
                _setGuardian(_guardian);
                if (_paused) {
                    _pause("Initializer paused");
                }
            }
            /// @notice Getter for the guardian address.
            function guardian() public view returns (address guardian_) {
                guardian_ = Storage.getAddress(GUARDIAN_SLOT);
            }
            /// @notice Getter for the current paused status.
            function paused() public view returns (bool paused_) {
                paused_ = Storage.getBool(PAUSED_SLOT);
            }
            /// @notice Pauses withdrawals.
            /// @param _identifier (Optional) A string to identify provenance of the pause transaction.
            function pause(string memory _identifier) external {
                require(msg.sender == guardian(), "SuperchainConfig: only guardian can pause");
                _pause(_identifier);
            }
            /// @notice Pauses withdrawals.
            /// @param _identifier (Optional) A string to identify provenance of the pause transaction.
            function _pause(string memory _identifier) internal {
                Storage.setBool(PAUSED_SLOT, true);
                emit Paused(_identifier);
            }
            /// @notice Unpauses withdrawals.
            function unpause() external {
                require(msg.sender == guardian(), "SuperchainConfig: only guardian can unpause");
                Storage.setBool(PAUSED_SLOT, false);
                emit Unpaused();
            }
            /// @notice Sets the guardian address. This is only callable during initialization, so an upgrade
            ///         will be required to change the guardian.
            /// @param _guardian The new guardian address.
            function _setGuardian(address _guardian) internal {
                Storage.setAddress(GUARDIAN_SLOT, _guardian);
                emit ConfigUpdate(UpdateType.GUARDIAN, abi.encode(_guardian));
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
        pragma solidity ^0.8.0;
        import "../proxy/utils/Initializable.sol";
        /**
         * @dev Provides information about the current execution context, including the
         * sender of the transaction and its data. While these are generally available
         * via msg.sender and msg.data, they should not be accessed in such a direct
         * manner, since when dealing with meta-transactions the account sending and
         * paying for execution may not be the actual sender (as far as an application
         * is concerned).
         *
         * This contract is only required for intermediate, library-like contracts.
         */
        abstract contract ContextUpgradeable is Initializable {
            function __Context_init() internal onlyInitializing {
            }
            function __Context_init_unchained() internal onlyInitializing {
            }
            function _msgSender() internal view virtual returns (address) {
                return msg.sender;
            }
            function _msgData() internal view virtual returns (bytes calldata) {
                return msg.data;
            }
            /**
             * @dev This empty reserved space is put in place to allow future versions to add new
             * variables without shifting down storage in the inheritance chain.
             * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
             */
            uint256[50] private __gap;
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/AddressUpgradeable.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
             * initialization step. This is essential to configure modules that are added through upgrades and that require
             * initialization.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized < type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
        pragma solidity ^0.8.2;
        import "../../utils/Address.sol";
        /**
         * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
         * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
         * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
         * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
         *
         * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
         * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
         * case an upgrade adds a module that needs to be initialized.
         *
         * For example:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * contract MyToken is ERC20Upgradeable {
         *     function initialize() initializer public {
         *         __ERC20_init("MyToken", "MTK");
         *     }
         * }
         * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
         *     function initializeV2() reinitializer(2) public {
         *         __ERC20Permit_init("MyToken");
         *     }
         * }
         * ```
         *
         * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
         * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
         *
         * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
         * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
         *
         * [CAUTION]
         * ====
         * Avoid leaving a contract uninitialized.
         *
         * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
         * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
         * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
         *
         * [.hljs-theme-light.nopadding]
         * ```
         * /// @custom:oz-upgrades-unsafe-allow constructor
         * constructor() {
         *     _disableInitializers();
         * }
         * ```
         * ====
         */
        abstract contract Initializable {
            /**
             * @dev Indicates that the contract has been initialized.
             * @custom:oz-retyped-from bool
             */
            uint8 private _initialized;
            /**
             * @dev Indicates that the contract is in the process of being initialized.
             */
            bool private _initializing;
            /**
             * @dev Triggered when the contract has been initialized or reinitialized.
             */
            event Initialized(uint8 version);
            /**
             * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
             * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
             */
            modifier initializer() {
                bool isTopLevelCall = !_initializing;
                require(
                    (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
                    "Initializable: contract is already initialized"
                );
                _initialized = 1;
                if (isTopLevelCall) {
                    _initializing = true;
                }
                _;
                if (isTopLevelCall) {
                    _initializing = false;
                    emit Initialized(1);
                }
            }
            /**
             * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
             * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
             * used to initialize parent contracts.
             *
             * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
             * initialization step. This is essential to configure modules that are added through upgrades and that require
             * initialization.
             *
             * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
             * a contract, executing them in the right order is up to the developer or operator.
             */
            modifier reinitializer(uint8 version) {
                require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                _initialized = version;
                _initializing = true;
                _;
                _initializing = false;
                emit Initialized(version);
            }
            /**
             * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
             * {initializer} and {reinitializer} modifiers, directly or indirectly.
             */
            modifier onlyInitializing() {
                require(_initializing, "Initializable: contract is not initializing");
                _;
            }
            /**
             * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
             * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
             * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
             * through proxies.
             */
            function _disableInitializers() internal virtual {
                require(!_initializing, "Initializable: contract is initializing");
                if (_initialized < type(uint8).max) {
                    _initialized = type(uint8).max;
                    emit Initialized(type(uint8).max);
                }
            }
        }
        // SPDX-License-Identifier: MIT
        pragma solidity ^0.8.0;
        /// @title Storage
        /// @notice Storage handles reading and writing to arbitary storage locations
        library Storage {
            /// @notice Returns an address stored in an arbitrary storage slot.
            ///         These storage slots decouple the storage layout from
            ///         solc's automation.
            /// @param _slot The storage slot to retrieve the address from.
            function getAddress(bytes32 _slot) internal view returns (address addr_) {
                assembly {
                    addr_ := sload(_slot)
                }
            }
            /// @notice Stores an address in an arbitrary storage slot, `_slot`.
            /// @param _slot The storage slot to store the address in.
            /// @param _address The protocol version to store
            /// @dev WARNING! This function must be used cautiously, as it allows for overwriting addresses
            ///      in arbitrary storage slots.
            function setAddress(bytes32 _slot, address _address) internal {
                assembly {
                    sstore(_slot, _address)
                }
            }
            /// @notice Returns a uint256 stored in an arbitrary storage slot.
            ///         These storage slots decouple the storage layout from
            ///         solc's automation.
            /// @param _slot The storage slot to retrieve the address from.
            function getUint(bytes32 _slot) internal view returns (uint256 value_) {
                assembly {
                    value_ := sload(_slot)
                }
            }
            /// @notice Stores a value in an arbitrary storage slot, `_slot`.
            /// @param _slot The storage slot to store the address in.
            /// @param _value The protocol version to store
            /// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
            ///      in arbitrary storage slots.
            function setUint(bytes32 _slot, uint256 _value) internal {
                assembly {
                    sstore(_slot, _value)
                }
            }
            /// @notice Returns a bytes32 stored in an arbitrary storage slot.
            ///         These storage slots decouple the storage layout from
            ///         solc's automation.
            /// @param _slot The storage slot to retrieve the address from.
            function getBytes32(bytes32 _slot) internal view returns (bytes32 value_) {
                assembly {
                    value_ := sload(_slot)
                }
            }
            /// @notice Stores a bytes32 value in an arbitrary storage slot, `_slot`.
            /// @param _slot The storage slot to store the address in.
            /// @param _value The bytes32 value to store.
            /// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
            ///      in arbitrary storage slots.
            function setBytes32(bytes32 _slot, bytes32 _value) internal {
                assembly {
                    sstore(_slot, _value)
                }
            }
            /// @notice Stores a bool value in an arbitrary storage slot, `_slot`.
            /// @param _slot The storage slot to store the bool in.
            /// @param _value The bool value to store
            /// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
            ///      in arbitrary storage slots.
            function setBool(bytes32 _slot, bool _value) internal {
                assembly {
                    sstore(_slot, _value)
                }
            }
            /// @notice Returns a bool stored in an arbitrary storage slot.
            /// @param _slot The storage slot to retrieve the bool from.
            function getBool(bytes32 _slot) internal view returns (bool value_) {
                assembly {
                    value_ := sload(_slot)
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library AddressUpgradeable {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCall(target, data, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                require(isContract(target), "Address: call to non-contract");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                require(isContract(target), "Address: static call to non-contract");
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
        }
        // SPDX-License-Identifier: MIT
        // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
        pragma solidity ^0.8.1;
        /**
         * @dev Collection of functions related to the address type
         */
        library Address {
            /**
             * @dev Returns true if `account` is a contract.
             *
             * [IMPORTANT]
             * ====
             * It is unsafe to assume that an address for which this function returns
             * false is an externally-owned account (EOA) and not a contract.
             *
             * Among others, `isContract` will return false for the following
             * types of addresses:
             *
             *  - an externally-owned account
             *  - a contract in construction
             *  - an address where a contract will be created
             *  - an address where a contract lived, but was destroyed
             * ====
             *
             * [IMPORTANT]
             * ====
             * You shouldn't rely on `isContract` to protect against flash loan attacks!
             *
             * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
             * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
             * constructor.
             * ====
             */
            function isContract(address account) internal view returns (bool) {
                // This method relies on extcodesize/address.code.length, which returns 0
                // for contracts in construction, since the code is only stored at the end
                // of the constructor execution.
                return account.code.length > 0;
            }
            /**
             * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
             * `recipient`, forwarding all available gas and reverting on errors.
             *
             * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
             * of certain opcodes, possibly making contracts go over the 2300 gas limit
             * imposed by `transfer`, making them unable to receive funds via
             * `transfer`. {sendValue} removes this limitation.
             *
             * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
             *
             * IMPORTANT: because control is transferred to `recipient`, care must be
             * taken to not create reentrancy vulnerabilities. Consider using
             * {ReentrancyGuard} or the
             * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
             */
            function sendValue(address payable recipient, uint256 amount) internal {
                require(address(this).balance >= amount, "Address: insufficient balance");
                (bool success, ) = recipient.call{value: amount}("");
                require(success, "Address: unable to send value, recipient may have reverted");
            }
            /**
             * @dev Performs a Solidity function call using a low level `call`. A
             * plain `call` is an unsafe replacement for a function call: use this
             * function instead.
             *
             * If `target` reverts with a revert reason, it is bubbled up by this
             * function (like regular Solidity function calls).
             *
             * Returns the raw returned data. To convert to the expected return value,
             * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
             *
             * Requirements:
             *
             * - `target` must be a contract.
             * - calling `target` with `data` must not revert.
             *
             * _Available since v3.1._
             */
            function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionCall(target, data, "Address: low-level call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
             * `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, 0, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but also transferring `value` wei to `target`.
             *
             * Requirements:
             *
             * - the calling contract must have an ETH balance of at least `value`.
             * - the called Solidity function must be `payable`.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value
            ) internal returns (bytes memory) {
                return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
            }
            /**
             * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
             * with `errorMessage` as a fallback revert reason when `target` reverts.
             *
             * _Available since v3.1._
             */
            function functionCallWithValue(
                address target,
                bytes memory data,
                uint256 value,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(address(this).balance >= value, "Address: insufficient balance for call");
                require(isContract(target), "Address: call to non-contract");
                (bool success, bytes memory returndata) = target.call{value: value}(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                return functionStaticCall(target, data, "Address: low-level static call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a static call.
             *
             * _Available since v3.3._
             */
            function functionStaticCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal view returns (bytes memory) {
                require(isContract(target), "Address: static call to non-contract");
                (bool success, bytes memory returndata) = target.staticcall(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                return functionDelegateCall(target, data, "Address: low-level delegate call failed");
            }
            /**
             * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
             * but performing a delegate call.
             *
             * _Available since v3.4._
             */
            function functionDelegateCall(
                address target,
                bytes memory data,
                string memory errorMessage
            ) internal returns (bytes memory) {
                require(isContract(target), "Address: delegate call to non-contract");
                (bool success, bytes memory returndata) = target.delegatecall(data);
                return verifyCallResult(success, returndata, errorMessage);
            }
            /**
             * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
             * revert reason using the provided one.
             *
             * _Available since v4.3._
             */
            function verifyCallResult(
                bool success,
                bytes memory returndata,
                string memory errorMessage
            ) internal pure returns (bytes memory) {
                if (success) {
                    return returndata;
                } else {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
        }