Verified contractPartialMIT
AggregateVerifier
Address0xc08b8ffaf04abb1d7013b74a0e57eccbd7fa5a70
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.15
- Same code
Only this contract
Details
- Compiler
- solc 0.8.15+commit.e14f2714
- Language
- solidity
- Optimization
- Yes, 999,999 runs
- EVM version
- london
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,285,895
- Creation transaction
- 0xc2f3aec472…361ca6f298
23 files
- src/L1/proofs/AggregateVerifier.solmain56.31 KB
- interfaces/L1/IProtocolVersions.sol2.96 KB
- interfaces/L1/IProxyAdminOwnedBase.sol620 B
- interfaces/L1/IResourceMetering.sol680 B
- interfaces/L1/ISuperchainConfig.sol1.38 KB
- interfaces/L1/ISystemConfig.sol5.56 KB
- interfaces/L1/proofs/IAnchorStateRegistry.sol3.13 KB
- interfaces/L1/proofs/IDelayedWETH.sol2.35 KB
- interfaces/L1/proofs/IDisputeGame.sol1.37 KB
- interfaces/L1/proofs/IDisputeGameFactory.sol3.26 KB
- interfaces/L1/proofs/IInitializable.sol209 B
- interfaces/L1/proofs/IVerifier.sol735 B
- interfaces/legacy/IAddressManager.sol521 B
- interfaces/universal/IOwnable.sol436 B
- interfaces/universal/IProxyAdmin.sol1.62 KB
- interfaces/universal/IReinitializableBase.sol323 B
- interfaces/universal/ISemver.sol519 B
- lib/solady/src/utils/Clone.sol14.61 KB
- lib/solady/src/utils/FixedPointMathLib.sol45.99 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.3 KB
- src/libraries/bridge/Errors.sol2.62 KB
- src/libraries/bridge/LibUDT.sol4.36 KB
- src/libraries/bridge/Types.sol1.1 KB
src/L1/proofs/AggregateVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
// Optimism
import {
AlreadyInitialized,
BondTransferFailed,
ClaimAlreadyResolved,
GameNotFinalized,
GameNotInProgress,
GameNotResolved,
GamePaused,
NoCreditToClaim
} from "src/libraries/bridge/Errors.sol";
import { IDelayedWETH } from "interfaces/L1/proofs/IDelayedWETH.sol";
import { IDisputeGame } from "interfaces/L1/proofs/IDisputeGame.sol";
import { IDisputeGameFactory } from "interfaces/L1/proofs/IDisputeGameFactory.sol";
import { IAnchorStateRegistry } from "interfaces/L1/proofs/IAnchorStateRegistry.sol";
import { GameStatus, GameType, Hash, Proposal } from "src/libraries/bridge/Types.sol";
import { Timestamp, Claim } from "src/libraries/bridge/LibUDT.sol";
// Solady
import { Clone } from "lib/solady/src/utils/Clone.sol";
import { FixedPointMathLib } from "lib/solady/src/utils/FixedPointMathLib.sol";
import { ReentrancyGuard } from "lib/solady/src/utils/ReentrancyGuard.sol";
import { IVerifier } from "interfaces/L1/proofs/IVerifier.sol";
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IProtocolVersions } from "interfaces/L1/IProtocolVersions.sol";
contract AggregateVerifier is Clone, ReentrancyGuard, ISemver {
////////////////////////////////////////////////////////////////
// Enums //
////////////////////////////////////////////////////////////////
/// @notice The type of proof. Can be expanded for different types of ZK proofs.
enum ProofType {
TEE,
ZK
}
/// @notice Hashes for the ZK proving programs.
struct ZkHashes {
bytes32 rangeHash;
bytes32 aggregateHash;
}
/// @notice Upgrade registry and L2 timestamp anchor used to pin proof games.
struct ScheduleConfig {
IProtocolVersions protocolVersions;
uint256 genesisBlockNumber;
uint64 genesisTimestamp;
uint64 blockTime;
}
/// @notice Proposal block intervals for each side of the block-speedup activation.
/// @dev Both pairs must yield the same intermediate root count, so the CWIA `extraData` layout
/// and `INITIALIZE_CALLDATA_SIZE` are identical on both sides of the fork.
struct IntervalConfig {
uint256 slowBlockInterval;
uint256 slowIntermediateBlockInterval;
uint256 fastBlockInterval;
uint256 fastIntermediateBlockInterval;
}
////////////////////////////////////////////////////////////////
// Constants //
////////////////////////////////////////////////////////////////
/// @notice The slow finalization delay.
uint64 public constant SLOW_FINALIZATION_DELAY = 5 days;
/// @notice The fast finalization delay.
uint64 public constant FAST_FINALIZATION_DELAY = 1 days;
/// @notice The EIP-2935 blockhash history contract address (deployed post-Pectra).
/// @dev This contract stores blockhashes for the last ~8192 blocks, extending the
/// 256-block window of the native blockhash() opcode.
address public constant EIP2935_CONTRACT = 0x0000F90827F1C53a10cb7A02335B175320002935;
/// @notice The maximum number of blocks that blockhash() can look back.
uint256 public constant BLOCKHASH_WINDOW = 256;
/// @notice The maximum number of blocks that EIP-2935 can look back (~8192).
uint256 public constant EIP2935_WINDOW = 8191;
/// @notice The minimum number of proofs required to resolve the game.
uint256 public constant PROOF_THRESHOLD = 1;
/// @notice The ProtocolVersions upgrade index at which L2 blocks switch to the fast cadence.
/// @dev This is the one place the contract is tied to a specific hardfork: index 13 is Denim,
/// which drops the L2 block time from 2s to 200ms. Everything downstream is expressed as
/// slow-vs-fast blocks, so a later cadence change is a new index and new interval pair
/// rather than new machinery.
/// @dev Index 13 is one past the end of the current Base mainnet schedule, so `getSchedule()`
/// returns a shorter array until Denim is registered. `_firstFastBlock()` treats that as
/// unscheduled, which is the same state an index-in-range zero timestamp produces.
uint256 private constant FAST_BLOCK_UPGRADE_INDEX = 13;
/// @notice The number of whole fast-cadence L2 blocks produced per second.
uint256 private constant FAST_BLOCKS_PER_SECOND = 5;
////////////////////////////////////////////////////////////////
// Immutables //
////////////////////////////////////////////////////////////////
/// @notice The anchor state registry.
IAnchorStateRegistry internal immutable ANCHOR_STATE_REGISTRY;
/// @notice The dispute game factory.
IDisputeGameFactory public immutable DISPUTE_GAME_FACTORY;
/// @notice The delayed WETH contract.
IDelayedWETH public immutable DELAYED_WETH;
/// @notice The TEE prover.
IVerifier public immutable TEE_VERIFIER;
/// @notice The hash of the TEE image.
bytes32 public immutable TEE_IMAGE_HASH;
/// @notice The ZK prover.
IVerifier public immutable ZK_VERIFIER;
/// @notice The hash of the ZK range program.
bytes32 public immutable ZK_RANGE_HASH;
/// @notice The hash of the ZK aggregate program.
bytes32 public immutable ZK_AGGREGATE_HASH;
/// @notice The hash of the rollup configuration.
bytes32 public immutable CONFIG_HASH;
/// @notice The chain ID of the L2 network this contract argues about.
uint256 public immutable L2_CHAIN_ID;
/// @notice The L2 genesis block number used as the timestamp anchor.
uint256 public immutable L2_GENESIS_BLOCK_NUMBER;
/// @notice The timestamp of the L2 genesis block.
uint64 public immutable L2_GENESIS_TIMESTAMP;
/// @notice The legacy number of seconds between consecutive L2 blocks.
uint64 public immutable L2_BLOCK_TIME;
/// @notice The block interval between each proposal, for games starting on slow blocks.
/// @dev The parent's block number + SLOW_BLOCK_INTERVAL = this proposal's block number.
uint256 public immutable SLOW_BLOCK_INTERVAL;
/// @notice The block interval for intermediate proposals, for games starting on slow blocks.
/// @dev SLOW_BLOCK_INTERVAL must be divisible by SLOW_INTERMEDIATE_BLOCK_INTERVAL.
uint256 public immutable SLOW_INTERMEDIATE_BLOCK_INTERVAL;
/// @notice The block interval between each proposal, for games starting on fast blocks.
uint256 public immutable FAST_BLOCK_INTERVAL;
/// @notice The block interval for intermediate proposals, for games starting on fast blocks.
/// @dev FAST_BLOCK_INTERVAL must be divisible by FAST_INTERMEDIATE_BLOCK_INTERVAL, and their
/// ratio must equal the slow-block one.
uint256 public immutable FAST_INTERMEDIATE_BLOCK_INTERVAL;
/// @notice The size of the initialize call data.
uint256 internal immutable INITIALIZE_CALLDATA_SIZE;
/// @notice The game type ID.
GameType internal immutable GAME_TYPE;
/// @notice The ProtocolVersions upgrade schedule contract.
IProtocolVersions public immutable PROTOCOL_VERSIONS;
////////////////////////////////////////////////////////////////
// State Vars //
////////////////////////////////////////////////////////////////
/// @notice The starting timestamp of the game.
Timestamp public createdAt;
/// @notice The timestamp of the game's global resolution.
Timestamp public resolvedAt;
/// @notice The current status of the game.
GameStatus public status;
/// @notice Flag for the `initialize` function to prevent re-initialization.
bool internal initialized;
/// @notice A boolean for whether or not the game type was respected when the game was created.
bool public wasRespectedGameTypeWhenCreated;
/// @notice The starting output root of the game that is proven from in case of a challenge.
/// @dev This should match the claim root of the parent game.
Proposal public startingOutputRoot;
/// @notice The address that can claim the bond.
address public bondRecipient;
/// @notice Whether or not the bond has been unlocked.
bool public bondUnlocked;
/// @notice Whether or not the bond has been claimed.
bool public bondClaimed;
/// @notice The amount of the bond.
uint256 public bondAmount;
/// @notice The index of the intermediate root that countered this game.
/// @dev The index is 1-based, so the countered intermediate root index is counteredByIntermediateRootIndexPlusOne -
/// 1. 0 is used to indicate that the game was not countered.
uint256 public counteredByIntermediateRootIndexPlusOne;
/// @notice The address that provided a proof of the given type.
/// @dev The address is the zero address if no proof has been provided or the proof has been nullified.
mapping(ProofType => address) internal proofTypeToProver;
/// @notice The timestamp of the game's expected resolution.
Timestamp public expectedResolution;
/// @notice The number of proofs provided.
uint8 public proofCount;
/// @notice Commitment to upgrades activated at this game's ending L2 block.
/// @dev Pinned once at initialization. The game's ending L2 block deterministically selects
/// the activation cutoff, so every proof for the game commits to the same historical
/// schedule even after newer upgrades are registered or activated.
bytes32 public scheduleId;
////////////////////////////////////////////////////////////////
// Events //
////////////////////////////////////////////////////////////////
/// @notice Emitted when the game is resolved.
/// @param status The status of the game.
event Resolved(GameStatus status);
/// @notice Emitted when a proposal with a TEE proof is challenged with a ZK proof.
/// @param challenger The address of the challenger.
/// @param intermediateRootIndex The index of the intermediate root that was countered.
event Challenged(address indexed challenger, uint256 intermediateRootIndex);
/// @notice Emitted when the game is proved.
/// @param proposer The address of the proposer.
/// @param proofType The type of proof.
event Proved(address indexed proposer, ProofType indexed proofType);
/// @notice Emitted when the game is nullified.
/// @param nullifier The address of the nullifier.
/// @param intermediateRootIndex The index of the intermediate root.
/// @param intermediateRoot The intermediate root.
event Nullified(address indexed nullifier, uint256 intermediateRootIndex, bytes32 intermediateRoot);
/// @notice Emitted when the credit is claimed.
/// @param recipient The address of the recipient.
/// @param amount The amount of credit claimed.
event CreditClaimed(address indexed recipient, uint256 amount);
////////////////////////////////////////////////////////////////
// Errors //
////////////////////////////////////////////////////////////////
/// @notice When the block interval or intermediate block interval is invalid.
error InvalidBlockInterval(uint256 slowBlockInterval, uint256 slowIntermediateBlockInterval);
/// @notice When the slow- and fast-block intervals do not yield the same intermediate root count.
error MismatchedIntermediateRootCount(uint256 slowCount, uint256 fastCount);
/// @notice When the block number is unexpected.
error UnexpectedBlockNumber(uint256 expectedBlockNumber, uint256 actualBlockNumber);
/// @notice When the game is over.
error GameOver();
/// @notice When the game is not over.
error GameNotOver();
/// @notice When the game is invalid.
error InvalidGame();
/// @notice When the parent game is invalid.
error InvalidParentGame();
/// @notice When the parent game has not resolved.
error ParentGameNotResolved();
/// @notice When there is no proof of the given type.
error MissingProof(ProofType proofType);
/// @notice When the proof has already been verified.
error AlreadyProven(ProofType proofType);
/// @notice When the proof is invalid.
error InvalidProof();
/// @notice When an invalid proof type is provided.
error InvalidProofType();
/// @notice When the intermediate root index is invalid.
error InvalidIntermediateRootIndex();
/// @notice When the intermediate root is the same as the proposed intermediate root.
error IntermediateRootSameAsProposed();
/// @notice When the intermediate root does not match the claim.
error IntermediateRootMismatch(bytes32 intermediateRoot, bytes32 claim);
/// @notice Thrown when the L1 origin block is too old to verify.
error L1OriginTooOld(uint256 l1OriginNumber, uint256 currentBlock);
/// @notice Thrown when the L1 origin block number is in the future.
error L1OriginInFuture(uint256 l1OriginNumber, uint256 currentBlock);
/// @notice Thrown when the L1 origin hash doesn't match the actual blockhash.
error L1OriginHashMismatch(bytes32 claimed, bytes32 actual);
/// @notice Thrown when the configured L2 block time is zero.
error InvalidL2BlockTime();
/// @notice Thrown when an L2 block precedes the configured genesis block.
error L2BlockBeforeGenesis(uint256 blockNumber, uint256 genesisBlockNumber);
/// @notice Thrown when an L2 block timestamp cannot be represented as a uint64.
error L2TimestampOverflow(uint256 blockNumber);
/// @notice Thrown when the claimed L2 block's timestamp has not yet been reached on L1.
error L2TimestampInFuture(uint64 claimTimestamp, uint256 l1Timestamp);
/// @notice Thrown when there are not enough proofs to resolve the game.
error NotEnoughProofs();
/// @param gameType_ The game type.
/// @param anchorStateRegistry_ The anchor state registry.
/// @param delayedWETH The delayed WETH contract.
/// @param teeVerifier The TEE verifier.
/// @param zkVerifier The ZK verifier.
/// @param teeImageHash The hash of the TEE image.
/// @param zkHashes The hashes of the ZK range and aggregate programs.
/// @param configHash The hash of the rollup configuration.
/// @param l2ChainId The chain ID of the L2 network.
/// @param intervalConfig The slow- and fast-block proposal intervals.
/// @param scheduleConfig Upgrade registry and deterministic L2 timestamp configuration.
constructor(
GameType gameType_,
IAnchorStateRegistry anchorStateRegistry_,
IDelayedWETH delayedWETH,
IVerifier teeVerifier,
IVerifier zkVerifier,
bytes32 teeImageHash,
ZkHashes memory zkHashes,
bytes32 configHash,
uint256 l2ChainId,
IntervalConfig memory intervalConfig,
ScheduleConfig memory scheduleConfig
) {
_validateIntervals(intervalConfig);
if (scheduleConfig.blockTime == 0) revert InvalidL2BlockTime();
// Set up initial game state.
GAME_TYPE = gameType_;
ANCHOR_STATE_REGISTRY = anchorStateRegistry_;
DISPUTE_GAME_FACTORY = ANCHOR_STATE_REGISTRY.disputeGameFactory();
DELAYED_WETH = delayedWETH;
TEE_VERIFIER = teeVerifier;
ZK_VERIFIER = zkVerifier;
TEE_IMAGE_HASH = teeImageHash;
ZK_RANGE_HASH = zkHashes.rangeHash;
ZK_AGGREGATE_HASH = zkHashes.aggregateHash;
CONFIG_HASH = configHash;
L2_CHAIN_ID = l2ChainId;
L2_GENESIS_BLOCK_NUMBER = scheduleConfig.genesisBlockNumber;
L2_GENESIS_TIMESTAMP = scheduleConfig.genesisTimestamp;
L2_BLOCK_TIME = scheduleConfig.blockTime;
SLOW_BLOCK_INTERVAL = intervalConfig.slowBlockInterval;
SLOW_INTERMEDIATE_BLOCK_INTERVAL = intervalConfig.slowIntermediateBlockInterval;
FAST_BLOCK_INTERVAL = intervalConfig.fastBlockInterval;
FAST_INTERMEDIATE_BLOCK_INTERVAL = intervalConfig.fastIntermediateBlockInterval;
PROTOCOL_VERSIONS = scheduleConfig.protocolVersions;
INITIALIZE_CALLDATA_SIZE = 0x8E + 0x20 * intermediateOutputRootsCount();
}
/// @notice Initializes the contract.
/// @param proof Encoding: uint8 proofType || bytes32 l1OriginHash || uint256 l1OriginNumber || verifier payload.
/// @dev This function may only be called once.
/// @dev The proof-supplied L1 origin hash is verified against the supplied block number and journaled. It need not
/// equal `l1Head()`, which the factory captures at game creation for proofs submitted after initialization.
function initializeWithInitData(bytes calldata proof) external payable virtual {
// The game must not have already been initialized.
if (initialized) revert AlreadyInitialized();
// 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: 0x8E + 0x20 * intermediateOutputRootsCount()
// - 0x04 selector
// - 0x14 creator address (CWIA data offset: 0x00)
// - 0x20 root claim (CWIA data offset: 0x14)
// - 0x20 l1 head (CWIA data offset: 0x34)
// - 0x20 extraData (l2BlockNumber) (CWIA data offset: 0x54)
// - 0x14 extraData (parent game address) (CWIA data offset: 0x74)
// - 0x20 x (SLOW_BLOCK_INTERVAL / SLOW_INTERMEDIATE_BLOCK_INTERVAL) extraData (intermediate roots) (CWIA data
// offset: 0x88)
// - 0x02 CWIA bytes
// - 0x20 proof length location
// - 0x20 proof length
// - ((proof.length + 32 - 1)/ 32) * 32 (round up to the nearest 32 bytes)
uint256 proofLength = (proof.length + 32 - 1) / 32 * 32;
uint256 expectedCallDataSize = INITIALIZE_CALLDATA_SIZE + 0x40 + proofLength;
assembly {
if iszero(eq(calldatasize(), expectedCallDataSize)) {
// Store the selector for `BadExtraData()` & revert.
mstore(0x00, 0x9824bdab)
revert(0x1C, 0x04)
}
}
// Last intermediate root has to match the proposal's claim
if (intermediateOutputRoot(intermediateOutputRootsCount() - 1) != rootClaim().raw()) {
revert IntermediateRootMismatch(
intermediateOutputRoot(intermediateOutputRootsCount() - 1), rootClaim().raw()
);
}
// The first game is initialized with a parent address of the AnchorStateRegistry.
if (parentAddress() != address(ANCHOR_STATE_REGISTRY)) {
// For subsequent games, get the parent game's information.
IDisputeGame parentGame = IDisputeGame(parentAddress());
// Parent game must be registered, respected, not blacklisted, not retired, and not challenged.
if (!_isValidGame(parentGame)) revert InvalidParentGame();
startingOutputRoot = Proposal({
l2SequenceNumber: parentGame.l2SequenceNumber(), root: Hash.wrap(parentGame.rootClaim().raw())
});
} else {
// When there is no parent game, the starting output root is the starting root in the AnchorStateRegistry.
startingOutputRoot = ANCHOR_STATE_REGISTRY.getStartingAnchorRoot();
}
// Resolved once and threaded through both fork-sensitive decisions below, which would
// otherwise re-read the schedule from `PROTOCOL_VERSIONS` a second time.
uint256 firstFastBlock = _firstFastBlock();
// The block number must be one block interval after the starting block number. The interval
// is selected on the starting block so the game chain stays contiguous across the speedup.
(uint256 blockInterval,) = _intervalsAt(startingOutputRoot.l2SequenceNumber, firstFastBlock);
if (l2SequenceNumber() != startingOutputRoot.l2SequenceNumber + blockInterval) {
revert UnexpectedBlockNumber(startingOutputRoot.l2SequenceNumber + blockInterval, l2SequenceNumber());
}
// Set the game as initialized.
initialized = true;
// Pinning the upgrades active at the ending L2 block makes the schedule independent of both
// the proof's L1 head and the L1 block in which this game is created.
//
// Note that this anchors on the *ending* block while the interval selection above anchors on
// the *starting* block. That is deliberate, and it is what makes the straddling game work: it
// spans the slow-block interval its start selects, while pinning the post-speedup schedule
// its end falls under, so the prover knows the fast cadence is active past the boundary.
uint256 claimBlock = l2SequenceNumber();
if (claimBlock < L2_GENESIS_BLOCK_NUMBER) {
revert L2BlockBeforeGenesis(claimBlock, L2_GENESIS_BLOCK_NUMBER);
}
uint64 claimTimestamp = _l2Timestamp(claimBlock, firstFastBlock);
// `ProtocolVersions` freezes mutations to an activation `FREEZE_WINDOW` before it takes
// effect. Requiring the claim timestamp to have been reached on L1 additionally ensures the
// game's L2 time is not still in L1's future when its active schedule is pinned.
if (claimTimestamp > block.timestamp) revert L2TimestampInFuture(claimTimestamp, block.timestamp);
scheduleId = PROTOCOL_VERSIONS.activatedScheduleId(claimTimestamp);
// Set the game's starting timestamp.
createdAt = Timestamp.wrap(uint64(block.timestamp));
// Set the game as respected if the game type is respected.
wasRespectedGameTypeWhenCreated =
GameType.unwrap(ANCHOR_STATE_REGISTRY.respectedGameType()) == GameType.unwrap(GAME_TYPE);
// Set expected resolution.
expectedResolution = Timestamp.wrap(type(uint64).max);
// Verify the proof.
ProofType proofType = ProofType(uint8(proof[0]));
bytes32 l1OriginHash = bytes32(proof[1:33]);
uint256 l1OriginNumber = uint256(bytes32(proof[33:65]));
// Verify claimed L1 origin hash matches actual blockhash
_verifyL1Origin(l1OriginHash, l1OriginNumber);
_verifyProof(
proof[65:],
proofType,
gameCreator(),
l1OriginHash,
startingOutputRoot.root.raw(),
uint64(startingOutputRoot.l2SequenceNumber),
rootClaim().raw(),
uint64(l2SequenceNumber()),
intermediateOutputRoots()
);
_proofVerifiedUpdate(proofType, gameCreator());
// Set the bond recipient to the creator. It can change if challenged successfully.
bondRecipient = gameCreator();
// Deposit the bond.
bondAmount = msg.value;
DELAYED_WETH.deposit{ value: msg.value }();
}
/// @notice Verifies a proof for the current game.
/// @param proofBytes The proof.
/// @dev The first byte of the proof is the proof type.
function verifyProposalProof(bytes calldata proofBytes) external {
// The game must be in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
// The game must not be over.
if (gameOver()) revert GameOver();
ProofType proofType = ProofType(uint8(proofBytes[0]));
if (proofTypeToProver[proofType] != address(0)) revert AlreadyProven(proofType);
_verifyProof(
proofBytes[1:],
proofType,
msg.sender,
l1Head().raw(),
startingOutputRoot.root.raw(),
uint64(startingOutputRoot.l2SequenceNumber),
rootClaim().raw(),
uint64(l2SequenceNumber()),
intermediateOutputRoots()
);
_proofVerifiedUpdate(proofType, msg.sender);
}
/// @notice Resolves the game after a proof has been provided and enough time has passed.
function resolve() external returns (GameStatus) {
// The game must be in progress.
if (status != GameStatus.IN_PROGRESS) revert ClaimAlreadyResolved();
GameStatus parentGameStatus = _getParentGameStatus();
// The parent game must have resolved.
if (parentGameStatus == GameStatus.IN_PROGRESS) revert ParentGameNotResolved();
// If the parent game's claim is invalid, blacklisted, or retired, then the current game's claim is invalid.
// We don't care about what happens in this game once the parent is invalid.
if (parentGameStatus == GameStatus.CHALLENGER_WINS) {
status = GameStatus.CHALLENGER_WINS;
} else {
// Game must be completed with a valid proof and enough proofs.
if (_updateProofCount()) {
return status;
}
if (!gameOver()) revert GameNotOver();
if (proofCount < PROOF_THRESHOLD) revert NotEnoughProofs();
// If the game is challenged, reward the challenger.
if (counteredByIntermediateRootIndexPlusOne > 0) {
status = GameStatus.CHALLENGER_WINS;
bondRecipient = proofTypeToProver[ProofType.ZK];
} else {
status = GameStatus.DEFENDER_WINS;
}
}
// Mark the game as resolved.
resolvedAt = Timestamp.wrap(uint64(block.timestamp));
emit Resolved(status);
return status;
}
/// @notice Challenges the TEE proof with a ZK proof.
/// @param proofBytes The proof bytes.
/// @param intermediateRootIndex The index of the intermediate root to challenge.
/// @param intermediateRootToProve The intermediate root that the proof claims to be correct.
function challenge(
bytes calldata proofBytes,
uint256 intermediateRootIndex,
bytes32 intermediateRootToProve
)
external
{
// Can only challenge a game that has not been challenged or resolved yet.
if (status != GameStatus.IN_PROGRESS) revert ClaimAlreadyResolved();
// This game cannot be blacklisted or retired.
if (!_isValidGame(IDisputeGame(address(this)))) revert InvalidGame();
// The parent game cannot have been challenged.
if (_getParentGameStatus() == GameStatus.CHALLENGER_WINS) revert InvalidParentGame();
// The TEE prover must not be empty.
if (proofTypeToProver[ProofType.TEE] == address(0)) revert MissingProof(ProofType.TEE);
// You should nullify the game if a ZK proof has already been provided.
// This also prevents another challenge while the current challenge is in progress.
if (proofTypeToProver[ProofType.ZK] != address(0)) revert AlreadyProven(ProofType.ZK);
// Can only challenge with a ZK proof.
ProofType proofType = ProofType(uint8(proofBytes[0]));
if (proofType != ProofType.ZK) revert InvalidProofType();
_checkIntermediateRoot(intermediateRootIndex, intermediateRootToProve);
(bytes32 startingRoot, uint64 startingL2SequenceNumber, uint64 endingL2SequenceNumber) =
_getStartingIntermediateRootAndL2SequenceNumbers(intermediateRootIndex);
_verifyProof(
proofBytes[1:],
proofType,
msg.sender,
l1Head().raw(),
startingRoot,
startingL2SequenceNumber,
intermediateRootToProve,
endingL2SequenceNumber,
abi.encodePacked(intermediateRootToProve)
);
// This allows a ZK nullification to be performed.
proofTypeToProver[proofType] = msg.sender;
// This is only in case the ZK proof is nullified, which would lower the proof count.
// If the ZK is nullified, we allow the remaining TEE proof to resolve.
// The expected resolution time can no longer be increased as both proof types have been submitted.
// The exception is if the ZK proof is nullified, in which case the expected resolution will be
// increased by SLOW_FINALIZATION_DELAY from the time of nullification.
proofCount += 1;
// We purposely increase the resolution to allow for a ZK nullification.
expectedResolution = Timestamp.wrap(uint64(block.timestamp + SLOW_FINALIZATION_DELAY));
// Store which intermediate root was countered.
counteredByIntermediateRootIndexPlusOne = intermediateRootIndex + 1;
// Emit the challenged event.
emit Challenged(msg.sender, intermediateRootIndex);
}
/// @notice Nullifies the game if a soundness issue is found.
/// @param proofBytes The proof.
/// @param intermediateRootIndex Index of the intermediate root to challenge.
/// @param intermediateRootToProve The intermediate root that the proof claims to be correct.
/// @dev The first byte of the proof is the proof type.
function nullify(
bytes calldata proofBytes,
uint256 intermediateRootIndex,
bytes32 intermediateRootToProve
)
external
{
// Can only nullify if the game is still in progress.
if (status != GameStatus.IN_PROGRESS) revert ClaimAlreadyResolved();
ProofType proofType = ProofType(uint8(proofBytes[0]));
if (proofTypeToProver[proofType] == address(0)) revert MissingProof(proofType);
// If this game has been challenged, can only nullify the challenged intermediate root and only with ZK.
if (counteredByIntermediateRootIndexPlusOne > 0) {
if (intermediateRootIndex != counteredByIntermediateRootIndexPlusOne - 1) {
revert InvalidIntermediateRootIndex();
}
if (intermediateRootToProve != intermediateOutputRoot(intermediateRootIndex)) {
revert IntermediateRootMismatch(intermediateRootToProve, intermediateOutputRoot(intermediateRootIndex));
}
if (proofType != ProofType.ZK) revert InvalidProofType();
} else {
_checkIntermediateRoot(intermediateRootIndex, intermediateRootToProve);
}
(bytes32 startingRoot, uint64 startingL2SequenceNumber, uint64 endingL2SequenceNumber) =
_getStartingIntermediateRootAndL2SequenceNumbers(intermediateRootIndex);
_verifyProof(
proofBytes[1:],
proofType,
msg.sender,
l1Head().raw(),
startingRoot,
startingL2SequenceNumber,
intermediateRootToProve,
endingL2SequenceNumber,
abi.encodePacked(intermediateRootToProve)
);
_proofRefutedUpdate(proofType);
emit Nullified(msg.sender, intermediateRootIndex, intermediateRootToProve);
// Nullify the verifier to prevent further proof verification.
if (proofType == ProofType.ZK) {
IVerifier(ZK_VERIFIER).nullify();
} else if (proofType == ProofType.TEE) {
IVerifier(TEE_VERIFIER).nullify();
}
}
/// @notice Claim the credit belonging to the bond recipient. Reverts if the game isn't
/// finalized or if the bond transfer fails.
function claimCredit() external nonReentrant {
// The bond must not have been claimed yet.
if (bondClaimed) revert NoCreditToClaim();
// The game must have resolved or 14 days have passed since creation.
// 14 days chosen as the proof system should have progressed enough so this can't update the
// anchor state registry anymore.
if (expectedResolution.raw() != type(uint64).max) {
if (resolvedAt.raw() == 0) revert GameNotResolved();
} else {
if (block.timestamp < createdAt.raw() + 14 days) revert GameNotOver();
}
if (!bondUnlocked) {
DELAYED_WETH.unlock(bondRecipient, bondAmount);
bondUnlocked = true;
return;
}
bondClaimed = true;
DELAYED_WETH.withdraw(bondRecipient, bondAmount);
// Transfer the credit to the bond recipient.
(bool success,) = bondRecipient.call{ value: bondAmount }(hex"");
if (!success) revert BondTransferFailed();
// Emit the credit claimed event.
emit CreditClaimed(bondRecipient, bondAmount);
}
/// @notice Closes the game by trying to update the anchor state.
function closeGame() external {
// We won't close the game if the system is currently paused.
if (ANCHOR_STATE_REGISTRY.paused()) {
revert GamePaused();
}
// Make sure that the game is resolved.
// AnchorStateRegistry should be checking this but we're being defensive here.
if (resolvedAt.raw() == 0) {
revert GameNotResolved();
}
// Game must be finalized according to the AnchorStateRegistry.
bool finalized = ANCHOR_STATE_REGISTRY.isGameFinalized(IDisputeGame(address(this)));
if (!finalized) {
revert GameNotFinalized();
}
// Try to update the anchor game first. Won't always succeed because delays can lead
// to situations in which this game might not be eligible to be a new anchor game.
// eip150-safe
try ANCHOR_STATE_REGISTRY.setAnchorState(IDisputeGame(address(this))) { } catch { }
}
/// @notice The starting block number of the game.
function startingBlockNumber() external view returns (uint256) {
return startingOutputRoot.l2SequenceNumber;
}
/// @notice The starting output root of the game.
function startingRootHash() external view returns (Hash) {
return startingOutputRoot.root;
}
/// @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, Claim, bytes memory) {
return (GAME_TYPE, rootClaim(), extraData());
}
/// @notice Address that provided a TEE proof.
function teeProver() external view returns (address) {
return proofTypeToProver[ProofType.TEE];
}
/// @notice Address that provided a ZK proof.
function zkProver() external view returns (address) {
return proofTypeToProver[ProofType.ZK];
}
/// @notice The game type.
/// @dev For compliance with the IDisputeGame interface.
function gameType() external view returns (GameType) {
return GAME_TYPE;
}
/// @notice The anchor state registry.
/// @dev Needed for anchorStateRegistry.isGameRegistered()
function anchorStateRegistry() external view returns (IAnchorStateRegistry) {
return ANCHOR_STATE_REGISTRY;
}
/// @notice Determines if the game is finished.
function gameOver() public view returns (bool) {
return expectedResolution.raw() <= block.timestamp;
}
/// @notice Returns the proposal intervals that govern a game starting at `startingBlock`.
/// @dev Offchain proposers and challengers must resolve intervals per game through this getter
/// rather than reading `SLOW_BLOCK_INTERVAL` / `SLOW_INTERMEDIATE_BLOCK_INTERVAL`, which describe
/// only games starting on slow blocks.
/// @dev Selection is on the starting block rather than the ending block so the game chain stays
/// contiguous across the activation: every game satisfies
/// `end == parent.end + blockInterval` for the interval its own start selects. Exactly one
/// game straddles the activation and is proven under the slow-block interval, which is
/// correct because provers apply fork rules per block by timestamp.
/// @param startingBlock The starting L2 block number of the game.
/// @return The block interval and the intermediate block interval governing that game.
function intervalsForStartingBlock(uint256 startingBlock) public view returns (uint256, uint256) {
return _intervalsAt(startingBlock, _firstFastBlock());
}
/// @notice The number of intermediate output roots.
/// @dev At least one as the proposal's root claim is considered an intermediate root.
/// The constructor requires both interval pairs to yield the same count, so this is constant
/// across the speedup activation and the CWIA `extraData` layout never changes.
function intermediateOutputRootsCount() public view returns (uint256) {
return (SLOW_BLOCK_INTERVAL / SLOW_INTERMEDIATE_BLOCK_INTERVAL);
}
/// @notice The intermediate output roots of the game.
function intermediateOutputRoots() public view returns (bytes memory) {
return _getArgBytes(0x88, 0x20 * intermediateOutputRootsCount());
}
/// @notice The intermediate output root at the given index.
/// @param index The index of the intermediate output root.
function intermediateOutputRoot(uint256 index) public view returns (bytes32) {
if (index >= intermediateOutputRootsCount()) revert InvalidIntermediateRootIndex();
return _getArgBytes32(0x88 + 0x20 * index);
}
/// @notice Getter for the extra data.
function extraData() public view returns (bytes memory) {
// The extra data starts at the second word within the cwia calldata and
// is 52 + 32 x intermediateRootsCount() bytes long.
// 32 bytes are for the l2BlockNumber
// 20 bytes are for the parent address
// 32 bytes are for each intermediate root
return _getArgBytes(0x54, 0x34 + 0x20 * intermediateOutputRootsCount());
}
/// @notice Getter for the creator of the dispute game.
function gameCreator() public pure returns (address) {
return _getArgAddress(0x00);
}
/// @notice Getter for the root claim.
function rootClaim() public pure returns (Claim) {
return Claim.wrap(_getArgBytes32(0x14));
}
/// @notice Getter for the parent hash of the L1 block when the dispute game was created.
/// @dev Proofs submitted through `verifyProposalProof`, `challenge`, and `nullify` journal this factory-captured
/// hash. Initialization instead journals the independently verified L1 origin hash supplied to
/// `initializeWithInitData`.
function l1Head() public pure returns (Hash) {
return Hash.wrap(_getArgBytes32(0x34));
}
/// @notice The L2 sequence number for which this game is proposing an output root (in this case - the block
/// number).
function l2SequenceNumber() public pure returns (uint256) {
return _getArgUint256(0x54);
}
/// @notice The parent UUID of the game.
function parentAddress() public pure returns (address) {
return _getArgAddress(0x74);
}
function _proofVerifiedUpdate(ProofType proofType, address proposer) internal {
proofTypeToProver[proofType] = proposer;
proofCount += 1;
_decreaseExpectedResolution();
emit Proved(proposer, proofType);
}
/// @notice Decreases the expected resolution timestamp.
function _decreaseExpectedResolution() internal {
uint64 delay = _getDelay();
if (delay == type(uint64).max) {
// If there are no proofs, don't allow the game to resolve.
expectedResolution = Timestamp.wrap(type(uint64).max);
return;
}
// Only allow decreases to the expected resolution.
uint64 newResolution = uint64(block.timestamp) + delay;
expectedResolution = Timestamp.wrap(uint64(FixedPointMathLib.min(newResolution, expectedResolution.raw())));
}
/// @dev Should only occur if challenged or nullified.
function _proofRefutedUpdate(ProofType proofType) internal {
delete proofTypeToProver[proofType];
// A ZK challenge is recorded in `counteredByIntermediateRootIndexPlusOne`; dropping the ZK proof clears it.
if (proofType == ProofType.ZK) {
delete counteredByIntermediateRootIndexPlusOne;
}
// Should not be possible, but just in case.
if (proofCount == 0) revert NotEnoughProofs();
unchecked {
proofCount -= 1;
}
_increaseExpectedResolution();
}
function _increaseExpectedResolution() internal {
uint64 delay = _getDelay();
if (delay == type(uint64).max) {
// If there are no proofs, don't allow the game to resolve.
expectedResolution = Timestamp.wrap(type(uint64).max);
return;
}
// We purposely increase the resolution even if it's longer than it should be
// as this can only occur if there is an issue with the proof system so
// we give enough time to resolve the issue and possibly blacklist this game.
expectedResolution = Timestamp.wrap(uint64(block.timestamp) + delay);
}
/// @notice Updates the proof count and returns true if a proof was nullified.
function _updateProofCount() internal returns (bool) {
if (proofTypeToProver[ProofType.TEE] != address(0) && TEE_VERIFIER.nullified()) {
_proofRefutedUpdate(ProofType.TEE);
return true;
}
if (proofTypeToProver[ProofType.ZK] != address(0) && ZK_VERIFIER.nullified()) {
_proofRefutedUpdate(ProofType.ZK);
return true;
}
return false;
}
function _getDelay() internal view returns (uint64) {
if (proofCount >= 2) {
return FAST_FINALIZATION_DELAY;
} else if (proofCount == 1) {
return SLOW_FINALIZATION_DELAY;
} else {
return type(uint64).max;
}
}
function _verifyProof(
bytes calldata proofBytes,
ProofType proofType,
address proposer,
bytes32 l1OriginHash,
bytes32 startingRoot,
uint64 startingL2SequenceNumber,
bytes32 endingRoot,
uint64 endingL2SequenceNumber,
bytes memory intermediateRoots
)
internal
view
{
if (proofBytes.length < 1) revert InvalidProof();
if (proofType == ProofType.TEE) {
_verifyTeeProof(
proofBytes,
proposer,
l1OriginHash,
startingRoot,
startingL2SequenceNumber,
endingRoot,
endingL2SequenceNumber,
intermediateRoots
);
} else if (proofType == ProofType.ZK) {
_verifyZkProof(
proofBytes,
proposer,
l1OriginHash,
startingRoot,
startingL2SequenceNumber,
endingRoot,
endingL2SequenceNumber,
intermediateRoots
);
} else {
revert InvalidProofType();
}
}
/// @notice Verifies a TEE proof for the current game.
/// @param proofBytes The proof: signature(65).
function _verifyTeeProof(
bytes calldata proofBytes,
address proposer,
bytes32 l1OriginHash,
bytes32 startingRoot,
uint64 startingL2SequenceNumber,
bytes32 endingRoot,
uint64 endingL2SequenceNumber,
bytes memory intermediateRoots
)
internal
view
{
bytes32 journal = keccak256(
abi.encodePacked(
proposer,
l1OriginHash,
startingRoot,
startingL2SequenceNumber,
endingRoot,
endingL2SequenceNumber,
intermediateRoots,
CONFIG_HASH,
TEE_IMAGE_HASH,
scheduleId
)
);
// Validate the proof.
bytes memory proof = abi.encodePacked(proposer, proofBytes);
if (!TEE_VERIFIER.verify(proof, TEE_IMAGE_HASH, journal)) revert InvalidProof();
}
/// @notice Verifies a ZK proof for the current game.
/// @param proofBytes The proof: zkProof (variable).
function _verifyZkProof(
bytes calldata proofBytes,
address proposer,
bytes32 l1OriginHash,
bytes32 startingRoot,
uint64 startingL2SequenceNumber,
bytes32 endingRoot,
uint64 endingL2SequenceNumber,
bytes memory intermediateRoots
)
internal
view
{
bytes32 journal = keccak256(
abi.encodePacked(
proposer,
l1OriginHash,
startingRoot,
startingL2SequenceNumber,
endingRoot,
endingL2SequenceNumber,
intermediateRoots,
CONFIG_HASH,
ZK_RANGE_HASH,
scheduleId
)
);
// Validate the proof.
if (!ZK_VERIFIER.verify(proofBytes, ZK_AGGREGATE_HASH, journal)) revert InvalidProof();
}
/// @notice Returns the status of the parent game.
/// @dev If the parent game address is `address(ANCHOR_STATE_REGISTRY)`, then the parent game's status is considered
/// as `DEFENDER_WINS`.
function _getParentGameStatus() internal view returns (GameStatus) {
if (parentAddress() != address(ANCHOR_STATE_REGISTRY)) {
IDisputeGame parentGame = IDisputeGame(parentAddress());
if (ANCHOR_STATE_REGISTRY.isGameBlacklisted(parentGame) || ANCHOR_STATE_REGISTRY.isGameRetired(parentGame))
{
return GameStatus.CHALLENGER_WINS;
}
return parentGame.status();
}
// If this is the first dispute game (i.e. parent game address is `address(ANCHOR_STATE_REGISTRY)`), then the
// parent game's status is considered as `DEFENDER_WINS`.
return GameStatus.DEFENDER_WINS;
}
/// @notice Checks if the game is registered, respected, not blacklisted, not retired, and not challenged.
/// @param game The game to check.
function _isValidGame(IDisputeGame game) internal view returns (bool) {
return ANCHOR_STATE_REGISTRY.isGameRegistered(game) && ANCHOR_STATE_REGISTRY.isGameRespected(game)
&& !ANCHOR_STATE_REGISTRY.isGameBlacklisted(game) && !ANCHOR_STATE_REGISTRY.isGameRetired(game)
&& (game.status() != GameStatus.CHALLENGER_WINS);
}
/// @notice Verifies that the claimed L1 origin hash matches the actual blockhash.
/// @param l1OriginHash The L1 block hash claimed in the proof.
/// @param l1OriginNumber The L1 block number claimed in the proof.
function _verifyL1Origin(bytes32 l1OriginHash, uint256 l1OriginNumber) internal view {
// Check for future block
if (l1OriginNumber >= block.number) {
revert L1OriginInFuture(l1OriginNumber, block.number);
}
bytes32 actualHash;
uint256 blockAge = block.number - l1OriginNumber;
// Prefer blockhash() over EIP-2935 when possible since it's cheaper (no external call).
if (blockAge <= BLOCKHASH_WINDOW) {
actualHash = blockhash(l1OriginNumber);
} else if (blockAge <= EIP2935_WINDOW) {
// EIP-2935 expects raw calldata: exactly 32 bytes containing the block number.
// Using a Solidity interface would add a 4-byte function selector, causing a revert.
// We use a low-level staticcall with raw 32-byte calldata instead.
(bool success, bytes memory result) = EIP2935_CONTRACT.staticcall(abi.encode(l1OriginNumber));
if (!success || result.length != 32) {
revert L1OriginTooOld(l1OriginNumber, block.number);
}
actualHash = abi.decode(result, (bytes32));
} else {
revert L1OriginTooOld(l1OriginNumber, block.number);
}
if (actualHash == bytes32(0)) {
revert L1OriginTooOld(l1OriginNumber, block.number);
}
if (actualHash != l1OriginHash) {
revert L1OriginHashMismatch(l1OriginHash, actualHash);
}
}
/// @notice Checks if the intermediate root index is valid and that the intermediate root differs from the proposed
/// intermediate root.
///@param intermediateRootIndex The index of the intermediate root to check.
/// @param intermediateRootToProve The intermediate root that the proof claims to be correct.
function _checkIntermediateRoot(uint256 intermediateRootIndex, bytes32 intermediateRootToProve) internal view {
if (intermediateRootIndex >= intermediateOutputRootsCount()) revert InvalidIntermediateRootIndex();
if (intermediateOutputRoot(intermediateRootIndex) == intermediateRootToProve) {
revert IntermediateRootSameAsProposed();
}
}
/// @notice Gets the starting intermediate root and the starting and ending L2 sequence numbers.
/// @param intermediateRootIndex The index of the intermediate root to get the starting intermediate root and L2
/// sequence numbers for. @return startingRoot The starting intermediate root.
/// @return startingL2SequenceNumber The starting L2 sequence number.
/// @return endingL2SequenceNumber The ending L2 sequence number.
function _getStartingIntermediateRootAndL2SequenceNumbers(uint256 intermediateRootIndex)
internal
view
returns (bytes32, uint64, uint64)
{
bytes32 startingRoot = intermediateRootIndex == 0
? startingOutputRoot.root.raw()
: intermediateOutputRoot(intermediateRootIndex - 1);
(, uint256 intermediateBlockInterval) = intervalsForStartingBlock(startingOutputRoot.l2SequenceNumber);
uint64 startingL2SequenceNumber =
uint64(startingOutputRoot.l2SequenceNumber + intermediateRootIndex * intermediateBlockInterval);
uint64 endingL2SequenceNumber = startingL2SequenceNumber + uint64(intermediateBlockInterval);
return (startingRoot, startingL2SequenceNumber, endingL2SequenceNumber);
}
/// @notice Semantic version.
/// @custom:semver 0.3.0
function version() public pure virtual returns (string memory) {
return "0.3.0";
}
/// @notice Derives an L2 block timestamp: the slow cadence before the speedup, whole-second groups after it.
/// @param claimBlock The L2 block number to derive a timestamp for.
/// @param firstFastBlock The speedup activation block, as returned by `_firstFastBlock()`.
function _l2Timestamp(uint256 claimBlock, uint256 firstFastBlock) private view returns (uint64) {
if (claimBlock < firstFastBlock) return _slowL2Timestamp(claimBlock);
uint256 claimTimestamp =
uint256(_slowL2Timestamp(firstFastBlock)) + (claimBlock - firstFastBlock) / FAST_BLOCKS_PER_SECOND;
if (claimTimestamp > type(uint64).max) revert L2TimestampOverflow(claimBlock);
return uint64(claimTimestamp);
}
/// @notice Reverts unless both interval pairs are positive, divisible, and yield the same
/// intermediate root count.
function _validateIntervals(IntervalConfig memory intervalConfig) private pure {
uint256 slowBlockInterval = intervalConfig.slowBlockInterval;
uint256 slowIntermediateBlockInterval = intervalConfig.slowIntermediateBlockInterval;
uint256 fastBlockInterval = intervalConfig.fastBlockInterval;
uint256 fastIntermediateBlockInterval = intervalConfig.fastIntermediateBlockInterval;
if (
slowBlockInterval == 0 || slowIntermediateBlockInterval == 0
|| slowBlockInterval % slowIntermediateBlockInterval != 0
) {
revert InvalidBlockInterval(slowBlockInterval, slowIntermediateBlockInterval);
}
if (
fastBlockInterval == 0 || fastIntermediateBlockInterval == 0
|| fastBlockInterval % fastIntermediateBlockInterval != 0
) {
revert InvalidBlockInterval(fastBlockInterval, fastIntermediateBlockInterval);
}
// The intermediate root count fixes the CWIA `extraData` layout, which is frozen for the
// lifetime of this implementation. Both interval pairs must therefore agree on it.
uint256 slowCount = slowBlockInterval / slowIntermediateBlockInterval;
uint256 fastCount = fastBlockInterval / fastIntermediateBlockInterval;
if (slowCount != fastCount) revert MismatchedIntermediateRootCount(slowCount, fastCount);
}
/// @notice Returns the first L2 block number produced at the fast cadence, or `type(uint256).max`
/// when the speedup is not scheduled.
/// @dev Reading the live schedule is safe despite it being mutable, in both directions:
///
/// - A game that selected the fast-block intervals has a starting block at or past the
/// activation, so the activation is in the past. `ProtocolVersions._assertNotFrozen`
/// rejects every mutation of a passed activation, from `setTimestamp` and
/// `delayTimestamp` alike, so that game's selection can never be revoked.
/// - A game that selected the slow-block intervals cannot be pulled across the boundary
/// either, including by the owner moving the activation *earlier* rather than later.
/// `initializeWithInitData` rejects a game whose ending L2 timestamp L1 has not yet
/// reached, so every initialized game satisfies `startingTimestamp < endingTimestamp <=
/// block.timestamp`, while any new activation must clear `block.timestamp + MIN_NOTICE`.
/// The activation therefore always lands after the game's starting block.
function _firstFastBlock() private view returns (uint256) {
uint64[] memory schedule = PROTOCOL_VERSIONS.getSchedule();
if (schedule.length <= FAST_BLOCK_UPGRADE_INDEX) return type(uint256).max;
uint64 fastActivationTimestamp = schedule[FAST_BLOCK_UPGRADE_INDEX];
if (fastActivationTimestamp == 0) return type(uint256).max;
if (fastActivationTimestamp <= L2_GENESIS_TIMESTAMP) {
return L2_GENESIS_BLOCK_NUMBER;
}
return L2_GENESIS_BLOCK_NUMBER
+ FixedPointMathLib.divUp(fastActivationTimestamp - L2_GENESIS_TIMESTAMP, L2_BLOCK_TIME);
}
/// @notice Selects the proposal intervals governing a game, from its starting block number and an
/// already-resolved speedup activation block.
/// @dev Takes `firstFastBlock` rather than resolving it so a caller making more than one
/// fork-sensitive decision pays for `PROTOCOL_VERSIONS.getSchedule()` once.
function _intervalsAt(uint256 startingBlock, uint256 firstFastBlock) private view returns (uint256, uint256) {
if (startingBlock < firstFastBlock) return (SLOW_BLOCK_INTERVAL, SLOW_INTERMEDIATE_BLOCK_INTERVAL);
return (FAST_BLOCK_INTERVAL, FAST_INTERMEDIATE_BLOCK_INTERVAL);
}
/// @notice Derives an L2 block timestamp using the slow block cadence.
function _slowL2Timestamp(uint256 claimBlock) private view returns (uint64) {
uint256 blocksSinceGenesis = claimBlock - L2_GENESIS_BLOCK_NUMBER;
uint256 maxBlocks = (type(uint64).max - L2_GENESIS_TIMESTAMP) / L2_BLOCK_TIME;
if (blocksSinceGenesis > maxBlocks) revert L2TimestampOverflow(claimBlock);
return L2_GENESIS_TIMESTAMP + uint64(blocksSinceGenesis * uint256(L2_BLOCK_TIME));
}
}
interfaces/L1/IProtocolVersions.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
import { IReinitializableBase } from "interfaces/universal/IReinitializableBase.sol";
/// @title IProtocolVersions
/// @notice Interface for the ProtocolVersions upgrade schedule contract.
interface IProtocolVersions is IProxyAdminOwnedBase, ISemver, IReinitializableBase {
event UpgradeRegistered(uint256 indexed id);
event MinimumProtocolVersionUpdated(uint256 indexed protocolVersion);
event TimestampSet(uint256 indexed id, uint256 timestamp);
event ScheduleIdUpdated(bytes32 indexed newScheduleId);
event IncidentResponderUpdated(address indexed previousIncidentResponder, address indexed newIncidentResponder);
event Initialized(uint8 version);
error ProtocolVersions_UnknownUpgrade(uint256 id);
error ProtocolVersions_InvalidProtocolVersion();
error ProtocolVersions_ActivationAlreadyPassed(uint256 id, uint64 activationTimestamp);
error ProtocolVersions_ActivationFrozen(uint256 id, uint64 activationTimestamp);
error ProtocolVersions_NotIncidentResponder();
error ProtocolVersions_NotScheduled(uint256 id);
error ProtocolVersions_DelayMustBeLater(uint64 currentTimestamp, uint64 newTimestamp);
error ProtocolVersions_StaticScheduleHole(uint256 id, uint256 nextScheduledId);
error ProtocolVersions_TimestampNotAfterPrevious(
uint256 id, uint256 previousId, uint64 previousTimestamp, uint64 timestamp
);
error ProtocolVersions_TimestampNotBeforeNext(uint256 id, uint256 nextId, uint64 timestamp, uint64 nextTimestamp);
error ProtocolVersions_NotInitialized();
error ProtocolVersions_InsufficientNotice(uint64 timestamp);
function initialize(
address _incidentResponder,
uint64[] calldata _initialSchedule,
uint256 _initialMinimumProtocolVersion
)
external;
function registerUpgrade(uint64 timestamp, uint256 minProtocolVersion) external returns (uint256);
function setMinimumProtocolVersion(uint256 protocolVersion) external;
function setTimestamp(uint256 id, uint64 timestamp) external;
function setIncidentResponder(address newIncidentResponder) external;
function delayTimestamp(uint256 id, uint64 newTimestamp) external;
function MIN_NOTICE() external view returns (uint64);
function FREEZE_WINDOW() external view returns (uint64);
function minimumProtocolVersion() external view returns (uint256);
function incidentResponder() external view returns (address);
function scheduleId() external view returns (bytes32);
function scheduleId(uint256 id) external view returns (bytes32);
function activatedScheduleId(uint64 l2Timestamp) external view returns (bytes32);
function getSchedule() external view returns (uint64[] memory);
function __constructor__() external;
}
interfaces/L1/IProxyAdminOwnedBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
interface IProxyAdminOwnedBase {
error ProxyAdminOwnedBase_NotSharedProxyAdminOwner();
error ProxyAdminOwnedBase_NotProxyAdminOwner();
error ProxyAdminOwnedBase_NotProxyAdmin();
error ProxyAdminOwnedBase_NotProxyAdminOrProxyAdminOwner();
error ProxyAdminOwnedBase_ProxyAdminNotFound();
error ProxyAdminOwnedBase_NotResolvedDelegateProxy();
function proxyAdmin() external view returns (IProxyAdmin);
function proxyAdminOwner() external view returns (address);
}
interfaces/L1/IResourceMetering.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IResourceMetering {
struct ResourceParams {
uint128 prevBaseFee;
uint64 prevBoughtGas;
uint64 prevBlockNum;
}
struct ResourceConfig {
uint32 maxResourceLimit;
uint8 elasticityMultiplier;
uint8 baseFeeMaxChangeDenominator;
uint32 minimumBaseFee;
uint32 systemTxMaxGas;
uint128 maximumBaseFee;
}
error OutOfGas();
event Initialized(uint8 version);
function params() external view returns (uint128 prevBaseFee, uint64 prevBoughtGas, uint64 prevBlockNum); // nosemgrep
function __constructor__() external;
}
interfaces/L1/ISuperchainConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
interface ISuperchainConfig is IProxyAdminOwnedBase {
event Paused(address identifier);
event Unpaused(address identifier);
event PauseExtended(address identifier);
error SuperchainConfig_OnlyGuardian();
error SuperchainConfig_OnlyGuardianOrIncidentResponder();
error SuperchainConfig_AlreadyPaused(address identifier);
error SuperchainConfig_NotAlreadyPaused(address identifier);
function guardian() external view returns (address);
function incidentResponder() external view returns (address);
function pause(address _identifier) external;
function unpause(address _identifier) external;
function pausable(address _identifier) external view returns (bool);
function paused() external view returns (bool);
function paused(address _identifier) external view returns (bool);
function expiration(address _identifier) external view returns (uint256);
function extend(address _identifier) external;
function version() external view returns (string memory);
function pauseTimestamps(address) external view returns (uint256);
function pauseExpiry() external view returns (uint256);
function __constructor__(address _guardian, address _incidentResponder) external;
}
interfaces/L1/ISystemConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IResourceMetering } from "interfaces/L1/IResourceMetering.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
interface ISystemConfig is IProxyAdminOwnedBase {
enum UpdateType {
BATCHER,
FEE_SCALARS,
GAS_LIMIT,
UNSAFE_BLOCK_SIGNER,
EIP_1559_PARAMS,
OPERATOR_FEE_PARAMS,
MIN_BASE_FEE,
DA_FOOTPRINT_GAS_SCALAR
}
struct Addresses {
address l1CrossDomainMessenger;
address l1ERC721Bridge;
address l1StandardBridge;
address optimismPortal;
address optimismMintableERC20Factory;
address delayedWETH;
}
error ReinitializableBase_ZeroInitVersion();
error SystemConfig_InvalidFeatureState();
event ConfigUpdate(uint256 indexed version, UpdateType indexed updateType, bytes data);
event FeatureSet(bytes32 indexed feature, bool indexed enabled);
event Initialized(uint8 version);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function BATCH_INBOX_SLOT() external view returns (bytes32);
function L1_CROSS_DOMAIN_MESSENGER_SLOT() external view returns (bytes32);
function L1_ERC_721_BRIDGE_SLOT() external view returns (bytes32);
function L1_STANDARD_BRIDGE_SLOT() external view returns (bytes32);
function OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT() external view returns (bytes32);
function OPTIMISM_PORTAL_SLOT() external view returns (bytes32);
function DELAYED_WETH_SLOT() external view returns (bytes32);
function START_BLOCK_SLOT() external view returns (bytes32);
function UNSAFE_BLOCK_SIGNER_SLOT() external view returns (bytes32);
function VERSION() external view returns (uint256);
function basefeeScalar() external view returns (uint32);
function batchInbox() external view returns (address addr_);
function batcherHash() external view returns (bytes32);
function blobbasefeeScalar() external view returns (uint32);
function disputeGameFactory() external view returns (address addr_);
function gasLimit() external view returns (uint64);
function eip1559Denominator() external view returns (uint32);
function eip1559Elasticity() external view returns (uint32);
function getAddresses() external view returns (Addresses memory);
function initialize(
address _owner,
uint32 _basefeeScalar,
uint32 _blobbasefeeScalar,
bytes32 _batcherHash,
uint64 _gasLimit,
address _unsafeBlockSigner,
IResourceMetering.ResourceConfig memory _config,
address _batchInbox,
Addresses memory _addresses,
uint256 _l2ChainId,
ISuperchainConfig _superchainConfig
)
external;
function initVersion() external view returns (uint8);
function l1CrossDomainMessenger() external view returns (address addr_);
function l1ERC721Bridge() external view returns (address addr_);
function l1StandardBridge() external view returns (address addr_);
function l2ChainId() external view returns (uint256);
function maximumGasLimit() external pure returns (uint64);
function minimumGasLimit() external view returns (uint64);
function operatorFeeConstant() external view returns (uint64);
function operatorFeeScalar() external view returns (uint32);
function minBaseFee() external view returns (uint64);
function daFootprintGasScalar() external view returns (uint16);
function optimismMintableERC20Factory() external view returns (address addr_);
function optimismPortal() external view returns (address addr_);
function delayedWETH() external view returns (address addr_);
function overhead() external view returns (uint256);
function owner() external view returns (address);
function renounceOwnership() external;
function resourceConfig() external view returns (IResourceMetering.ResourceConfig memory);
function scalar() external view returns (uint256);
function setBatcherHash(address _batcher) external;
function setBatcherHash(bytes32 _batcherHash) external;
function setGasConfig(uint256 _overhead, uint256 _scalar) external;
function setGasConfigEcotone(uint32 _basefeeScalar, uint32 _blobbasefeeScalar) external;
function setGasLimit(uint64 _gasLimit) external;
function setOperatorFeeScalars(uint32 _operatorFeeScalar, uint64 _operatorFeeConstant) external;
function setUnsafeBlockSigner(address _unsafeBlockSigner) external;
function setEIP1559Params(uint32 _denominator, uint32 _elasticity) external;
function setMinBaseFee(uint64 _minBaseFee) external;
function setDAFootprintGasScalar(uint16 _daFootprintGasScalar) external;
function startBlock() external view returns (uint256 startBlock_);
function transferOwnership(address newOwner) external; // nosemgrep
function unsafeBlockSigner() external view returns (address addr_);
function version() external pure returns (string memory);
function paused() external view returns (bool);
function superchainConfig() external view returns (ISuperchainConfig);
function guardian() external view returns (address);
function setFeature(bytes32 _feature, bool _enabled) external;
function isFeatureEnabled(bytes32) external view returns (bool);
function isCustomGasToken() external view returns (bool);
function __constructor__() external;
}
interfaces/L1/proofs/IAnchorStateRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IDisputeGame } from "interfaces/L1/proofs/IDisputeGame.sol";
import { IDisputeGameFactory } from "interfaces/L1/proofs/IDisputeGameFactory.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { GameType, Hash, Proposal } from "src/libraries/bridge/Types.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
interface IAnchorStateRegistry is IProxyAdminOwnedBase {
error AnchorStateRegistry_InvalidAnchorGame();
error AnchorStateRegistry_Unauthorized();
error ReinitializableBase_ZeroInitVersion();
event AnchorUpdated(IDisputeGame indexed game);
event DisputeGameBlacklisted(IDisputeGame indexed disputeGame);
event Initialized(uint8 version);
event RespectedGameTypeSet(GameType gameType);
event RetirementTimestampSet(uint256 timestamp);
function initVersion() external view returns (uint8);
function anchorGame() external view returns (IDisputeGame);
function anchors(GameType) external view returns (Hash, uint256);
function blacklistDisputeGame(IDisputeGame _disputeGame) external;
function disputeGameBlacklist(IDisputeGame) external view returns (bool);
function getAnchorRoot() external view returns (Hash, uint256);
function getStartingAnchorRoot() external view returns (Proposal memory);
function disputeGameFinalityDelaySeconds() external view returns (uint256);
function disputeGameFactory() external view returns (IDisputeGameFactory);
function initialize(
ISystemConfig _systemConfig,
IDisputeGameFactory _disputeGameFactory,
Proposal memory _startingAnchorRoot,
GameType _startingRespectedGameType
)
external;
function isGameBlacklisted(IDisputeGame _game) external view returns (bool);
function isGameProper(IDisputeGame _game) external view returns (bool);
function isGameRegistered(IDisputeGame _game) external view returns (bool);
function isGameResolved(IDisputeGame _game) external view returns (bool);
function isGameRespected(IDisputeGame _game) external view returns (bool);
function isGameRetired(IDisputeGame _game) external view returns (bool);
function isGameFinalized(IDisputeGame _game) external view returns (bool);
function isGameClaimValid(IDisputeGame _game) external view returns (bool);
function paused() external view returns (bool);
function respectedGameType() external view returns (GameType);
function retirementTimestamp() external view returns (uint64);
function setAnchorState(IDisputeGame _game) external;
function setRespectedGameType(GameType _gameType) external;
function systemConfig() external view returns (ISystemConfig);
function updateRetirementTimestamp() external;
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__(
uint256 _disputeGameFinalityDelaySeconds
) external;
}
interfaces/L1/proofs/IDelayedWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
interface IDelayedWETH is IProxyAdminOwnedBase {
error ReinitializableBase_ZeroInitVersion();
struct WithdrawalRequest {
uint256 amount;
uint256 timestamp;
}
event Initialized(uint8 version);
fallback() external payable;
receive() external payable;
function initVersion() external view returns (uint8);
function systemConfig() external view returns (ISystemConfig);
function delay() external view returns (uint256);
function hold(address _guy) external;
function hold(address _guy, uint256 _wad) external;
function initialize(ISystemConfig _systemConfig) external;
function recover(uint256 _wad) external;
function unlock(address _guy, uint256 _wad) external;
function withdraw(address _guy, uint256 _wad) external;
function withdrawals(address, address) external view returns (uint256 amount, uint256 timestamp);
function version() external view returns (string memory);
function withdraw(uint256 _wad) external;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address src) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function deposit() external payable;
function totalSupply() external view returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(address src, address dst, uint256 wad) external returns (bool);
function config() external view returns (ISuperchainConfig);
function __constructor__(uint256 _delay) external;
}
interfaces/L1/proofs/IDisputeGame.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IInitializable } from "interfaces/L1/proofs/IInitializable.sol";
import { IAnchorStateRegistry } from "./IAnchorStateRegistry.sol";
import { GameStatus, GameType, Hash } from "src/libraries/bridge/Types.sol";
import { Timestamp, Claim } from "src/libraries/bridge/LibUDT.sol";
interface IDisputeGame is IInitializable {
event Resolved(GameStatus indexed status);
function createdAt() external view returns (Timestamp);
function resolvedAt() external view returns (Timestamp);
function status() external view returns (GameStatus);
function gameType() external view returns (GameType gameType_);
function gameCreator() external pure returns (address creator_);
function rootClaim() external pure returns (Claim rootClaim_);
function l1Head() external pure returns (Hash l1Head_);
function l2SequenceNumber() external pure returns (uint256 l2SequenceNumber_);
function extraData() external pure returns (bytes memory extraData_);
function resolve() external returns (GameStatus status_);
function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_);
function wasRespectedGameTypeWhenCreated() external view returns (bool);
function anchorStateRegistry() external view returns (IAnchorStateRegistry);
}
interfaces/L1/proofs/IDisputeGameFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IDisputeGame } from "interfaces/L1/proofs/IDisputeGame.sol";
import { Hash, GameType } from "src/libraries/bridge/Types.sol";
import { Timestamp, Claim, GameId } from "src/libraries/bridge/LibUDT.sol";
import { IProxyAdminOwnedBase } from "interfaces/L1/IProxyAdminOwnedBase.sol";
import { IReinitializableBase } from "interfaces/universal/IReinitializableBase.sol";
interface IDisputeGameFactory is IProxyAdminOwnedBase, IReinitializableBase {
struct GameSearchResult {
uint256 index;
GameId metadata;
Timestamp timestamp;
Claim rootClaim;
bytes extraData;
}
error GameAlreadyExists(Hash uuid);
error IncorrectBondAmount();
error NoImplementation(GameType gameType);
event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim);
event ImplementationSet(address indexed impl, GameType indexed gameType);
event ImplementationArgsSet(GameType indexed gameType, bytes args);
event InitBondUpdated(GameType indexed gameType, uint256 indexed newBond);
event Initialized(uint8 version);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function create(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
payable
returns (IDisputeGame proxy_);
function createWithInitData(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData,
bytes memory initData
)
external
payable
returns (IDisputeGame proxy_);
function findLatestGames(
GameType _gameType,
uint256 _start,
uint256 _n
)
external
view
returns (GameSearchResult[] memory games_);
function gameAtIndex(uint256 _index)
external
view
returns (GameType gameType_, Timestamp timestamp_, IDisputeGame proxy_);
function gameCount() external view returns (uint256 gameCount_);
function gameArgs(GameType) external view returns (bytes memory);
function gameImpls(GameType) external view returns (IDisputeGame);
function games(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
view
returns (IDisputeGame proxy_, Timestamp timestamp_);
function getGameUUID(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
pure
returns (Hash uuid_);
function initBonds(GameType) external view returns (uint256);
function initialize(address _owner) external;
function owner() external view returns (address);
function renounceOwnership() external;
function setImplementation(GameType _gameType, IDisputeGame _impl) external;
function setImplementation(GameType _gameType, IDisputeGame _impl, bytes calldata _args) external;
function setInitBond(GameType _gameType, uint256 _initBond) external;
function transferOwnership(address newOwner) external; // nosemgrep
function version() external view returns (string memory);
function __constructor__() external;
}
interfaces/L1/proofs/IInitializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IInitializable {
function initialize() external payable;
function initializeWithInitData(bytes calldata initData) external payable;
}
interfaces/L1/proofs/IVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
interface IVerifier {
/// @notice Verifies a proof.
/// @param proofBytes The proof.
/// @param imageId The image ID.
/// @param journal The journal.
/// @return valid Whether the proof is valid.
function verify(bytes calldata proofBytes, bytes32 imageId, bytes32 journal) external view returns (bool);
/// @notice Nullifies the prover to prevent further proof verification.
/// @dev Should only occur if a soundness issue is found.
/// @dev Should only be callable by a proper dispute game.
function nullify() external;
/// @notice Whether this verifier has been nullified.
function nullified() external view returns (bool);
}
interfaces/legacy/IAddressManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IOwnable } from "interfaces/universal/IOwnable.sol";
/// @title IAddressManager
/// @notice Interface for the AddressManager contract.
interface IAddressManager is IOwnable {
event AddressSet(string indexed name, address newAddress, address oldAddress);
function getAddress(string memory _name) external view returns (address);
function setAddress(string memory _name, address _address) external;
function __constructor__() external;
}
interfaces/universal/IOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOwnable
/// @notice Interface for Ownable.
interface IOwnable {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external; // nosemgrep
function __constructor__() external;
}
interfaces/universal/IProxyAdmin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IAddressManager } from "interfaces/legacy/IAddressManager.sol";
interface IProxyAdmin {
enum ProxyType {
ERC1967,
CHUGSPLASH,
RESOLVED
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function addressManager() external view returns (IAddressManager);
function changeProxyAdmin(address payable _proxy, address _newAdmin) external;
function getProxyAdmin(address payable _proxy) external view returns (address);
function getProxyImplementation(address _proxy) external view returns (address);
function implementationName(address) external view returns (string memory);
function isUpgrading() external view returns (bool);
function owner() external view returns (address);
function proxyType(address) external view returns (ProxyType);
function renounceOwnership() external;
function setAddress(string memory _name, address _address) external;
function setAddressManager(IAddressManager _address) external;
function setImplementationName(address _address, string memory _name) external;
function setProxyType(address _address, ProxyType _type) external;
function setUpgrading(bool _upgrading) external;
function transferOwnership(address newOwner) external; // nosemgrep
function upgrade(address payable _proxy, address _implementation) external;
function upgradeAndCall(address payable _proxy, address _implementation, bytes memory _data) external payable;
function __constructor__(address _owner) external;
}
interfaces/universal/IReinitializableBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IReinitializableBase {
error ReinitializableBase_ZeroInitVersion();
function initVersion() external view returns (uint8);
// ReinitializerBase is abstract, so it has no constructor in its interface.
function __constructor__() external;
}
interfaces/universal/ISemver.sol
// 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);
}
lib/solady/src/utils/Clone.sol
// 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))))
}
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// 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)
}
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), 2) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, 2)
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, 1)
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), 2) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
src/libraries/bridge/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
// Libraries
import { GameType, Hash, Claim } from "src/libraries/bridge/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 a supplied bond is not equal to the required bond amount to cover the cost of the interaction.
error IncorrectBondAmount();
////////////////////////////////////////////////////////////////
// `OptimismPortal2` Errors. //
////////////////////////////////////////////////////////////////
/// @notice Thrown when an output root proof is invalid.
error InvalidOutputRootProof();
////////////////////////////////////////////////////////////////
// `AggregateVerifier` Errors //
////////////////////////////////////////////////////////////////
/// @notice Thrown when a dispute game has already been initialized.
error AlreadyInitialized();
/// @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 an action that requires the game to be `IN_PROGRESS` is invoked when
/// the game is not in progress.
error GameNotInProgress();
/// @notice Thrown when resolving a claim that has already been resolved.
error ClaimAlreadyResolved();
/// @notice Thrown when the game is not yet finalized.
error GameNotFinalized();
/// @notice Thrown when the game is not yet resolved.
error GameNotResolved();
/// @notice Thrown when trying to close a game while the system is paused.
error GamePaused();
/// @notice Thrown when the parent game is invalid.
error InvalidParentGame();
/// @notice Thrown when the parent game is not resolved.
error ParentGameNotResolved();
/// @notice Thrown when the game is over.
error GameOver();
/// @notice Thrown when the game is not over.
error GameNotOver();
src/libraries/bridge/LibUDT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
using LibClaim for Claim global;
using LibHash for Hash global;
using LibGameId for GameId global;
using LibTimestamp for Timestamp global;
using LibGameType for GameType global;
/// @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 a proposed output root.
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 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 `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
}
}
}
src/libraries/bridge/Types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
// Libraries
import { Hash, GameType } from "src/libraries/bridge/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 root and the L2 sequence number at which it was generated.
/// @custom:field root The output root.
/// @custom:field l2SequenceNumber The L2 Sequence Number ( e.g. block number / timestamp) at which the root was
/// generated.
struct Proposal {
Hash root;
uint256 l2SequenceNumber;
}
/// @title GameTypes
/// @notice A library that defines the IDs of games that can be played.
library GameTypes {
/// @notice A dispute game type for aggregating results from TEE + ZK verifiers (multiproofs).
GameType internal constant AGGREGATE_VERIFIER = GameType.wrap(621);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 999999,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"ds-test/=lib/solady/lib/ds-test/src/",
"solady/=lib/solady/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.