Source Code
Overview
ETH Balance
0 ETH
More Info
ContractCreator
Multichain Info
N/A
Latest 1 from a total of 1 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
0x61020060 | 6306583 | 92 days ago | IN | 0 ETH | 0.01768979 |
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xBEA4384f...9eD2fe0C6 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
PermissionedDisputeGame
Compiler Version
v0.8.15+commit.e14f2714
Optimization Enabled:
Yes with 999999 runs
Other Settings:
london EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol"; import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol"; import { FaultDisputeGame, IFaultDisputeGame, IBigStepper, IInitializable } from "src/dispute/FaultDisputeGame.sol"; import "src/dispute/lib/Types.sol"; import "src/dispute/lib/Errors.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 IFaultDisputeGame 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); } /// @inheritdoc IInitializable 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.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; import { IDisputeGameFactory } from "src/dispute/interfaces/IDisputeGameFactory.sol"; import "src/dispute/lib/Types.sol"; /// @title IAnchorStateRegistry /// @notice Describes a contract that stores the anchor state for each game type. interface IAnchorStateRegistry { /// @notice Returns the anchor state for the given game type. /// @param _gameType The game type to get the anchor state for. /// @return The anchor state for the given game type. function anchors(GameType _gameType) external view returns (Hash, uint256); /// @notice Returns the DisputeGameFactory address. /// @return DisputeGameFactory address. function disputeGameFactory() external view returns (IDisputeGameFactory); /// @notice Callable by FaultDisputeGame contracts to update the anchor state. Pulls the anchor state directly from /// the FaultDisputeGame contract and stores it in the registry if the new anchor state is valid and the /// state is newer than the current anchor state. function tryUpdateAnchorState() external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import { FixedPointMathLib } from "@solady/utils/FixedPointMathLib.sol"; import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol"; import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol"; import { IFaultDisputeGame } from "src/dispute/interfaces/IFaultDisputeGame.sol"; import { IInitializable } from "src/dispute/interfaces/IInitializable.sol"; import { IBigStepper, IPreimageOracle } from "src/dispute/interfaces/IBigStepper.sol"; import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol"; import { Clone } from "@solady/utils/Clone.sol"; import { Types } from "src/libraries/Types.sol"; import { ISemver } from "src/universal/ISemver.sol"; import { Types } from "src/libraries/Types.sol"; import { Hashing } from "src/libraries/Hashing.sol"; import { RLPReader } from "src/libraries/rlp/RLPReader.sol"; import "src/dispute/lib/Types.sol"; import "src/dispute/lib/Errors.sol"; /// @title FaultDisputeGame /// @notice An implementation of the `IFaultDisputeGame` interface. contract FaultDisputeGame is IFaultDisputeGame, Clone, ISemver { //////////////////////////////////////////////////////////////// // 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.2.0 string public constant version = "1.2.0"; /// @notice The starting timestamp of the game Timestamp public createdAt; /// @notice The timestamp of the game's global resolution. Timestamp public resolvedAt; /// @inheritdoc IDisputeGame 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 cannot be greater than or equal to the max game depth. if (_splitDepth >= _maxGameDepth) revert InvalidSplitDepth(); // The clock extension may not be greater than the max clock duration. if (_clockExtension.raw() > _maxClockDuration.raw()) revert InvalidClockExtension(); 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; } /// @inheritdoc IInitializable 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 // //////////////////////////////////////////////////////////////// /// @inheritdoc IFaultDisputeGame 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(); // If the remaining clock time has less than `CLOCK_EXTENSION` seconds remaining, grant the potential // grandchild's clock `CLOCK_EXTENSION` seconds. This is to ensure that, even if a player has to inherit another // team's clock to counter a freeloader claim, they will always have enough time to to respond. This extension // is bounded by the depth of the tree. If the potential grandchild is an execution trace bisection root, the // clock extension is doubled. This is to allow for extra time for the off-chain challenge agent to generate // the initial instruction trace on the native FPVM. if (nextDuration.raw() > MAX_CLOCK_DURATION.raw() - CLOCK_EXTENSION.raw()) { // If the potential grandchild is an execution trace bisection root, double the clock extension. uint64 extensionPeriod = nextPositionDepth == SPLIT_DEPTH - 1 ? CLOCK_EXTENSION.raw() * 2 : CLOCK_EXTENSION.raw(); nextDuration = Duration.wrap(MAX_CLOCK_DURATION.raw() - extensionPeriod); } // 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); } /// @inheritdoc IFaultDisputeGame function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable { move(_disputed, _parentIndex, _claim, true); } /// @inheritdoc IFaultDisputeGame function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable { move(_disputed, _parentIndex, _claim, false); } /// @inheritdoc IFaultDisputeGame 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; 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(); } } /// @inheritdoc IFaultDisputeGame 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; } /// @inheritdoc IFaultDisputeGame function l2BlockNumber() public pure returns (uint256 l2BlockNumber_) { l2BlockNumber_ = _getArgUint256(0x54); } /// @inheritdoc IFaultDisputeGame function startingBlockNumber() external view returns (uint256 startingBlockNumber_) { startingBlockNumber_ = startingOutputRoot.l2BlockNumber; } /// @inheritdoc IFaultDisputeGame 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 // //////////////////////////////////////////////////////////////// /// @inheritdoc IDisputeGame 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(); } /// @inheritdoc IFaultDisputeGame 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; } } } /// @inheritdoc IDisputeGame function gameType() public view override returns (GameType gameType_) { gameType_ = GAME_TYPE; } /// @inheritdoc IDisputeGame function gameCreator() public pure returns (address creator_) { creator_ = _getArgAddress(0x00); } /// @inheritdoc IDisputeGame function rootClaim() public pure returns (Claim rootClaim_) { rootClaim_ = Claim.wrap(_getArgBytes32(0x14)); } /// @inheritdoc IDisputeGame function l1Head() public pure returns (Hash l1Head_) { l1Head_ = Hash.wrap(_getArgBytes32(0x34)); } /// @inheritdoc IDisputeGame 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); } /// @inheritdoc IDisputeGame 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 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 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();
// 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: MIT pragma solidity ^0.8.0; import { IDisputeGame } from "./IDisputeGame.sol"; import "src/dispute/lib/Types.sol"; /// @title IDisputeGameFactory /// @notice The interface for a DisputeGameFactory contract. interface IDisputeGameFactory { /// @notice Emitted when a new dispute game is created /// @param disputeProxy The address of the dispute game proxy /// @param gameType The type of the dispute game proxy's implementation /// @param rootClaim The root claim of the dispute game event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim); /// @notice Emitted when a new game implementation added to the factory /// @param impl The implementation contract for the given `GameType`. /// @param gameType The type of the DisputeGame. event ImplementationSet(address indexed impl, GameType indexed gameType); /// @notice Emitted when a game type's initialization bond is updated /// @param gameType The type of the DisputeGame. /// @param newBond The new bond (in wei) for initializing the game type. event InitBondUpdated(GameType indexed gameType, uint256 indexed newBond); /// @notice Information about a dispute game found in a `findLatestGames` search. struct GameSearchResult { uint256 index; GameId metadata; Timestamp timestamp; Claim rootClaim; bytes extraData; } /// @notice The total number of dispute games created by this factory. /// @return gameCount_ The total number of dispute games created by this factory. function gameCount() external view returns (uint256 gameCount_); /// @notice `games` queries an internal mapping that maps the hash of /// `gameType ++ rootClaim ++ extraData` to the deployed `DisputeGame` clone. /// @dev `++` equates to concatenation. /// @param _gameType The type of the DisputeGame - used to decide the proxy implementation /// @param _rootClaim The root claim of the DisputeGame. /// @param _extraData Any extra data that should be provided to the created dispute game. /// @return proxy_ The clone of the `DisputeGame` created with the given parameters. /// Returns `address(0)` if nonexistent. /// @return timestamp_ The timestamp of the creation of the dispute game. function games( GameType _gameType, Claim _rootClaim, bytes calldata _extraData ) external view returns (IDisputeGame proxy_, Timestamp timestamp_); /// @notice `gameAtIndex` returns the dispute game contract address and its creation timestamp /// at the given index. Each created dispute game increments the underlying index. /// @param _index The index of the dispute game. /// @return gameType_ The type of the DisputeGame - used to decide the proxy implementation. /// @return timestamp_ The timestamp of the creation of the dispute game. /// @return proxy_ The clone of the `DisputeGame` created with the given parameters. /// Returns `address(0)` if nonexistent. function gameAtIndex(uint256 _index) external view returns (GameType gameType_, Timestamp timestamp_, IDisputeGame proxy_); /// @notice `gameImpls` is a mapping that maps `GameType`s to their respective /// `IDisputeGame` implementations. /// @param _gameType The type of the dispute game. /// @return impl_ The address of the implementation of the game type. /// Will be cloned on creation of a new dispute game with the given `gameType`. function gameImpls(GameType _gameType) external view returns (IDisputeGame impl_); /// @notice Returns the required bonds for initializing a dispute game of the given type. /// @param _gameType The type of the dispute game. /// @return bond_ The required bond for initializing a dispute game of the given type. function initBonds(GameType _gameType) external view returns (uint256 bond_); /// @notice Creates a new DisputeGame proxy contract. /// @param _gameType The type of the DisputeGame - used to decide the proxy implementation. /// @param _rootClaim The root claim of the DisputeGame. /// @param _extraData Any extra data that should be provided to the created dispute game. /// @return proxy_ The address of the created DisputeGame proxy. function create( GameType _gameType, Claim _rootClaim, bytes calldata _extraData ) external payable returns (IDisputeGame proxy_); /// @notice Sets the implementation contract for a specific `GameType`. /// @dev May only be called by the `owner`. /// @param _gameType The type of the DisputeGame. /// @param _impl The implementation contract for the given `GameType`. function setImplementation(GameType _gameType, IDisputeGame _impl) external; /// @notice Sets the bond (in wei) for initializing a game type. /// @dev May only be called by the `owner`. /// @param _gameType The type of the DisputeGame. /// @param _initBond The bond (in wei) for initializing a game type. function setInitBond(GameType _gameType, uint256 _initBond) external; /// @notice Returns a unique identifier for the given dispute game parameters. /// @dev Hashes the concatenation of `gameType . rootClaim . extraData` /// without expanding memory. /// @param _gameType The type of the DisputeGame. /// @param _rootClaim The root claim of the DisputeGame. /// @param _extraData Any extra data that should be provided to the created dispute game. /// @return uuid_ The unique identifier for the given dispute game parameters. function getGameUUID( GameType _gameType, Claim _rootClaim, bytes memory _extraData ) external pure returns (Hash uuid_); /// @notice Finds the `_n` most recent `GameId`'s of type `_gameType` starting at `_start`. If there are less than /// `_n` games of type `_gameType` starting at `_start`, then the returned array will be shorter than `_n`. /// @param _gameType The type of game to find. /// @param _start The index to start the reverse search from. /// @param _n The number of games to find. function findLatestGames( GameType _gameType, uint256 _start, uint256 _n ) external view returns (GameSearchResult[] memory games_); }
// 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.0; import { IInitializable } from "src/dispute/interfaces/IInitializable.sol"; import "src/dispute/lib/Types.sol"; /// @title IDisputeGame /// @notice The generic interface for a DisputeGame contract. interface IDisputeGame is IInitializable { /// @notice Emitted when the game is resolved. /// @param status The status of the game after resolution. event Resolved(GameStatus indexed status); /// @notice Returns the timestamp that the DisputeGame contract was created at. /// @return createdAt_ The timestamp that the DisputeGame contract was created at. function createdAt() external view returns (Timestamp createdAt_); /// @notice Returns the timestamp that the DisputeGame contract was resolved at. /// @return resolvedAt_ The timestamp that the DisputeGame contract was resolved at. function resolvedAt() external view returns (Timestamp resolvedAt_); /// @notice Returns the current status of the game. /// @return status_ The current status of the game. function status() external view returns (GameStatus status_); /// @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() external view returns (GameType gameType_); /// @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() external pure returns (address creator_); /// @notice Getter for the root claim. /// @dev `clones-with-immutable-args` argument #2 /// @return rootClaim_ The root claim of the DisputeGame. function rootClaim() external pure returns (Claim rootClaim_); /// @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() external pure returns (Hash l1Head_); /// @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() external pure returns (bytes memory extraData_); /// @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_); /// @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_); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IDisputeGame } from "./IDisputeGame.sol"; import "src/dispute/lib/Types.sol"; /// @title IFaultDisputeGame /// @notice The interface for a fault proof backed dispute game. interface IFaultDisputeGame is IDisputeGame { /// @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; } /// @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); /// @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; /// @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; /// @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) external; /// @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; /// @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; /// @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) external view returns (uint256 numRemainingChildren_); /// @notice The l2BlockNumber of the disputed output root in the `L2OutputOracle`. function l2BlockNumber() external view returns (uint256 l2BlockNumber_); /// @notice Starting output root and block number of the game. function startingOutputRoot() external view returns (Hash startingRoot_, uint256 l2BlockNumber_); /// @notice Only the starting block number of the game. function startingBlockNumber() external view returns (uint256 startingBlockNumber_); /// @notice Only the starting output root of the game. function startingRootHash() external view returns (Hash startingRootHash_); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title IInitializable /// @notice An interface for initializable contracts. interface IInitializable { /// @notice Initializes the contract. /// @dev This function may only be called once. function initialize() external payable; }
// 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 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; } }
// 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 { 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 ) ); } }
// 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.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.15; /// @title IPreimageOracle /// @notice Interface for a preimage oracle. interface IPreimageOracle { /// @notice Reads a preimage from the oracle. /// @param _key The key of the preimage to read. /// @param _offset The offset of the preimage to read. /// @return dat_ The preimage data. /// @return datLen_ The length of the preimage data. function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_); /// @notice Loads of local data part into the preimage oracle. /// @param _ident The identifier of the local data. /// @param _localContext The local key context for the preimage oracle. Optionally, can be set as a constant /// if the caller only requires one set of local keys. /// @param _word The local data word. /// @param _size The number of bytes in `_word` to load. /// @param _partOffset The offset of the local data part to write to the oracle. /// @dev The local data parts are loaded into the preimage oracle under the context /// of the caller - no other account can write to the caller's context /// specific data. /// /// There are 5 local data identifiers: /// ┌────────────┬────────────────────────┐ /// │ Identifier │ Data │ /// ├────────────┼────────────────────────┤ /// │ 1 │ L1 Head Hash (bytes32) │ /// │ 2 │ Output Root (bytes32) │ /// │ 3 │ Root Claim (bytes32) │ /// │ 4 │ L2 Block Number (u64) │ /// │ 5 │ Chain ID (u64) │ /// └────────────┴────────────────────────┘ function loadLocalData( uint256 _ident, bytes32 _localContext, bytes32 _word, uint256 _size, uint256 _partOffset ) external returns (bytes32 key_); /// @notice Prepares a preimage to be read by keccak256 key, starting at the given offset and up to 32 bytes /// (clipped at preimage length, if out of data). /// @param _partOffset The offset of the preimage to read. /// @param _preimage The preimage data. function loadKeccak256PreimagePart(uint256 _partOffset, bytes calldata _preimage) external; /// @notice Prepares a preimage to be read by sha256 key, starting at the given offset and up to 32 bytes /// (clipped at preimage length, if out of data). /// @param _partOffset The offset of the preimage to read. /// @param _preimage The preimage data. function loadSha256PreimagePart(uint256 _partOffset, bytes calldata _preimage) external; /// @notice Verifies that `p(_z) = _y` given `_commitment` that corresponds to the polynomial `p(x)` and a KZG // proof. The value `y` is the pre-image, and the preimage key is `5 ++ keccak256(_commitment ++ z)[1:]`. /// @param _z Big endian point value. Part of the preimage key. /// @param _y Big endian point value. The preimage for the key. /// @param _commitment The commitment to the polynomial. 48 bytes, part of the preimage key. /// @param _proof The KZG proof, part of the preimage key. /// @param _partOffset The offset of the preimage to store. function loadBlobPreimagePart( uint256 _z, uint256 _y, bytes calldata _commitment, bytes calldata _proof, uint256 _partOffset ) external; /// @notice Prepares a precompile result to be read by a precompile key for the specified offset. /// The precompile result data is a concatenation of the precompile call status byte and its return data. /// The preimage key is `6 ++ keccak256(precompile ++ input)[1:]`. /// @param _partOffset The offset of the precompile result being loaded. /// @param _precompile The precompile address /// @param _input The input to the precompile call. function loadPrecompilePreimagePart(uint256 _partOffset, address _precompile, bytes calldata _input) 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) { 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) { 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. /// @param _dependencySet Array of the chain IDs in the interop dependency set. function encodeSetL1BlockValuesInterop( uint32 _baseFeeScalar, uint32 _blobBaseFeeScalar, uint64 _sequenceNumber, uint64 _timestamp, uint64 _number, uint256 _baseFee, uint256 _blobBaseFee, bytes32 _hash, bytes32 _batcherHash, uint256[] memory _dependencySet ) internal pure returns (bytes memory) { require(_dependencySet.length <= type(uint8).max, "Encoding: dependency set length is too large"); // Check that the batcher hash is just the address with 0 padding to the left for version 0. require(uint160(uint256(_batcherHash)) == uint256(_batcherHash), "Encoding: invalid batcher hash"); bytes4 functionSignature = bytes4(keccak256("setL1BlockValuesInterop()")); return abi.encodePacked( functionSignature, _baseFeeScalar, _blobBaseFeeScalar, _sequenceNumber, _timestamp, _number, _baseFee, _blobBaseFee, _hash, _batcherHash, uint8(_dependencySet.length), _dependencySet ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; /// @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; /// @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; } } }
{ "remappings": [ "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/", "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/", "@rari-capital/solmate/=lib/solmate/", "@lib-keccak/=lib/lib-keccak/contracts/lib/", "@solady/=lib/solady/src/", "forge-std/=lib/forge-std/src/", "ds-test/=lib/forge-std/lib/ds-test/src/", "safe-contracts/=lib/safe-contracts/contracts/", "kontrol-cheatcodes/=lib/kontrol-cheatcodes/src/", "@solady-test/=lib/lib-keccak/lib/solady/test/", "lib-keccak/=lib/lib-keccak/contracts/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "solady/=lib/solady/", "solmate/=lib/solmate/src/" ], "optimizer": { "enabled": true, "runs": 999999 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "none" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "london", "viaIR": false, "libraries": {} }
[{"inputs":[{"internalType":"GameType","name":"_gameType","type":"uint32"},{"internalType":"Claim","name":"_absolutePrestate","type":"bytes32"},{"internalType":"uint256","name":"_maxGameDepth","type":"uint256"},{"internalType":"uint256","name":"_splitDepth","type":"uint256"},{"internalType":"Duration","name":"_clockExtension","type":"uint64"},{"internalType":"Duration","name":"_maxClockDuration","type":"uint64"},{"internalType":"contract IBigStepper","name":"_vm","type":"address"},{"internalType":"contract IDelayedWETH","name":"_weth","type":"address"},{"internalType":"contract IAnchorStateRegistry","name":"_anchorStateRegistry","type":"address"},{"internalType":"uint256","name":"_l2ChainId","type":"uint256"},{"internalType":"address","name":"_proposer","type":"address"},{"internalType":"address","name":"_challenger","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"AnchorRootNotFound","type":"error"},{"inputs":[],"name":"BadAuth","type":"error"},{"inputs":[],"name":"BlockNumberMatches","type":"error"},{"inputs":[],"name":"BondTransferFailed","type":"error"},{"inputs":[],"name":"CannotDefendRootClaim","type":"error"},{"inputs":[],"name":"ClaimAboveSplit","type":"error"},{"inputs":[],"name":"ClaimAlreadyExists","type":"error"},{"inputs":[],"name":"ClaimAlreadyResolved","type":"error"},{"inputs":[],"name":"ClockNotExpired","type":"error"},{"inputs":[],"name":"ClockTimeExceeded","type":"error"},{"inputs":[],"name":"ContentLengthMismatch","type":"error"},{"inputs":[],"name":"DuplicateStep","type":"error"},{"inputs":[],"name":"EmptyItem","type":"error"},{"inputs":[],"name":"GameDepthExceeded","type":"error"},{"inputs":[],"name":"GameNotInProgress","type":"error"},{"inputs":[],"name":"IncorrectBondAmount","type":"error"},{"inputs":[],"name":"InvalidClockExtension","type":"error"},{"inputs":[],"name":"InvalidDataRemainder","type":"error"},{"inputs":[],"name":"InvalidDisputedClaimIndex","type":"error"},{"inputs":[],"name":"InvalidHeader","type":"error"},{"inputs":[],"name":"InvalidHeaderRLP","type":"error"},{"inputs":[],"name":"InvalidLocalIdent","type":"error"},{"inputs":[],"name":"InvalidOutputRootProof","type":"error"},{"inputs":[],"name":"InvalidParent","type":"error"},{"inputs":[],"name":"InvalidPrestate","type":"error"},{"inputs":[],"name":"InvalidSplitDepth","type":"error"},{"inputs":[],"name":"L2BlockNumberChallenged","type":"error"},{"inputs":[],"name":"MaxDepthTooLarge","type":"error"},{"inputs":[],"name":"NoCreditToClaim","type":"error"},{"inputs":[],"name":"OutOfOrderResolution","type":"error"},{"inputs":[],"name":"UnexpectedList","type":"error"},{"inputs":[{"internalType":"Claim","name":"rootClaim","type":"bytes32"}],"name":"UnexpectedRootClaim","type":"error"},{"inputs":[],"name":"UnexpectedString","type":"error"},{"inputs":[],"name":"ValidStep","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"parentIndex","type":"uint256"},{"indexed":true,"internalType":"Claim","name":"claim","type":"bytes32"},{"indexed":true,"internalType":"address","name":"claimant","type":"address"}],"name":"Move","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"enum GameStatus","name":"status","type":"uint8"}],"name":"Resolved","type":"event"},{"inputs":[],"name":"absolutePrestate","outputs":[{"internalType":"Claim","name":"absolutePrestate_","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_ident","type":"uint256"},{"internalType":"uint256","name":"_execLeafIdx","type":"uint256"},{"internalType":"uint256","name":"_partOffset","type":"uint256"}],"name":"addLocalData","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"anchorStateRegistry","outputs":[{"internalType":"contract IAnchorStateRegistry","name":"registry_","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Claim","name":"_disputed","type":"bytes32"},{"internalType":"uint256","name":"_parentIndex","type":"uint256"},{"internalType":"Claim","name":"_claim","type":"bytes32"}],"name":"attack","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes32","name":"version","type":"bytes32"},{"internalType":"bytes32","name":"stateRoot","type":"bytes32"},{"internalType":"bytes32","name":"messagePasserStorageRoot","type":"bytes32"},{"internalType":"bytes32","name":"latestBlockhash","type":"bytes32"}],"internalType":"struct Types.OutputRootProof","name":"_outputRootProof","type":"tuple"},{"internalType":"bytes","name":"_headerRLP","type":"bytes"}],"name":"challengeRootL2Block","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"challenger","outputs":[{"internalType":"address","name":"challenger_","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_recipient","type":"address"}],"name":"claimCredit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"claimData","outputs":[{"internalType":"uint32","name":"parentIndex","type":"uint32"},{"internalType":"address","name":"counteredBy","type":"address"},{"internalType":"address","name":"claimant","type":"address"},{"internalType":"uint128","name":"bond","type":"uint128"},{"internalType":"Claim","name":"claim","type":"bytes32"},{"internalType":"Position","name":"position","type":"uint128"},{"internalType":"Clock","name":"clock","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimDataLen","outputs":[{"internalType":"uint256","name":"len_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Hash","name":"","type":"bytes32"}],"name":"claims","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"clockExtension","outputs":[{"internalType":"Duration","name":"clockExtension_","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"createdAt","outputs":[{"internalType":"Timestamp","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"credit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Claim","name":"_disputed","type":"bytes32"},{"internalType":"uint256","name":"_parentIndex","type":"uint256"},{"internalType":"Claim","name":"_claim","type":"bytes32"}],"name":"defend","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"extraData","outputs":[{"internalType":"bytes","name":"extraData_","type":"bytes"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"gameCreator","outputs":[{"internalType":"address","name":"creator_","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"gameData","outputs":[{"internalType":"GameType","name":"gameType_","type":"uint32"},{"internalType":"Claim","name":"rootClaim_","type":"bytes32"},{"internalType":"bytes","name":"extraData_","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gameType","outputs":[{"internalType":"GameType","name":"gameType_","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_claimIndex","type":"uint256"}],"name":"getChallengerDuration","outputs":[{"internalType":"Duration","name":"duration_","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_claimIndex","type":"uint256"}],"name":"getNumToResolve","outputs":[{"internalType":"uint256","name":"numRemainingChildren_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Position","name":"_position","type":"uint128"}],"name":"getRequiredBond","outputs":[{"internalType":"uint256","name":"requiredBond_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"l1Head","outputs":[{"internalType":"Hash","name":"l1Head_","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"l2BlockNumber","outputs":[{"internalType":"uint256","name":"l2BlockNumber_","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"l2BlockNumberChallenged","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"l2BlockNumberChallenger","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"l2ChainId","outputs":[{"internalType":"uint256","name":"l2ChainId_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxClockDuration","outputs":[{"internalType":"Duration","name":"maxClockDuration_","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxGameDepth","outputs":[{"internalType":"uint256","name":"maxGameDepth_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Claim","name":"_disputed","type":"bytes32"},{"internalType":"uint256","name":"_challengeIndex","type":"uint256"},{"internalType":"Claim","name":"_claim","type":"bytes32"},{"internalType":"bool","name":"_isAttack","type":"bool"}],"name":"move","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"proposer","outputs":[{"internalType":"address","name":"proposer_","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"resolutionCheckpoints","outputs":[{"internalType":"bool","name":"initialCheckpointComplete","type":"bool"},{"internalType":"uint32","name":"subgameIndex","type":"uint32"},{"internalType":"Position","name":"leftmostPosition","type":"uint128"},{"internalType":"address","name":"counteredBy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"resolve","outputs":[{"internalType":"enum GameStatus","name":"status_","type":"uint8"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_claimIndex","type":"uint256"},{"internalType":"uint256","name":"_numToResolve","type":"uint256"}],"name":"resolveClaim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resolvedAt","outputs":[{"internalType":"Timestamp","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"resolvedSubgames","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rootClaim","outputs":[{"internalType":"Claim","name":"rootClaim_","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"splitDepth","outputs":[{"internalType":"uint256","name":"splitDepth_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"startingBlockNumber","outputs":[{"internalType":"uint256","name":"startingBlockNumber_","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"startingOutputRoot","outputs":[{"internalType":"Hash","name":"root","type":"bytes32"},{"internalType":"uint256","name":"l2BlockNumber","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"startingRootHash","outputs":[{"internalType":"Hash","name":"startingRootHash_","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"status","outputs":[{"internalType":"enum GameStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_claimIndex","type":"uint256"},{"internalType":"bool","name":"_isAttack","type":"bool"},{"internalType":"bytes","name":"_stateData","type":"bytes"},{"internalType":"bytes","name":"_proof","type":"bytes"}],"name":"step","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"subgames","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vm","outputs":[{"internalType":"contract IBigStepper","name":"vm_","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"weth","outputs":[{"internalType":"contract IDelayedWETH","name":"weth_","type":"address"}],"stateMutability":"view","type":"function"}]
Deployed Bytecode
0x6080604052600436106103085760003560e01c806370872aa51161019a578063c6f0308c116100e1578063ec5e63081161008a578063fa24f74311610064578063fa24f74314610b94578063fa315aa914610bb8578063fe2bbeb214610beb57600080fd5b8063ec5e630814610b11578063eff0f59214610b44578063f8f43ff614610b7457600080fd5b8063d6ae3cd5116100bb578063d6ae3cd514610a8b578063d8cc1a3c14610abe578063dabd396d14610ade57600080fd5b8063c6f0308c146109b3578063cf09e0d014610a3d578063d5d44d8014610a5e57600080fd5b8063a445ece611610143578063bcef3b551161011d578063bcef3b5514610933578063bd8da95614610973578063c395e1ca1461099357600080fd5b8063a445ece6146107f3578063a8e4fb90146108bf578063bbdc02db146108f257600080fd5b80638980e0cc116101745780638980e0cc1461076b5780638b85902b146107805780638d450a95146107c057600080fd5b806370872aa51461073b5780637b0f0adc146107505780638129fc1c1461076357600080fd5b80633fc8cef31161025e5780635c0cba33116102075780636361506d116101e15780636361506d146106b55780636b6716c0146106f55780636f0344091461072857600080fd5b80635c0cba331461064d578063609d33341461068057806360e274641461069557600080fd5b806354fd4d501161023857806354fd4d50146105a757806357da950e146105fd5780635a5fa2d91461062d57600080fd5b80633fc8cef31461052e578063472777c614610561578063534db0e21461057457600080fd5b80632810e1d6116102c057806337b1b2291161029a57806337b1b2291461047b5780633a768463146104bb5780633e3ac912146104ee57600080fd5b80632810e1d6146103f45780632ad69aeb1461040957806330dbe5701461042957600080fd5b806319effeb4116102f157806319effeb41461034f578063200d2ed21461039a57806325fc2ace146103d557600080fd5b8063019351301461030d57806303c2924d1461032f575b600080fd5b34801561031957600080fd5b5061032d6103283660046155a8565b610c1b565b005b34801561033b57600080fd5b5061032d61034a366004615603565b610f3c565b34801561035b57600080fd5b5060005461037c9068010000000000000000900467ffffffffffffffff1681565b60405167ffffffffffffffff90911681526020015b60405180910390f35b3480156103a657600080fd5b506000546103c890700100000000000000000000000000000000900460ff1681565b6040516103919190615654565b3480156103e157600080fd5b506008545b604051908152602001610391565b34801561040057600080fd5b506103c86115e2565b34801561041557600080fd5b506103e6610424366004615603565b611887565b34801561043557600080fd5b506001546104569073ffffffffffffffffffffffffffffffffffffffff1681565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610391565b34801561048757600080fd5b50367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90033560601c610456565b3480156104c757600080fd5b507f000000000000000000000000e43266085af74d9b247849989d7b861f3102f36a610456565b3480156104fa57600080fd5b5060005461051e907201000000000000000000000000000000000000900460ff1681565b6040519015158152602001610391565b34801561053a57600080fd5b507f0000000000000000000000005222ea384870b43cd82e565271f7d3517cb023b7610456565b61032d61056f366004615695565b6118bd565b34801561058057600080fd5b507f0000000000000000000000008379214180ccc124371ad6afc1b9d1845de85808610456565b3480156105b357600080fd5b506105f06040518060400160405280600581526020017f312e322e3000000000000000000000000000000000000000000000000000000081525081565b604051610391919061572c565b34801561060957600080fd5b50600854600954610618919082565b60408051928352602083019190915201610391565b34801561063957600080fd5b506103e661064836600461573f565b6118cf565b34801561065957600080fd5b507f0000000000000000000000000d6b654a2f455c5abda5830e7c323ee66d1b2dc8610456565b34801561068c57600080fd5b506105f0611909565b3480156106a157600080fd5b5061032d6106b036600461577d565b611917565b3480156106c157600080fd5b50367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c9003603401356103e6565b34801561070157600080fd5b507f000000000000000000000000000000000000000000000000000000000000000061037c565b61032d6107363660046157af565b611abe565b34801561074757600080fd5b506009546103e6565b61032d61075e366004615695565b611b7f565b61032d611b8c565b34801561077757600080fd5b506002546103e6565b34801561078c57600080fd5b50367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c9003605401356103e6565b3480156107cc57600080fd5b507f03c7ae758795765c6664a5d39bf63841c71ff191e9189522bad8ebff5d4eca986103e6565b3480156107ff57600080fd5b5061086b61080e36600461573f565b6007602052600090815260409020805460019091015460ff821691610100810463ffffffff1691650100000000009091046fffffffffffffffffffffffffffffffff169073ffffffffffffffffffffffffffffffffffffffff1684565b60408051941515855263ffffffff90931660208501526fffffffffffffffffffffffffffffffff9091169183019190915273ffffffffffffffffffffffffffffffffffffffff166060820152608001610391565b3480156108cb57600080fd5b507f0000000000000000000000009457644abc44eefafd7756850d50cc6453d7a764610456565b3480156108fe57600080fd5b5060405163ffffffff7f0000000000000000000000000000000000000000000000000000000000000001168152602001610391565b34801561093f57600080fd5b50367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c9003601401356103e6565b34801561097f57600080fd5b5061037c61098e36600461573f565b611c05565b34801561099f57600080fd5b506103e66109ae3660046157ee565b611de4565b3480156109bf57600080fd5b506109d36109ce36600461573f565b611fc7565b6040805163ffffffff909816885273ffffffffffffffffffffffffffffffffffffffff968716602089015295909416948601949094526fffffffffffffffffffffffffffffffff9182166060860152608085015291821660a08401521660c082015260e001610391565b348015610a4957600080fd5b5060005461037c9067ffffffffffffffff1681565b348015610a6a57600080fd5b506103e6610a7936600461577d565b60036020526000908152604090205481565b348015610a9757600080fd5b507f000000000000000000000000000000000000000000000000000000000000a83d6103e6565b348015610aca57600080fd5b5061032d610ad9366004615820565b61205e565b348015610aea57600080fd5b507f000000000000000000000000000000000000000000000000000000000000025861037c565b348015610b1d57600080fd5b507f000000000000000000000000000000000000000000000000000000000000000e6103e6565b348015610b5057600080fd5b5061051e610b5f36600461573f565b60046020526000908152604090205460ff1681565b348015610b8057600080fd5b5061032d610b8f366004615695565b612123565b348015610ba057600080fd5b50610ba9612575565b604051610391939291906158aa565b348015610bc457600080fd5b507f000000000000000000000000000000000000000000000000000000000000002c6103e6565b348015610bf757600080fd5b5061051e610c0636600461573f565b60066020526000908152604090205460ff1681565b60008054700100000000000000000000000000000000900460ff166002811115610c4757610c47615625565b14610c7e576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000547201000000000000000000000000000000000000900460ff1615610cd1576040517f0ea2e75200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610d08367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90036014013590565b90565b610d1f610d1a368690038601866158fe565b6125d5565b14610d56576040517f9cc00b5b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b82606001358282604051610d6b92919061598b565b604051809103902014610daa576040517fd81d583b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000610df3610dee84848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061263192505050565b61269e565b90506000610e1a82600881518110610e0d57610e0d61599b565b6020026020010151612854565b9050602081511115610e58576040517fd81d583b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b602081810151825190910360031b1c367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c9003605401358103610ecd576040517fb8ed883000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050600180547fffffffffffffffffffffffff000000000000000000000000000000000000000016331790555050600080547fffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffff1672010000000000000000000000000000000000001790555050565b60008054700100000000000000000000000000000000900460ff166002811115610f6857610f68615625565b14610f9f576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060028381548110610fb457610fb461599b565b906000526020600020906005020190506000610fcf84611c05565b905067ffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000025881169082161015611038576040517ff2440b5300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008481526006602052604090205460ff1615611081576040517ff1a9458100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600084815260056020526040902080548015801561109e57508515155b15611139578354640100000000900473ffffffffffffffffffffffffffffffffffffffff16600081156110d157816110ed565b600186015473ffffffffffffffffffffffffffffffffffffffff165b90506110f98187612908565b50505060009485525050600660205250506040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00166001179055565b6000868152600760209081526040918290208251608081018452815460ff81161515808352610100820463ffffffff16948301949094526501000000000090046fffffffffffffffffffffffffffffffff16938101939093526001015473ffffffffffffffffffffffffffffffffffffffff1660608301526111dc576fffffffffffffffffffffffffffffffff60408201526001815260008690036111dc578195505b600086826020015163ffffffff166111f491906159f9565b905060008382116112055781611207565b835b602084015190915063ffffffff165b818110156113535760008682815481106112325761123261599b565b6000918252602080832090910154808352600690915260409091205490915060ff1661128a576040517f9a07664600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006002828154811061129f5761129f61599b565b600091825260209091206005909102018054909150640100000000900473ffffffffffffffffffffffffffffffffffffffff161580156112fc5750600481015460408701516fffffffffffffffffffffffffffffffff9182169116115b1561133e57600181015473ffffffffffffffffffffffffffffffffffffffff16606087015260048101546fffffffffffffffffffffffffffffffff1660408701525b5050808061134b90615a11565b915050611216565b5063ffffffff818116602085810191825260008c81526007909152604090819020865181549351928801517fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000009094169015157fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000ff161761010092909416918202939093177fffffffffffffffffffffff00000000000000000000000000000000ffffffffff16650100000000006fffffffffffffffffffffffffffffffff909316929092029190911782556060850151600190920180547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff909316929092179091558490036115d757606083015160008a815260066020526040902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00166001179055891580156114d357506000547201000000000000000000000000000000000000900460ff165b156115485760015473ffffffffffffffffffffffffffffffffffffffff166114fb818a612908565b885473ffffffffffffffffffffffffffffffffffffffff909116640100000000027fffffffffffffffff0000000000000000000000000000000000000000ffffffff9091161788556115d5565b61158f73ffffffffffffffffffffffffffffffffffffffff82161561156d5781611589565b600189015473ffffffffffffffffffffffffffffffffffffffff165b89612908565b87547fffffffffffffffff0000000000000000000000000000000000000000ffffffff1664010000000073ffffffffffffffffffffffffffffffffffffffff8316021788555b505b505050505050505050565b600080600054700100000000000000000000000000000000900460ff16600281111561161057611610615625565b14611647576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000805260066020527f54cdd369e4e8a8515e52ca72ec816c2101831ad1f18bf44102ed171459c9b4f85460ff166116ab576040517f9a07664600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff1660026000815481106116d7576116d761599b565b6000918252602090912060059091020154640100000000900473ffffffffffffffffffffffffffffffffffffffff1614611712576001611715565b60025b6000805467ffffffffffffffff421668010000000000000000027fffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff82168117835592935083927fffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffff167fffffffffffffffffffffffffffffff000000000000000000ffffffffffffffff909116177001000000000000000000000000000000008360028111156117c6576117c6615625565b0217905560028111156117db576117db615625565b6040517f5e186f09b9c93491f14e277eea7faa5de6a2d4bda75a79af7a3684fbfb42da6090600090a27f0000000000000000000000000d6b654a2f455c5abda5830e7c323ee66d1b2dc873ffffffffffffffffffffffffffffffffffffffff1663838c2d1e6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561186c57600080fd5b505af1158015611880573d6000803e3d6000fd5b5050505090565b600560205281600052604060002081815481106118a357600080fd5b90600052602060002001600091509150505481565b905090565b6118ca8383836001611abe565b505050565b6000818152600760209081526040808320600590925282208054825461190090610100900463ffffffff1682615a49565b95945050505050565b60606118b860546020612a09565b73ffffffffffffffffffffffffffffffffffffffff811660009081526003602052604081208054908290559081900361197c576040517f17bfe5f700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517ff3fef3a300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8381166004830152602482018390527f0000000000000000000000005222ea384870b43cd82e565271f7d3517cb023b7169063f3fef3a390604401600060405180830381600087803b158015611a0c57600080fd5b505af1158015611a20573d6000803e3d6000fd5b5050505060008273ffffffffffffffffffffffffffffffffffffffff168260405160006040518083038185875af1925050503d8060008114611a7e576040519150601f19603f3d011682016040523d82523d6000602084013e611a83565b606091505b50509050806118ca576040517f83e6cc6b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009457644abc44eefafd7756850d50cc6453d7a764161480611b3757503373ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000008379214180ccc124371ad6afc1b9d1845de8580816145b611b6d576040517fd386ef3e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611b7984848484612a5b565b50505050565b6118ca8383836000611abe565b3273ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009457644abc44eefafd7756850d50cc6453d7a7641614611bfb576040517fd386ef3e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611c036133fc565b565b600080600054700100000000000000000000000000000000900460ff166002811115611c3357611c33615625565b14611c6a576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060028381548110611c7f57611c7f61599b565b600091825260208220600590910201805490925063ffffffff90811614611cee57815460028054909163ffffffff16908110611cbd57611cbd61599b565b906000526020600020906005020160040160109054906101000a90046fffffffffffffffffffffffffffffffff1690505b6004820154600090611d2690700100000000000000000000000000000000900467ffffffffffffffff165b67ffffffffffffffff1690565b611d3a9067ffffffffffffffff1642615a49565b611d59611d19846fffffffffffffffffffffffffffffffff1660401c90565b67ffffffffffffffff16611d6d91906159f9565b905067ffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000002581667ffffffffffffffff168167ffffffffffffffff1611611dba5780611900565b7f000000000000000000000000000000000000000000000000000000000000025895945050505050565b600080611e83836fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff1690507f000000000000000000000000000000000000000000000000000000000000002c811115611ee2576040517f56f57b2b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b642e90edd00062061a806311e1a3006000611efd8383615a8f565b9050670de0b6b3a76400006000611f34827f000000000000000000000000000000000000000000000000000000000000002c615aa3565b90506000611f52611f4d670de0b6b3a764000086615aa3565b613955565b90506000611f608484613bb0565b90506000611f6e8383613bff565b90506000611f7b82613c2d565b90506000611f9a82611f95670de0b6b3a76400008f615aa3565b613e15565b90506000611fa88b83613bff565b9050611fb4818d615aa3565b9f9e505050505050505050505050505050565b60028181548110611fd757600080fd5b60009182526020909120600590910201805460018201546002830154600384015460049094015463ffffffff8416955064010000000090930473ffffffffffffffffffffffffffffffffffffffff908116949216926fffffffffffffffffffffffffffffffff91821692918082169170010000000000000000000000000000000090041687565b3373ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009457644abc44eefafd7756850d50cc6453d7a7641614806120d757503373ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000008379214180ccc124371ad6afc1b9d1845de8580816145b61210d576040517fd386ef3e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61211b868686868686613e4f565b505050505050565b60008054700100000000000000000000000000000000900460ff16600281111561214f5761214f615625565b14612186576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000806000806121958661447e565b935093509350935060006121ab85858585614887565b905060007f000000000000000000000000e43266085af74d9b247849989d7b861f3102f36a73ffffffffffffffffffffffffffffffffffffffff16637dc0d1d06040518163ffffffff1660e01b8152600401602060405180830381865afa15801561221a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061223e9190615ae0565b9050600189036123365773ffffffffffffffffffffffffffffffffffffffff81166352f0f3ad8a8461229a367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90036034013590565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e086901b16815260048101939093526024830191909152604482015260206064820152608481018a905260a4015b6020604051808303816000875af115801561230c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123309190615afd565b506115d7565b600289036123625773ffffffffffffffffffffffffffffffffffffffff81166352f0f3ad8a848961229a565b6003890361238e5773ffffffffffffffffffffffffffffffffffffffff81166352f0f3ad8a848761229a565b600489036124aa5760006123d46fffffffffffffffffffffffffffffffff85167f000000000000000000000000000000000000000000000000000000000000000e614941565b6009546123e191906159f9565b6123ec9060016159f9565b905073ffffffffffffffffffffffffffffffffffffffff82166352f0f3ad8b8560405160e084901b7fffffffff000000000000000000000000000000000000000000000000000000001681526004810192909252602482015260c084901b604482015260086064820152608481018b905260a4016020604051808303816000875af115801561247f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a39190615afd565b50506115d7565b60058903612543576040517f52f0f3ad000000000000000000000000000000000000000000000000000000008152600481018a9052602481018390527f000000000000000000000000000000000000000000000000000000000000a83d60c01b6044820152600860648201526084810188905273ffffffffffffffffffffffffffffffffffffffff8216906352f0f3ad9060a4016122ed565b6040517fff137e6500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000000000000000001367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90036014013560606125ce611909565b9050909192565b60008160000151826020015183604001518460600151604051602001612614949392919093845260208401929092526040830152606082015260800190565b604051602081830303815290604052805190602001209050919050565b60408051808201909152600080825260208201528151600003612680576040517f5ab458fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50604080518082019091528151815260209182019181019190915290565b606060008060006126ae856149ef565b9194509250905060018160018111156126c9576126c9615625565b14612700576040517f4b9c6abe00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b845161270c83856159f9565b14612743576040517f5c5537b800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604080516020808252610420820190925290816020015b604080518082019091526000808252602082015281526020019060019003908161275a5790505093506000835b8651811015612848576000806127cd6040518060400160405280858c600001516127b19190615a49565b8152602001858c602001516127c691906159f9565b90526149ef565b5091509150604051806040016040528083836127e991906159f9565b8152602001848b602001516127fe91906159f9565b8152508885815181106128135761281361599b565b60209081029190910101526128296001856159f9565b935061283581836159f9565b61283f90846159f9565b92505050612787565b50845250919392505050565b60606000806000612864856149ef565b91945092509050600081600181111561287f5761287f615625565b146128b6576040517f1ff9b2e400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6128c082846159f9565b8551146128f9576040517f5c5537b800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61190085602001518484614e8d565b600281015473ffffffffffffffffffffffffffffffffffffffff8316600090815260036020526040812080546fffffffffffffffffffffffffffffffff909316928392906129579084906159f9565b90915550506040517f7eee288d00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8481166004830152602482018390527f0000000000000000000000005222ea384870b43cd82e565271f7d3517cb023b71690637eee288d90604401600060405180830381600087803b1580156129ec57600080fd5b505af1158015612a00573d6000803e3d6000fd5b50505050505050565b604051818152367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90038284820160208401378260208301016000815260208101604052505092915050565b60008054700100000000000000000000000000000000900460ff166002811115612a8757612a87615625565b14612abe576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060028481548110612ad357612ad361599b565b60009182526020918290206040805160e0810182526005909302909101805463ffffffff8116845273ffffffffffffffffffffffffffffffffffffffff64010000000090910481169484019490945260018101549093169082015260028201546fffffffffffffffffffffffffffffffff908116606083015260038301546080830181905260049093015480821660a084015270010000000000000000000000000000000090041660c082015291508514612bba576040517f3014033200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60a0810151600083156fffffffffffffffffffffffffffffffff83161760011b90506000612c7a826fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff169050861580612cb55750612cb27f000000000000000000000000000000000000000000000000000000000000000e60026159f9565b81145b8015612cbf575084155b15612cf6576040517fa42637bc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000547201000000000000000000000000000000000000900460ff168015612d1c575086155b15612d53576040517f0ea2e75200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000002c811115612dad576040517f56f57b2b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612dd87f000000000000000000000000000000000000000000000000000000000000000e60016159f9565b8103612dea57612dea86888588614f22565b34612df483611de4565b14612e2b576040517f8620aa1900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000612e3688611c05565b905067ffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000258811690821603612e9e576040517f3381d11400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b67ffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001667ffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000025816612efe9190615b16565b67ffffffffffffffff16612f198267ffffffffffffffff1690565b67ffffffffffffffff161115612ffb576000612f5660017f000000000000000000000000000000000000000000000000000000000000000e615a49565b8314612f8c5767ffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016612fc1565b612fc17f000000000000000000000000000000000000000000000000000000000000000067ffffffffffffffff166002615b3f565b9050612ff7817f000000000000000000000000000000000000000000000000000000000000025867ffffffffffffffff16615b16565b9150505b6000604082901b42176000898152608086901b6fffffffffffffffffffffffffffffffff8c1617602052604081209192509060008181526004602052604090205490915060ff1615613079576040517f80497e3b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60016004600083815260200190815260200160002060006101000a81548160ff02191690831515021790555060026040518060e001604052808c63ffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020013373ffffffffffffffffffffffffffffffffffffffff168152602001346fffffffffffffffffffffffffffffffff1681526020018b8152602001876fffffffffffffffffffffffffffffffff168152602001846fffffffffffffffffffffffffffffffff16815250908060018154018082558091505060019003906000526020600020906005020160009091909190915060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060608201518160020160006101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055506080820151816003015560a08201518160040160006101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff16021790555060c08201518160040160106101000a8154816fffffffffffffffffffffffffffffffff02191690836fffffffffffffffffffffffffffffffff1602179055505050600560008b8152602001908152602001600020600160028054905061330f9190615a49565b81546001810183556000928352602083200155604080517fd0e30db0000000000000000000000000000000000000000000000000000000008152905173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000005222ea384870b43cd82e565271f7d3517cb023b7169263d0e30db09234926004808301939282900301818588803b1580156133a757600080fd5b505af11580156133bb573d6000803e3d6000fd5b50506040513393508c92508d91507f9b3245740ec3b155098a55be84957a4da13eaf7f14a8bc6f53126c0b9350f2be90600090a45050505050505050505050565b60005471010000000000000000000000000000000000900460ff161561344e576040517f0dc149f000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040517f7258a80700000000000000000000000000000000000000000000000000000000815263ffffffff7f0000000000000000000000000000000000000000000000000000000000000001166004820152600090819073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000d6b654a2f455c5abda5830e7c323ee66d1b2dc81690637258a807906024016040805180830381865afa158015613502573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135269190615b6f565b909250905081613562576040517f6a6bc3b200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604080518082019091528281526020018190526008829055600981905536607a1461359557639824bdab6000526004601cfd5b80367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c9003605401351161362f576040517ff40239db000000000000000000000000000000000000000000000000000000008152367ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81013560f01c90036014013560048201526024015b60405180910390fd5b6040805160e08101825263ffffffff8082526000602083018181527ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe369081013560f01c90038035606090811c868801908152346fffffffffffffffffffffffffffffffff81811693890193845260149094013560808901908152600160a08a0181815242871660c08c019081526002805493840181558a529a5160059092027f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace81018054995173ffffffffffffffffffffffffffffffffffffffff908116640100000000027fffffffffffffffff000000000000000000000000000000000000000000000000909b1694909c16939093179890981790915592517f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5acf87018054918a167fffffffffffffffffffffffff000000000000000000000000000000000000000090921691909117905592517f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ad0860180549186167fffffffffffffffffffffffffffffffff0000000000000000000000000000000090921691909117905591517f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ad185015551955182167001000000000000000000000000000000000295909116949094177f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ad29091015580547fffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffffff167101000000000000000000000000000000000017815583517fd0e30db000000000000000000000000000000000000000000000000000000000815293517f0000000000000000000000005222ea384870b43cd82e565271f7d3517cb023b79092169363d0e30db093926004828101939282900301818588803b15801561390457600080fd5b505af1158015613918573d6000803e3d6000fd5b5050600080547fffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000164267ffffffffffffffff161790555050505050565b6fffffffffffffffffffffffffffffffff811160071b81811c67ffffffffffffffff1060061b1781811c63ffffffff1060051b1781811c61ffff1060041b1781811c60ff1060031b17600082136139b457631615e6386000526004601cfd5b7ff8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff6f8421084210842108cc6318c6db6d54be83831c1c601f161a1890811b609f90811c6c465772b2bbbb5f824b15207a3081018102606090811d6d0388eaa27412d5aca026815d636e018202811d6d0df99ac502031bf953eff472fdcc018202811d6d13cdffb29d51d99322bdff5f2211018202811d6d0a0f742023def783a307a986912e018202811d6d01920d8043ca89b5239253284e42018202811d6c0b7a86d7375468fac667a0a527016c29508e458543d8aa4df2abee7883018302821d6d0139601a2efabe717e604cbb4894018302821d6d02247f7a7b6594320649aa03aba1018302821d7fffffffffffffffffffffffffffffffffffffff73c0c716a594e00d54e3c4cbc9018302821d7ffffffffffffffffffffffffffffffffffffffdc7b88c420e53a9890533129f6f01830290911d7fffffffffffffffffffffffffffffffffffffff465fda27eb4d63ded474e5f832019091027ffffffffffffffff5f6af8f7b3396644f18e157960000000000000000000000000105711340daa0d5f769dba1915cef59f0815a5506029190037d0267a36c0c95b3975ab3ee5b203a7614a3f75373f047d803ae7b6687f2b302017d57115e47018c7177eebf7cd370a3356a1b7863008a5ae8028c72b88642840160ae1d90565b60007812725dd1d243aba0e75fe645cc4873f9e65afe688c928e1f218311670de0b6b3a764000002158202613bed57637c5f487d6000526004601cfd5b50670de0b6b3a7640000919091020490565b600081600019048311820215613c1d5763bac65e5b6000526004601cfd5b50670de0b6b3a764000091020490565b60007ffffffffffffffffffffffffffffffffffffffffffffffffdc0d0570925a462d78213613c5b57919050565b680755bf798b4a1bf1e58212613c795763a37bfec96000526004601cfd5b6503782dace9d9604e83901b059150600060606bb17217f7d1cf79abc9e3b39884821b056b80000000000000000000000001901d6bb17217f7d1cf79abc9e3b39881029093037fffffffffffffffffffffffffffffffffffffffdbf3ccf1604d263450f02a550481018102606090811d6d0277594991cfc85f6e2461837cd9018202811d7fffffffffffffffffffffffffffffffffffffe5adedaa1cb095af9e4da10e363c018202811d6db1bbb201f443cf962f1a1d3db4a5018202811d7ffffffffffffffffffffffffffffffffffffd38dc772608b0ae56cce01296c0eb018202811d6e05180bb14799ab47a8a8cb2a527d57016d02d16720577bd19bf614176fe9ea6c10fe68e7fd37d0007b713f765084018402831d9081019084017ffffffffffffffffffffffffffffffffffffffe2c69812cf03b0763fd454a8f7e010290911d6e0587f503bb6ea29d25fcb7401964500190910279d835ebba824c98fb31b83b2ca45c000000000000000000000000010574029d9dc38563c32e5c2f6dc192ee70ef65f9978af30260c3939093039290921c92915050565b6000613e46670de0b6b3a764000083613e2d86613955565b613e379190615b93565b613e419190615c4f565b613c2d565b90505b92915050565b60008054700100000000000000000000000000000000900460ff166002811115613e7b57613e7b615625565b14613eb2576040517f67fe195000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060028781548110613ec757613ec761599b565b6000918252602082206005919091020160048101549092506fffffffffffffffffffffffffffffffff16908715821760011b9050613f267f000000000000000000000000000000000000000000000000000000000000002c60016159f9565b613fc2826fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff1614613ffc576040517f5f53dd9800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008089156140f35761404f7f000000000000000000000000000000000000000000000000000000000000000e7f000000000000000000000000000000000000000000000000000000000000002c615a49565b6001901b61406e846fffffffffffffffffffffffffffffffff166150d3565b6fffffffffffffffffffffffffffffffff1661408a9190615cb7565b156140c7576140be6140af60016fffffffffffffffffffffffffffffffff8716615ccb565b865463ffffffff166000615172565b600301546140e9565b7f03c7ae758795765c6664a5d39bf63841c71ff191e9189522bad8ebff5d4eca985b915084905061411d565b6003850154915061411a6140af6fffffffffffffffffffffffffffffffff86166001615cf4565b90505b600882901b60088a8a60405161413492919061598b565b6040518091039020901b14614175576040517f696550ff00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006141808c615256565b9050600061418f836003015490565b6040517fe14ced320000000000000000000000000000000000000000000000000000000081527f000000000000000000000000e43266085af74d9b247849989d7b861f3102f36a73ffffffffffffffffffffffffffffffffffffffff169063e14ced3290614209908f908f908f908f908a90600401615d71565b6020604051808303816000875af1158015614228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061424c9190615afd565b6004850154911491506000906002906142f7906fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b614393896fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b61439d9190615dab565b6143a79190615dce565b60ff1615905081151581036143e8576040517ffb4e40dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8754640100000000900473ffffffffffffffffffffffffffffffffffffffff161561443f576040517f9071e6af00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b505085547fffffffffffffffff0000000000000000000000000000000000000000ffffffff163364010000000002179095555050505050505050505050565b600080600080600085905060006002828154811061449e5761449e61599b565b600091825260209091206004600590920201908101549091507f000000000000000000000000000000000000000000000000000000000000000e90614575906fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff16116145af576040517fb34b5c2200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000815b60048301547f000000000000000000000000000000000000000000000000000000000000000e90614676906fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff1692508211156146eb57825463ffffffff166146b57f000000000000000000000000000000000000000000000000000000000000000e60016159f9565b83036146bf578391505b600281815481106146d2576146d261599b565b90600052602060002090600502019350809450506145b3565b600481810154908401546fffffffffffffffffffffffffffffffff91821691166000816fffffffffffffffffffffffffffffffff1661475461473f856fffffffffffffffffffffffffffffffff1660011c90565b6fffffffffffffffffffffffffffffffff1690565b6fffffffffffffffffffffffffffffffff16149050801561482357600061478c836fffffffffffffffffffffffffffffffff166150d3565b6fffffffffffffffffffffffffffffffff1611156147f75760006147ce6147c660016fffffffffffffffffffffffffffffffff8616615ccb565b896001615172565b6003810154600490910154909c506fffffffffffffffffffffffffffffffff169a506147fd9050565b6008549a505b600386015460048701549099506fffffffffffffffffffffffffffffffff169750614879565b60006148456147c66fffffffffffffffffffffffffffffffff85166001615cf4565b6003808901546004808b015492840154930154909e506fffffffffffffffffffffffffffffffff9182169d50919b50169850505b505050505050509193509193565b60006fffffffffffffffffffffffffffffffff8416156148f45760408051602081018790526fffffffffffffffffffffffffffffffff8087169282019290925260608101859052908316608082015260a00160405160208183030381529060405280519060200120611900565b82826040516020016149229291909182526fffffffffffffffffffffffffffffffff16602082015260400190565b6040516020818303038152906040528051906020012095945050505050565b6000806149ce847e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff1690508083036001841b600180831b0386831b17039250505092915050565b60008060008360000151600003614a32576040517f5ab458fb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6020840151805160001a607f8111614a57576000600160009450945094505050614e86565b60b78111614b6d576000614a6c608083615a49565b905080876000015111614aab576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001838101517fff00000000000000000000000000000000000000000000000000000000000000169082148015614b2357507f80000000000000000000000000000000000000000000000000000000000000007fff000000000000000000000000000000000000000000000000000000000000008216105b15614b5a576040517fbabb01dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5060019550935060009250614e86915050565b60bf8111614ccb576000614b8260b783615a49565b905080876000015111614bc1576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60018301517fff00000000000000000000000000000000000000000000000000000000000000166000819003614c23576040517fbabb01dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600184015160088302610100031c60378111614c6b576040517fbabb01dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b614c7581846159f9565b895111614cae576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b614cb98360016159f9565b9750955060009450614e869350505050565b60f78111614d30576000614ce060c083615a49565b905080876000015111614d1f576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600195509350849250614e86915050565b6000614d3d60f783615a49565b905080876000015111614d7c576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60018301517fff00000000000000000000000000000000000000000000000000000000000000166000819003614dde576040517fbabb01dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600184015160088302610100031c60378111614e26576040517fbabb01dd00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b614e3081846159f9565b895111614e69576040517f66c9448500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b614e748360016159f9565b9750955060019450614e869350505050565b9193909250565b60608167ffffffffffffffff811115614ea857614ea86158cf565b6040519080825280601f01601f191660200182016040528015614ed2576020820181803683370190505b5090508115614f1b576000614ee784866159f9565b90506020820160005b84811015614f08578281015182820152602001614ef0565b84811115614f17576000858301525b5050505b9392505050565b6000614f416fffffffffffffffffffffffffffffffff84166001615cf4565b90506000614f5182866001615172565b9050600086901a838061503d5750614f8a60027f000000000000000000000000000000000000000000000000000000000000000e615cb7565b600483015460029061502e906fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b6150389190615dce565b60ff16145b156150955760ff811660011480615057575060ff81166002145b615090576040517ff40239db00000000000000000000000000000000000000000000000000000000815260048101889052602401613626565b612a00565b60ff811615612a00576040517ff40239db00000000000000000000000000000000000000000000000000000000815260048101889052602401613626565b600080615160837e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b600160ff919091161b90920392915050565b600080826151bb576151b66fffffffffffffffffffffffffffffffff86167f000000000000000000000000000000000000000000000000000000000000000e615285565b6151d6565b6151d6856fffffffffffffffffffffffffffffffff16615411565b9050600284815481106151eb576151eb61599b565b906000526020600020906005020191505b60048201546fffffffffffffffffffffffffffffffff82811691161461524e57815460028054909163ffffffff169081106152395761523961599b565b906000526020600020906005020191506151fc565b509392505050565b60008060008060006152678661447e565b935093509350935061527b84848484614887565b9695505050505050565b600081615324846fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff161161533a5763b34b5c226000526004601cfd5b61534383615411565b9050816153e2826fffffffffffffffffffffffffffffffff167e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff1611613e4957613e466153f88360016159f9565b6fffffffffffffffffffffffffffffffff8316906154b6565b600081196001830116816154a5827e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff169390931c8015179392505050565b600080615543847e09010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f7f07c4acdd0000000000000000000000000000000000000000000000000000000067ffffffffffffffff831160061b83811c63ffffffff1060051b1792831c600181901c17600281901c17600481901c17600881901c17601081901c170260fb1c1a1790565b60ff169050808303600180821b0385821b179250505092915050565b60008083601f84011261557157600080fd5b50813567ffffffffffffffff81111561558957600080fd5b6020830191508360208285010111156155a157600080fd5b9250929050565b600080600083850360a08112156155be57600080fd5b60808112156155cc57600080fd5b50839250608084013567ffffffffffffffff8111156155ea57600080fd5b6155f68682870161555f565b9497909650939450505050565b6000806040838503121561561657600080fd5b50508035926020909101359150565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b602081016003831061568f577f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b91905290565b6000806000606084860312156156aa57600080fd5b505081359360208301359350604090920135919050565b6000815180845260005b818110156156e7576020818501810151868301820152016156cb565b818111156156f9576000602083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b602081526000613e4660208301846156c1565b60006020828403121561575157600080fd5b5035919050565b73ffffffffffffffffffffffffffffffffffffffff8116811461577a57600080fd5b50565b60006020828403121561578f57600080fd5b8135614f1b81615758565b803580151581146157aa57600080fd5b919050565b600080600080608085870312156157c557600080fd5b8435935060208501359250604085013591506157e36060860161579a565b905092959194509250565b60006020828403121561580057600080fd5b81356fffffffffffffffffffffffffffffffff81168114614f1b57600080fd5b6000806000806000806080878903121561583957600080fd5b863595506158496020880161579a565b9450604087013567ffffffffffffffff8082111561586657600080fd5b6158728a838b0161555f565b9096509450606089013591508082111561588b57600080fd5b5061589889828a0161555f565b979a9699509497509295939492505050565b63ffffffff8416815282602082015260606040820152600061190060608301846156c1565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b60006080828403121561591057600080fd5b6040516080810181811067ffffffffffffffff8211171561595a577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b8060405250823581526020830135602082015260408301356040820152606083013560608201528091505092915050565b8183823760009101908152919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60008219821115615a0c57615a0c6159ca565b500190565b60007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203615a4257615a426159ca565b5060010190565b600082821015615a5b57615a5b6159ca565b500390565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082615a9e57615a9e615a60565b500490565b6000817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0483118215151615615adb57615adb6159ca565b500290565b600060208284031215615af257600080fd5b8151614f1b81615758565b600060208284031215615b0f57600080fd5b5051919050565b600067ffffffffffffffff83811690831681811015615b3757615b376159ca565b039392505050565b600067ffffffffffffffff80831681851681830481118215151615615b6657615b666159ca565b02949350505050565b60008060408385031215615b8257600080fd5b505080516020909101519092909150565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600084136000841385830485118282161615615bd457615bd46159ca565b7f80000000000000000000000000000000000000000000000000000000000000006000871286820588128184161615615c0f57615c0f6159ca565b60008712925087820587128484161615615c2b57615c2b6159ca565b87850587128184161615615c4157615c416159ca565b505050929093029392505050565b600082615c5e57615c5e615a60565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83147f800000000000000000000000000000000000000000000000000000000000000083141615615cb257615cb26159ca565b500590565b600082615cc657615cc6615a60565b500690565b60006fffffffffffffffffffffffffffffffff83811690831681811015615b3757615b376159ca565b60006fffffffffffffffffffffffffffffffff808316818516808303821115615d1f57615d1f6159ca565b01949350505050565b8183528181602085013750600060208284010152600060207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b606081526000615d85606083018789615d28565b8281036020840152615d98818688615d28565b9150508260408301529695505050505050565b600060ff821660ff841680821015615dc557615dc56159ca565b90039392505050565b600060ff831680615de157615de1615a60565b8060ff8416069150509291505056fea164736f6c634300080f000a
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.