Verified contractPartialMIT
DelayedWETH
Address0x03e166fb7c8c536bedeb5164fbc28ad57afd4660
- Balance
0 ETH
- Transactions
0
- 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,480,477
- Creation transaction
- 0xfb219f47a2…848e5b422f
29 files
- src/dispute/DelayedWETH.solmain9.23 KB
- interfaces/L1/IBridgeHook.sol571 B
- interfaces/L1/IETHLockbox.sol1.99 KB
- interfaces/L1/IOptimismPortal2.sol6.96 KB
- interfaces/L1/IResourceMetering.sol680 B
- interfaces/L1/ISuperchainConfig.sol1.57 KB
- interfaces/L1/ISystemConfig.sol5.56 KB
- interfaces/dispute/IAnchorStateRegistry.sol3.72 KB
- interfaces/dispute/IDisputeGame.sol1.26 KB
- interfaces/dispute/IDisputeGameFactory.sol2.98 KB
- interfaces/dispute/IInitializable.sol130 B
- interfaces/legacy/IAddressManager.sol521 B
- interfaces/universal/IOwnable.sol686 B
- interfaces/universal/IProxyAdmin.sol1.62 KB
- interfaces/universal/IProxyAdminOwnedBase.sol620 B
- interfaces/universal/IReinitializableBase.sol323 B
- interfaces/universal/ISemver.sol519 B
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol5.65 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol8.31 KB
- src/dispute/lib/LibPosition.sol9.48 KB
- src/dispute/lib/LibUDT.sol9.01 KB
- src/dispute/lib/Types.sol5.95 KB
- src/libraries/BridgeHookTypes.sol2.08 KB
- src/libraries/Constants.sol4.61 KB
- src/libraries/Storage.sol3.47 KB
- src/libraries/Types.sol4.23 KB
- src/universal/ProxyAdminOwnedBase.sol5.07 KB
- src/universal/ReinitializableBase.sol918 B
- src/universal/WETH98.sol6.05 KB
src/dispute/DelayedWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
// Contracts
import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import { WETH98 } from "src/universal/WETH98.sol";
import { ReinitializableBase } from "src/universal/ReinitializableBase.sol";
import { ProxyAdminOwnedBase } from "src/universal/ProxyAdminOwnedBase.sol";
// Interfaces
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
/// @custom:proxied true
/// @title DelayedWETH
/// @notice DelayedWETH is an extension to WETH9 that allows for delayed withdrawals. Accounts must trigger an unlock
/// function before they can withdraw WETH. Accounts must trigger unlock by specifying a sub-account and an
/// amount of WETH to unlock. Accounts can trigger the unlock function at any time, but must wait a delay
/// period before they can withdraw after the unlock function is triggered. DelayedWETH is designed to be used
/// by the DisputeGame contracts where unlock will only be triggered after a dispute is resolved. DelayedWETH
/// is meant to sit behind a proxy contract and has an owner address that can pull WETH from any account and
/// can recover ETH from the contract itself. The owner sets the delay at initialization and can change it
/// afterwards through `setDelay`, within the bounds fixed by the implementation. Variable and function
/// naming vaguely follows the vibe of WETH9. Not the prettiest contract in the world, but it gets the job
/// done.
contract DelayedWETH is Initializable, ProxyAdminOwnedBase, ReinitializableBase, WETH98, ISemver {
/// @notice Represents a withdrawal request.
struct WithdrawalRequest {
uint256 amount;
uint256 timestamp;
}
/// @notice Semantic version.
/// @custom:semver 3.0.0
string public constant version = "3.0.0";
/// @notice Returns a withdrawal request for the given address.
mapping(address => mapping(address => WithdrawalRequest)) public withdrawals;
/// @notice The lowest value that `delay` may be set to.
uint256 internal immutable MIN_DELAY;
/// @notice The highest value that `delay` may be set to.
uint256 internal immutable MAX_DELAY;
/// @custom:legacy
/// @custom:spacer systemConfig
/// @notice Spacer taking up the legacy `systemConfig` address slot.
address private spacer_4_0_20;
/// @notice The ETHLockbox used as the pause identifier.
IETHLockbox public ethLockbox;
/// @notice Withdrawal delay in seconds. An unlocked withdrawal can only be executed once this much
/// time has passed since the unlock. Bounded by `MIN_DELAY` and `MAX_DELAY`.
/// @custom:network-specific
uint256 public delay;
/// @notice Emitted when the withdrawal delay is set.
/// @param delay The new withdrawal delay in seconds.
event DelaySet(uint256 delay);
/// @notice Thrown when the withdrawal delay bounds are zero or inverted.
error DelayedWETH_InvalidDelayBounds();
/// @notice Thrown when a withdrawal delay is outside the configured bounds.
error DelayedWETH_InvalidDelay();
/// @param _minDelay The lowest withdrawal delay a chain may use, in seconds.
/// @param _maxDelay The highest withdrawal delay a chain may use, in seconds.
constructor(uint256 _minDelay, uint256 _maxDelay) ReinitializableBase(2) {
if (_minDelay == 0 || _minDelay > _maxDelay) {
revert DelayedWETH_InvalidDelayBounds();
}
MIN_DELAY = _minDelay;
MAX_DELAY = _maxDelay;
_disableInitializers();
}
/// @notice Initializes the contract. Emits `DelaySet` on every call, including upgrades that
/// pass the current delay back in, so a re-initialization that changes nothing still
/// emits an event carrying the unchanged value.
/// @param _ethLockbox The address of the ETHLockbox contract.
/// @param _delay The withdrawal delay in seconds.
function initialize(IETHLockbox _ethLockbox, uint256 _delay) external reinitializer(initVersion()) {
// Initialization transactions must come from the ProxyAdmin or its owner.
_assertOnlyProxyAdminOrProxyAdminOwner();
// Now perform initialization logic.
ethLockbox = _ethLockbox;
// Set the withdrawal delay. Bounds-checked and emits the same event as the setter.
_setDelay(_delay);
}
/// @notice Returns the lowest value that the withdrawal delay may be set to.
/// @return The minimum withdrawal delay in seconds.
function minDelay() external view returns (uint256) {
return MIN_DELAY;
}
/// @notice Returns the highest value that the withdrawal delay may be set to.
/// @return The maximum withdrawal delay in seconds.
function maxDelay() external view returns (uint256) {
return MAX_DELAY;
}
/// @notice Returns the SuperchainConfig contract.
/// @return ISuperchainConfig The SuperchainConfig contract.
function config() public view returns (ISuperchainConfig) {
return ethLockbox.superchainConfig();
}
/// @notice Allows the ProxyAdmin owner to set the withdrawal delay. The new value applies to
/// every pending withdrawal request, including requests unlocked before the change.
/// @param _delay The new withdrawal delay in seconds.
function setDelay(uint256 _delay) external {
// Only the ProxyAdmin owner can change the withdrawal delay.
_assertOnlyProxyAdminOwner();
_setDelay(_delay);
}
/// @notice Unlocks withdrawals for the sender's account, after a time delay.
/// @param _guy Sub-account to unlock.
/// @param _wad The amount of WETH to unlock.
function unlock(address _guy, uint256 _wad) external {
// Note that the unlock function can be called by any address, but the actual unlocking capability still only
// gives the msg.sender the ability to withdraw from the account. As long as the unlock and withdraw functions
// are called with the proper recipient addresses, this will be safe. Could be made safer by having external
// accounts execute withdrawals themselves but that would have added extra complexity and made DelayedWETH a
// leaky abstraction, so we chose this instead.
WithdrawalRequest storage wd = withdrawals[msg.sender][_guy];
wd.timestamp = block.timestamp;
wd.amount += _wad;
}
/// @notice Withdraws an amount of ETH.
/// @param _wad The amount of ETH to withdraw.
function withdraw(uint256 _wad) public override {
withdraw(msg.sender, _wad);
}
/// @notice Extension to withdrawal, must provide a sub-account to withdraw from.
/// @param _guy Sub-account to withdraw from.
/// @param _wad The amount of WETH to withdraw.
function withdraw(address _guy, uint256 _wad) public {
require(!ethLockbox.paused(), "DelayedWETH: contract is paused");
WithdrawalRequest storage wd = withdrawals[msg.sender][_guy];
require(wd.amount >= _wad, "DelayedWETH: insufficient unlocked withdrawal");
require(wd.timestamp > 0, "DelayedWETH: withdrawal not unlocked");
require(delay != 0, "DelayedWETH: delay not set");
require(wd.timestamp + delay <= block.timestamp, "DelayedWETH: withdrawal delay not met");
wd.amount -= _wad;
super.withdraw(_wad);
}
/// @notice Allows the owner to recover from error cases by pulling ETH out of the contract.
/// @param _wad The amount of WETH to recover.
function recover(uint256 _wad) external {
require(msg.sender == proxyAdminOwner(), "DelayedWETH: not owner");
uint256 amount = _wad < address(this).balance ? _wad : address(this).balance;
(bool success,) = payable(msg.sender).call{ value: amount }(hex"");
require(success, "DelayedWETH: recover failed");
}
/// @notice Allows the owner to recover from error cases by pulling all WETH from a specific owner.
/// @param _guy The address to recover the WETH from.
function hold(address _guy) external {
hold(_guy, balanceOf(_guy));
}
/// @notice Allows the owner to recover from error cases by pulling a specific amount of WETH from a specific owner.
/// @param _guy The address to recover the WETH from.
/// @param _wad The amount of WETH to recover.
function hold(address _guy, uint256 _wad) public {
require(msg.sender == proxyAdminOwner(), "DelayedWETH: not owner");
_allowance[_guy][msg.sender] = _wad;
emit Approval(_guy, msg.sender, _wad);
transferFrom(_guy, msg.sender, _wad);
}
/// @notice Sets the withdrawal delay after checking it against the configured bounds.
/// @param _delay The new withdrawal delay in seconds.
function _setDelay(uint256 _delay) internal {
if (_delay < MIN_DELAY || _delay > MAX_DELAY) {
revert DelayedWETH_InvalidDelay();
}
delay = _delay;
emit DelaySet(_delay);
}
}
interfaces/L1/IBridgeHook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { BridgeHookTypes } from "src/libraries/BridgeHookTypes.sol";
interface IBridgeHook {
function screenDeposit(BridgeHookTypes.Item calldata _item) external returns (bool pass_);
function holdDeposit(BridgeHookTypes.Item calldata _item) external payable;
function screenWithdrawal(
BridgeHookTypes.Item calldata _item,
uint256 _finalizableAt
)
external
returns (bool pass_);
function holdWithdrawal(BridgeHookTypes.Item calldata _item) external payable;
}
interfaces/L1/IETHLockbox.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
import { IOptimismPortal2 } from "interfaces/L1/IOptimismPortal2.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IReinitializableBase } from "interfaces/universal/IReinitializableBase.sol";
interface IETHLockbox is IProxyAdminOwnedBase, ISemver, IReinitializableBase {
error ETHLockbox_Unauthorized();
error ETHLockbox_Paused();
error ETHLockbox_InsufficientBalance();
error ETHLockbox_NoWithdrawalTransactions();
error ETHLockbox_DifferentSuperchainConfig();
event Initialized(uint8 version);
event ETHLocked(IOptimismPortal2 indexed portal, uint256 amount);
event ETHUnlocked(IOptimismPortal2 indexed portal, uint256 amount);
event PortalAuthorized(IOptimismPortal2 indexed portal);
event LockboxAuthorized(IETHLockbox indexed lockbox);
event LiquidityMigrated(IETHLockbox indexed lockbox, uint256 amount);
event LiquidityReceived(IETHLockbox indexed lockbox, uint256 amount);
function initialize(ISuperchainConfig _superchainConfig, IOptimismPortal2[] calldata _portals) external;
function paused() external view returns (bool);
function guardian() external view returns (address);
function authorizedPortals(IOptimismPortal2) external view returns (bool);
function authorizedLockboxes(IETHLockbox) external view returns (bool);
function receiveLiquidity() external payable;
function lockETH() external payable;
function unlockETH(uint256 _value) external;
function authorizePortal(IOptimismPortal2 _portal) external;
function authorizeLockbox(IETHLockbox _lockbox) external;
function migrateLiquidity(IETHLockbox _lockbox) external;
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__() external;
}
interfaces/L1/IOptimismPortal2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Types } from "src/libraries/Types.sol";
import { BridgeHookTypes } from "src/libraries/BridgeHookTypes.sol";
import { GameType } from "src/dispute/lib/LibUDT.sol";
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { IBridgeHook } from "interfaces/L1/IBridgeHook.sol";
interface IOptimismPortal2 is IProxyAdminOwnedBase {
error ContentLengthMismatch();
error EmptyItem();
error InvalidDataRemainder();
error InvalidHeader();
error ReinitializableBase_ZeroInitVersion();
error OptimismPortal_AlreadyFinalized();
error OptimismPortal_BadTarget();
error OptimismPortal_CallPaused();
error OptimismPortal_CalldataTooLarge();
error OptimismPortal_NotAllowedOnCGTMode();
error OptimismPortal_GasEstimation();
error OptimismPortal_GasLimitTooLow();
error OptimismPortal_ImproperDisputeGame();
error OptimismPortal_InvalidDisputeGame();
error OptimismPortal_InvalidMerkleProof();
error OptimismPortal_InvalidOutputRootProof();
error OptimismPortal_InvalidProofTimestamp();
error OptimismPortal_InvalidRootClaim();
error OptimismPortal_MigratingToSameRegistry();
error OptimismPortal_NoReentrancy();
error OptimismPortal_NotUsingInterop();
error OptimismPortal_NotUsingLockbox();
error OptimismPortal_ProofNotOldEnough();
error OptimismPortal_Unproven();
error OptimismPortal_InvalidInteropState();
error OptimismPortal_InvalidLockboxState();
error OptimismPortal_ZeroAddress();
error OptimismPortal_LockboxNotAuthorizedForPortal();
error OptimismPortal_DisputeGameNotInvalidated();
error OptimismPortal_InvalidProofMaturityDelayBounds();
error OptimismPortal_InvalidProofMaturityDelay();
error OutOfGas();
error UnexpectedList();
error UnexpectedString();
event Initialized(uint8 version);
event ETHMigrated(address indexed lockbox, uint256 balance);
event ProofMaturityDelaySecondsSet(uint256 proofMaturityDelaySeconds);
event PortalMigrated(
IETHLockbox oldLockbox,
IETHLockbox newLockbox,
IAnchorStateRegistry oldAnchorStateRegistry,
IAnchorStateRegistry newAnchorStateRegistry
);
event TransactionDeposited(address indexed from, address indexed to, uint256 indexed version, bytes opaqueData);
event WithdrawalFinalized(bytes32 indexed withdrawalHash, bool success);
event WithdrawalProofDeleted(bytes32 indexed withdrawalHash, address indexed proofSubmitter);
event WithdrawalProven(bytes32 indexed withdrawalHash, address indexed from, address indexed to);
event WithdrawalProvenExtension1(bytes32 indexed withdrawalHash, address indexed proofSubmitter);
receive() external payable;
function anchorStateRegistry() external view returns (IAnchorStateRegistry);
function ethLockbox() external view returns (IETHLockbox);
function checkWithdrawal(bytes32 _withdrawalHash, address _proofSubmitter) external view;
function deleteProvenWithdrawal(bytes32 _withdrawalHash, address _proofSubmitter) external;
function depositTransaction(
address _to,
uint256 _value,
uint64 _gasLimit,
bool _isCreation,
bytes memory _data
)
external
payable;
function disputeGameBlacklist(IDisputeGame _disputeGame) external view returns (bool);
function disputeGameFactory() external view returns (IDisputeGameFactory);
function disputeGameFinalityDelaySeconds() external view returns (uint256);
function donateETH() external payable;
function superchainConfig() external view returns (ISuperchainConfig);
function finalizeWithdrawalTransaction(Types.WithdrawalTransaction memory _tx) external;
function finalizeWithdrawalTransactionExternalProof(
Types.WithdrawalTransaction memory _tx,
address _proofSubmitter
)
external;
function finalizedWithdrawals(bytes32) external view returns (bool);
function guardian() external view returns (address);
function initialize(
ISystemConfig _systemConfig,
IAnchorStateRegistry _anchorStateRegistry,
IETHLockbox _ethLockbox,
uint256 _proofMaturityDelaySeconds
)
external;
function initVersion() external view returns (uint8);
function l2Sender() external view returns (address);
function maxProofMaturityDelaySeconds() external view returns (uint256);
function minProofMaturityDelaySeconds() external view returns (uint256);
function migrateLiquidity() external;
function migrateToSharedDisputeGame(IETHLockbox _newLockbox, IAnchorStateRegistry _newAnchorStateRegistry) external;
function minimumGasLimit(uint64 _byteCount) external pure returns (uint64);
function numProofSubmitters(bytes32 _withdrawalHash) external view returns (uint256);
function params() external view returns (uint128 prevBaseFee, uint64 prevBoughtGas, uint64 prevBlockNum); // nosemgrep
function paused() external view returns (bool);
function proofMaturityDelaySeconds() external view returns (uint256);
function proofSubmitters(bytes32, uint256) external view returns (address);
function proveWithdrawalTransaction(
Types.WithdrawalTransaction memory _tx,
uint256 _disputeGameIndex,
Types.OutputRootProof memory _outputRootProof,
bytes[] memory _withdrawalProof
)
external;
function provenWithdrawals(bytes32, address) external view returns (IDisputeGame disputeGameProxy, uint64 timestamp);
function respectedGameType() external view returns (GameType);
function respectedGameTypeUpdatedAt() external view returns (uint64);
function setProofMaturityDelaySeconds(uint256 _proofMaturityDelaySeconds) external;
function systemConfig() external view returns (ISystemConfig);
function version() external pure returns (string memory);
function bridgeHook() external view returns (IBridgeHook);
function setBridgeHook(IBridgeHook _hook) external;
function heldDeposits(bytes32 _id) external view returns (bool);
function heldWithdrawals(bytes32 _id) external view returns (bool);
function completeDepositTransaction(BridgeHookTypes.Item calldata _item) external payable;
function completeWithdrawalTransaction(BridgeHookTypes.Item calldata _item) external payable;
function __constructor__(uint256 _minProofMaturityDelaySeconds, uint256 _maxProofMaturityDelaySeconds) external;
}
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/universal/IProxyAdminOwnedBase.sol";
interface ISuperchainConfig is IProxyAdminOwnedBase {
enum UpdateType {
GUARDIAN
}
event ConfigUpdate(UpdateType indexed updateType, bytes data);
event Initialized(uint8 version);
event Paused(address identifier);
event Unpaused(address identifier);
error SuperchainConfig_OnlyGuardian();
error SuperchainConfig_AlreadyPaused(address identifier);
error SuperchainConfig_NotAlreadyPaused(address identifier);
error ReinitializableBase_ZeroInitVersion();
function guardian() external view returns (address);
function initialize(address _guardian) external;
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 isLocalOrGlobalPaused(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 initVersion() external view returns (uint8);
function __constructor__() 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/universal/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;
address opcm;
}
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 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 OPCM_SLOT() external view returns (bytes32);
function VERSION() external view returns (uint256);
function basefeeScalar() external view returns (uint32);
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,
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 lastUsedOPCM() external view returns (address addr_);
function lastUsedOPCMVersion() external view returns (string memory version_);
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 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/dispute/IAnchorStateRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { GameType, Hash, Proposal } from "src/dispute/lib/Types.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IAnchorStateRegistry is IProxyAdminOwnedBase {
error AnchorStateRegistry_InvalidAnchorGame();
error AnchorStateRegistry_InvalidDisputeGameFinalityDelay();
error AnchorStateRegistry_InvalidDisputeGameFinalityDelayBounds();
error AnchorStateRegistry_Unauthorized();
error ReinitializableBase_ZeroInitVersion();
event AnchorUpdated(IDisputeGame indexed game);
event DisputeGameBlacklisted(IDisputeGame indexed disputeGame);
event DisputeGameFinalityDelaySecondsSet(uint256 disputeGameFinalityDelaySeconds);
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(
IETHLockbox _ethLockbox,
IDisputeGameFactory _disputeGameFactory,
Proposal memory _startingAnchorRoot,
GameType _startingRespectedGameType,
uint256 _disputeGameFinalityDelaySeconds
)
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 maxDisputeGameFinalityDelaySeconds() external view returns (uint256);
function minDisputeGameFinalityDelaySeconds() external view returns (uint256);
function paused() external view returns (bool);
function respectedGameType() external view returns (GameType);
function retirementTimestamp() external view returns (uint64);
function setAnchorState(IDisputeGame _game) external;
function setDisputeGameFinalityDelaySeconds(uint256 _disputeGameFinalityDelaySeconds) external;
function setRespectedGameType(GameType _gameType) external;
function ethLockbox() external view returns (IETHLockbox);
function updateRetirementTimestamp() external;
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__(
uint256 _minDisputeGameFinalityDelaySeconds,
uint256 _maxDisputeGameFinalityDelaySeconds
)
external;
}
interfaces/dispute/IDisputeGame.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IInitializable } from "interfaces/dispute/IInitializable.sol";
import { Timestamp, GameStatus, GameType, Claim, Hash } from "src/dispute/lib/Types.sol";
interface IDisputeGame is IInitializable {
event Resolved(GameStatus indexed status);
function createdAt() external view returns (Timestamp);
function resolvedAt() external view returns (Timestamp);
function status() external view returns (GameStatus);
function gameType() external view returns (GameType gameType_);
function gameCreator() external pure returns (address creator_);
function rootClaim() external pure returns (Claim rootClaim_);
function rootClaimByChainId(uint256 _chainId) 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);
}
interfaces/dispute/IDisputeGameFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { GameId, Timestamp, Claim, Hash, GameType } from "src/dispute/lib/Types.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/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 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/dispute/IInitializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IInitializable {
function initialize() external payable;
}
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);
/// @dev The caller account is not authorized to perform an operation.
error OwnableUnauthorizedAccount(address account);
/// @dev The owner is not a valid owner account. (eg. `address(0)`)
error OwnableInvalidOwner(address owner);
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/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/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/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
* initialization step. This is essential to configure modules that are added through upgrades and that require
* initialization.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
src/dispute/lib/LibPosition.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
using LibPosition for Position global;
/// @notice A `Position` represents a position of a claim within the game tree.
/// @dev This is represented as a "generalized index" where the high-order bit
/// is the level in the tree and the remaining bits is a unique bit pattern, allowing
/// a unique identifier for each node in the tree. Mathematically, it is calculated
/// as 2^{depth} + indexAtDepth.
type Position is uint128;
/// @title LibPosition
/// @notice This library contains helper functions for working with the `Position` type.
library LibPosition {
/// @notice the `MAX_POSITION_BITLEN` is the number of bits that the `Position` type, and the implementation of
/// its behavior within this library, can safely support.
uint8 internal constant MAX_POSITION_BITLEN = 126;
/// @notice Computes a generalized index (2^{depth} + indexAtDepth).
/// @param _depth The depth of the position.
/// @param _indexAtDepth The index at the depth of the position.
/// @return position_ The computed generalized index.
function wrap(uint8 _depth, uint128 _indexAtDepth) internal pure returns (Position position_) {
assembly {
// gindex = 2^{_depth} + _indexAtDepth
position_ := add(shl(_depth, 1), _indexAtDepth)
}
}
/// @notice Pulls the `depth` out of a `Position` type.
/// @param _position The generalized index to get the `depth` of.
/// @return depth_ The `depth` of the `position` gindex.
/// @custom:attribution Solady <https://github.com/Vectorized/Solady>
function depth(Position _position) internal pure returns (uint8 depth_) {
// Return the most significant bit offset, which signifies the depth of the gindex.
assembly {
depth_ := or(depth_, shl(6, lt(0xffffffffffffffff, shr(depth_, _position))))
depth_ := or(depth_, shl(5, lt(0xffffffff, shr(depth_, _position))))
// For the remaining 32 bits, use a De Bruijn lookup.
_position := shr(depth_, _position)
_position := or(_position, shr(1, _position))
_position := or(_position, shr(2, _position))
_position := or(_position, shr(4, _position))
_position := or(_position, shr(8, _position))
_position := or(_position, shr(16, _position))
depth_ := or(
depth_,
byte(
shr(251, mul(_position, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f
)
)
}
}
/// @notice Pulls the `indexAtDepth` out of a `Position` type.
/// The `indexAtDepth` is the left/right index of a position at a specific depth within
/// the binary tree, starting from index 0. For example, at gindex 2, the `depth` = 1
/// and the `indexAtDepth` = 0.
/// @param _position The generalized index to get the `indexAtDepth` of.
/// @return indexAtDepth_ The `indexAtDepth` of the `position` gindex.
function indexAtDepth(Position _position) internal pure returns (uint128 indexAtDepth_) {
// Return bits p_{msb-1}...p_{0}. This effectively pulls the 2^{depth} out of the gindex,
// leaving only the `indexAtDepth`.
uint256 msb = depth(_position);
assembly {
indexAtDepth_ := sub(_position, shl(msb, 1))
}
}
/// @notice Get the left child of `_position`.
/// @param _position The position to get the left position of.
/// @return left_ The position to the left of `position`.
function left(Position _position) internal pure returns (Position left_) {
assembly {
left_ := shl(1, _position)
}
}
/// @notice Get the right child of `_position`
/// @param _position The position to get the right position of.
/// @return right_ The position to the right of `position`.
function right(Position _position) internal pure returns (Position right_) {
assembly {
right_ := or(1, shl(1, _position))
}
}
/// @notice Get the parent position of `_position`.
/// @param _position The position to get the parent position of.
/// @return parent_ The parent position of `position`.
function parent(Position _position) internal pure returns (Position parent_) {
assembly {
parent_ := shr(1, _position)
}
}
/// @notice Get the deepest, right most gindex relative to the `position`. This is equivalent to
/// calling `right` on a position until the maximum depth is reached.
/// @param _position The position to get the relative deepest, right most gindex of.
/// @param _maxDepth The maximum depth of the game.
/// @return rightIndex_ The deepest, right most gindex relative to the `position`.
function rightIndex(Position _position, uint256 _maxDepth) internal pure returns (Position rightIndex_) {
uint256 msb = depth(_position);
assembly {
let remaining := sub(_maxDepth, msb)
rightIndex_ := or(shl(remaining, _position), sub(shl(remaining, 1), 1))
}
}
/// @notice Get the deepest, right most trace index relative to the `position`. This is
/// equivalent to calling `right` on a position until the maximum depth is reached and
/// then finding its index at depth.
/// @param _position The position to get the relative trace index of.
/// @param _maxDepth The maximum depth of the game.
/// @return traceIndex_ The trace index relative to the `position`.
function traceIndex(Position _position, uint256 _maxDepth) internal pure returns (uint256 traceIndex_) {
uint256 msb = depth(_position);
assembly {
let remaining := sub(_maxDepth, msb)
traceIndex_ := sub(or(shl(remaining, _position), sub(shl(remaining, 1), 1)), shl(_maxDepth, 1))
}
}
/// @notice Gets the position of the highest ancestor of `_position` that commits to the same
/// trace index.
/// @param _position The position to get the highest ancestor of.
/// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
function traceAncestor(Position _position) internal pure returns (Position ancestor_) {
// Create a field with only the lowest unset bit of `_position` set.
Position lsb;
assembly {
lsb := and(not(_position), add(_position, 1))
}
// Find the index of the lowest unset bit within the field.
uint256 msb = depth(lsb);
// The highest ancestor that commits to the same trace index is the original position
// shifted right by the index of the lowest unset bit.
assembly {
let a := shr(msb, _position)
// Bound the ancestor to the minimum gindex, 1.
ancestor_ := or(a, iszero(a))
}
}
/// @notice Gets the position of the highest ancestor of `_position` that commits to the same
/// trace index, while still being below `_upperBoundExclusive`.
/// @param _position The position to get the highest ancestor of.
/// @param _upperBoundExclusive The exclusive upper depth bound, used to inform where to stop in order
/// to not escape a sub-tree.
/// @return ancestor_ The highest ancestor of `position` that commits to the same trace index.
function traceAncestorBounded(
Position _position,
uint256 _upperBoundExclusive
)
internal
pure
returns (Position ancestor_)
{
// This function only works for positions that are below the upper bound.
if (_position.depth() <= _upperBoundExclusive) {
assembly {
// Revert with `ClaimAboveSplit()`
mstore(0x00, 0xb34b5c22)
revert(0x1C, 0x04)
}
}
// Grab the global trace ancestor.
ancestor_ = traceAncestor(_position);
// If the ancestor is above or at the upper bound, shift it to be below the upper bound.
// This should be a special case that only covers positions that commit to the final leaf
// in a sub-tree.
if (ancestor_.depth() <= _upperBoundExclusive) {
ancestor_ = ancestor_.rightIndex(_upperBoundExclusive + 1);
}
}
/// @notice Get the move position of `_position`, which is the left child of:
/// 1. `_position` if `_isAttack` is true.
/// 2. `_position | 1` if `_isAttack` is false.
/// @param _position The position to get the relative attack/defense position of.
/// @param _isAttack Whether or not the move is an attack move.
/// @return move_ The move position relative to `position`.
function move(Position _position, bool _isAttack) internal pure returns (Position move_) {
assembly {
move_ := shl(1, or(iszero(_isAttack), _position))
}
}
/// @notice Get the value of a `Position` type in the form of the underlying uint128.
/// @param _position The position to get the value of.
/// @return raw_ The value of the `position` as a uint128 type.
function raw(Position _position) internal pure returns (uint128 raw_) {
assembly {
raw_ := _position
}
}
}
src/dispute/lib/LibUDT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
// Libraries
import { Position } from "src/dispute/lib/LibPosition.sol";
using LibClaim for Claim global;
using LibHash for Hash global;
using LibDuration for Duration global;
using LibClock for Clock global;
using LibGameId for GameId global;
using LibTimestamp for Timestamp global;
using LibVMStatus for VMStatus global;
using LibGameType for GameType global;
/// @notice A `Clock` represents a packed `Duration` and `Timestamp`
/// @dev The packed layout of this type is as follows:
/// ┌────────────┬────────────────┐
/// │ Bits │ Value │
/// ├────────────┼────────────────┤
/// │ [0, 64) │ Duration │
/// │ [64, 128) │ Timestamp │
/// └────────────┴────────────────┘
type Clock is uint128;
/// @title LibClock
/// @notice This library contains helper functions for working with the `Clock` type.
library LibClock {
/// @notice Packs a `Duration` and `Timestamp` into a `Clock` type.
/// @param _duration The `Duration` to pack into the `Clock` type.
/// @param _timestamp The `Timestamp` to pack into the `Clock` type.
/// @return clock_ The `Clock` containing the `_duration` and `_timestamp`.
function wrap(Duration _duration, Timestamp _timestamp) internal pure returns (Clock clock_) {
assembly {
clock_ := or(shl(0x40, _duration), _timestamp)
}
}
/// @notice Pull the `Duration` out of a `Clock` type.
/// @param _clock The `Clock` type to pull the `Duration` out of.
/// @return duration_ The `Duration` pulled out of `_clock`.
function duration(Clock _clock) internal pure returns (Duration duration_) {
// Shift the high-order 64 bits into the low-order 64 bits, leaving only the `duration`.
assembly {
duration_ := shr(0x40, _clock)
}
}
/// @notice Pull the `Timestamp` out of a `Clock` type.
/// @param _clock The `Clock` type to pull the `Timestamp` out of.
/// @return timestamp_ The `Timestamp` pulled out of `_clock`.
function timestamp(Clock _clock) internal pure returns (Timestamp timestamp_) {
// Clean the high-order 192 bits by shifting the clock left and then right again, leaving
// only the `timestamp`.
assembly {
timestamp_ := shr(0xC0, shl(0xC0, _clock))
}
}
/// @notice Get the value of a `Clock` type in the form of the underlying uint128.
/// @param _clock The `Clock` type to get the value of.
/// @return clock_ The value of the `Clock` type as a uint128 type.
function raw(Clock _clock) internal pure returns (uint128 clock_) {
assembly {
clock_ := _clock
}
}
}
/// @notice A `GameId` represents a packed 4 byte game ID, a 8 byte timestamp, and a 20 byte address.
/// @dev The packed layout of this type is as follows:
/// ┌───────────┬───────────┐
/// │ Bits │ Value │
/// ├───────────┼───────────┤
/// │ [0, 32) │ Game Type │
/// │ [32, 96) │ Timestamp │
/// │ [96, 256) │ Address │
/// └───────────┴───────────┘
type GameId is bytes32;
/// @title LibGameId
/// @notice Utility functions for packing and unpacking GameIds.
library LibGameId {
/// @notice Packs values into a 32 byte GameId type.
/// @param _gameType The game type.
/// @param _timestamp The timestamp of the game's creation.
/// @param _gameProxy The game proxy address.
/// @return gameId_ The packed GameId.
function pack(GameType _gameType, Timestamp _timestamp, address _gameProxy) internal pure returns (GameId gameId_) {
assembly {
gameId_ := or(or(shl(224, _gameType), shl(160, _timestamp)), _gameProxy)
}
}
/// @notice Unpacks values from a 32 byte GameId type.
/// @param _gameId The packed GameId.
/// @return gameType_ The game type.
/// @return timestamp_ The timestamp of the game's creation.
/// @return gameProxy_ The game proxy address.
function unpack(GameId _gameId)
internal
pure
returns (GameType gameType_, Timestamp timestamp_, address gameProxy_)
{
assembly {
gameType_ := shr(224, _gameId)
timestamp_ := and(shr(160, _gameId), 0xFFFFFFFFFFFFFFFF)
gameProxy_ := and(_gameId, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
}
/// @notice A claim represents an MPT root representing the state of the fault proof program.
type Claim is bytes32;
/// @title LibClaim
/// @notice This library contains helper functions for working with the `Claim` type.
library LibClaim {
/// @notice Get the value of a `Claim` type in the form of the underlying bytes32.
/// @param _claim The `Claim` type to get the value of.
/// @return claim_ The value of the `Claim` type as a bytes32 type.
function raw(Claim _claim) internal pure returns (bytes32 claim_) {
assembly {
claim_ := _claim
}
}
/// @notice Hashes a claim and a position together.
/// @param _claim A Claim type.
/// @param _position The position of `claim`.
/// @param _challengeIndex The index of the claim being moved against.
/// @return claimHash_ A hash of abi.encodePacked(claim, position|challengeIndex);
function hashClaimPos(
Claim _claim,
Position _position,
uint256 _challengeIndex
)
internal
pure
returns (Hash claimHash_)
{
assembly {
mstore(0x00, _claim)
mstore(0x20, or(shl(128, _position), and(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, _challengeIndex)))
claimHash_ := keccak256(0x00, 0x40)
}
}
}
/// @notice A dedicated duration type.
/// @dev Unit: seconds
type Duration is uint64;
/// @title LibDuration
/// @notice This library contains helper functions for working with the `Duration` type.
library LibDuration {
/// @notice Get the value of a `Duration` type in the form of the underlying uint64.
/// @param _duration The `Duration` type to get the value of.
/// @return duration_ The value of the `Duration` type as a uint64 type.
function raw(Duration _duration) internal pure returns (uint64 duration_) {
assembly {
duration_ := _duration
}
}
}
/// @notice A custom type for a generic hash.
type Hash is bytes32;
/// @title LibHash
/// @notice This library contains helper functions for working with the `Hash` type.
library LibHash {
/// @notice Get the value of a `Hash` type in the form of the underlying bytes32.
/// @param _hash The `Hash` type to get the value of.
/// @return hash_ The value of the `Hash` type as a bytes32 type.
function raw(Hash _hash) internal pure returns (bytes32 hash_) {
assembly {
hash_ := _hash
}
}
}
/// @notice A dedicated timestamp type.
type Timestamp is uint64;
/// @title LibTimestamp
/// @notice This library contains helper functions for working with the `Timestamp` type.
library LibTimestamp {
/// @notice Get the value of a `Timestamp` type in the form of the underlying uint64.
/// @param _timestamp The `Timestamp` type to get the value of.
/// @return timestamp_ The value of the `Timestamp` type as a uint64 type.
function raw(Timestamp _timestamp) internal pure returns (uint64 timestamp_) {
assembly {
timestamp_ := _timestamp
}
}
}
/// @notice A `VMStatus` represents the status of a VM execution.
type VMStatus is uint8;
/// @title LibVMStatus
/// @notice This library contains helper functions for working with the `VMStatus` type.
library LibVMStatus {
/// @notice Get the value of a `VMStatus` type in the form of the underlying uint8.
/// @param _vmstatus The `VMStatus` type to get the value of.
/// @return vmstatus_ The value of the `VMStatus` type as a uint8 type.
function raw(VMStatus _vmstatus) internal pure returns (uint8 vmstatus_) {
assembly {
vmstatus_ := _vmstatus
}
}
}
/// @notice A `GameType` represents the type of game being played.
type GameType is uint32;
/// @title LibGameType
/// @notice This library contains helper functions for working with the `GameType` type.
library LibGameType {
/// @notice Get the value of a `GameType` type in the form of the underlying uint32.
/// @param _gametype The `GameType` type to get the value of.
/// @return gametype_ The value of the `GameType` type as a uint32 type.
function raw(GameType _gametype) internal pure returns (uint32 gametype_) {
assembly {
gametype_ := _gametype
}
}
}
src/dispute/lib/Types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
// Libraries
import {
Position,
Hash,
GameType,
VMStatus,
Timestamp,
Duration,
Clock,
GameId,
Claim,
LibGameId,
LibClock
} from "src/dispute/lib/LibUDT.sol";
/// @notice The current status of the dispute game.
enum GameStatus {
// The game is currently in progress, and has not been resolved.
IN_PROGRESS,
// The game has concluded, and the `rootClaim` was challenged successfully.
CHALLENGER_WINS,
// The game has concluded, and the `rootClaim` could not be contested.
DEFENDER_WINS
}
/// @notice The game's bond distribution type. Games are expected to start in the `UNDECIDED`
/// state, and then choose either `NORMAL` or `REFUND`.
enum BondDistributionMode {
// Bond distribution strategy has not been chosen.
UNDECIDED,
// Bonds should be distributed as normal.
NORMAL,
// Bonds should be refunded to claimants.
REFUND
}
/// @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.
/// When adding a new game type, it must be added to the list returned by clearedGameTypes().
library GameTypes {
/// @dev A dispute game type the uses the cannon vm.
GameType internal constant CANNON = GameType.wrap(0);
/// @dev A permissioned dispute game type that uses the cannon vm.
GameType internal constant PERMISSIONED_CANNON = GameType.wrap(1);
/// @notice A dispute game type that uses the asterisc vm.
GameType internal constant ASTERISC = GameType.wrap(2);
/// @notice A dispute game type that uses the asterisc vm with Kona.
GameType internal constant ASTERISC_KONA = GameType.wrap(3);
/// @notice A dispute game type that uses the cannon vm (Super Roots).
GameType internal constant SUPER_CANNON = GameType.wrap(4);
/// @notice A permissioned dispute game type for Super Roots.
GameType internal constant SUPER_PERMISSIONED = GameType.wrap(5);
/// @notice A dispute game type that uses OP Succinct
GameType internal constant OP_SUCCINCT = GameType.wrap(6);
/// @notice A dispute game type that uses the asterisc vm with Kona (Super Roots).
GameType internal constant SUPER_ASTERISC_KONA = GameType.wrap(7);
/// @notice A dispute game type that uses the cannon vm with Kona.
GameType internal constant CANNON_KONA = GameType.wrap(8);
/// @notice A dispute game type that uses the cannon vm with Kona (Super Roots).
GameType internal constant SUPER_CANNON_KONA = GameType.wrap(9);
/// @notice A dispute game type that uses optimistic + ZK proofs for dispute resolution (Super Roots).
GameType internal constant ZK_DISPUTE_GAME = GameType.wrap(10);
/// @notice A dispute game type with short game duration for testing withdrawals.
/// Not intended for production use.
GameType internal constant FAST = GameType.wrap(254);
/// @notice A dispute game type that uses an alphabet vm.
/// Not intended for production use.
GameType internal constant ALPHABET = GameType.wrap(255);
/// @notice A dispute game type that uses RISC Zero's Kailua
GameType internal constant KAILUA = GameType.wrap(1337);
/// @notice The game types migration clears from a chain's pre-migration DisputeGameFactory.
/// It might include other games than the valid game types an OPCM accepts as
/// it also covers retired types, which are never valid config but may still be
/// registered on an old factory.
function clearedGameTypes() internal pure returns (GameType[] memory types_) {
types_ = new GameType[](7);
types_[0] = CANNON;
types_[1] = PERMISSIONED_CANNON;
types_[2] = CANNON_KONA;
types_[3] = SUPER_CANNON;
types_[4] = SUPER_PERMISSIONED;
types_[5] = SUPER_CANNON_KONA;
types_[6] = ZK_DISPUTE_GAME;
}
/// @notice Returns true if the game type uses super roots.
function isSuperGame(GameType _gameType) internal pure returns (bool) {
uint32 raw = _gameType.raw();
return raw == SUPER_CANNON.raw() || raw == SUPER_PERMISSIONED.raw() || raw == SUPER_ASTERISC_KONA.raw()
|| raw == SUPER_CANNON_KONA.raw() || raw == ZK_DISPUTE_GAME.raw();
}
}
/// @title VMStatuses
/// @notice Named type aliases for the various valid VM status bytes.
library VMStatuses {
/// @notice The VM has executed successfully and the outcome is valid.
VMStatus internal constant VALID = VMStatus.wrap(0);
/// @notice The VM has executed successfully and the outcome is invalid.
VMStatus internal constant INVALID = VMStatus.wrap(1);
/// @notice The VM has panicked.
VMStatus internal constant PANIC = VMStatus.wrap(2);
/// @notice The VM execution is still in progress.
VMStatus internal constant UNFINISHED = VMStatus.wrap(3);
}
/// @title LocalPreimageKey
/// @notice Named type aliases for local `PreimageOracle` key identifiers.
library LocalPreimageKey {
/// @notice The identifier for the L1 head hash.
uint256 internal constant L1_HEAD_HASH = 0x01;
/// @notice The identifier for the starting output root.
uint256 internal constant STARTING_OUTPUT_ROOT = 0x02;
/// @notice The identifier for the disputed output root.
uint256 internal constant DISPUTED_OUTPUT_ROOT = 0x03;
/// @notice The identifier for the disputed L2 block number.
uint256 internal constant DISPUTED_L2_BLOCK_NUMBER = 0x04;
/// @notice The identifier for the chain ID.
uint256 internal constant CHAIN_ID = 0x05;
}
src/libraries/BridgeHookTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BridgeHookTypes
/// @notice Contains the types shared by the OptimismPortal and its bridge hook.
library BridgeHookTypes {
/// @notice Deposit from L1 to L2, or withdrawal from L2 to L1.
enum Direction {
Deposit,
Withdrawal
}
/// @notice The asset an item moves. ERC20 is a token transfer between the standard bridges.
enum Asset {
ETH,
ERC20
}
/// @notice A deposit or withdrawal with the sender, target, values and data recorded by the
/// Portal. Its fields determine its ID, and the full item is emitted when held and
/// supplied again for completion.
/// @custom:field direction Whether the item is a deposit or a withdrawal.
/// @custom:field asset ERC20 when the Portal recognizes a transfer between the standard
/// bridges.
/// @custom:field from For a deposit, the L1 sender, aliased if it is a contract. For a
/// withdrawal, the L2 sender.
/// @custom:field aliased Whether `from` is aliased.
/// @custom:field to Deposit or withdrawal target.
/// @custom:field ethAmount A deposit's msg.value or a withdrawal's value. Zero for a token
/// transfer.
/// @custom:field l2Value ETH value of the L2 call. Deposits only.
/// @custom:field gasLimit Deposit or withdrawal gas limit.
/// @custom:field isCreation Whether the deposit creates a contract.
/// @custom:field data Call or contract creation data. For token transfers, includes the
/// token addresses and amount.
/// @custom:field nonce Deposit counter or withdrawal nonce.
struct Item {
Direction direction;
Asset asset;
address from;
bool aliased;
address to;
uint256 ethAmount;
uint256 l2Value;
uint256 gasLimit;
bool isCreation;
bytes data;
uint256 nonce;
}
}
src/libraries/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Interfaces
import { IResourceMetering } from "interfaces/L1/IResourceMetering.sol";
/// @title Constants
/// @notice Constants is a library for storing constants. Simple! Don't put everything in here, just
/// the stuff used in multiple contracts. Constants that only apply to a single contract
/// should be defined in that contract instead.
library Constants {
/// @notice Special address to be used as the tx origin for gas estimation calls in the
/// OptimismPortal and CrossDomainMessenger calls. You only need to use this address if
/// the minimum gas limit specified by the user is not actually enough to execute the
/// given message and you're attempting to estimate the actual necessary gas limit. We
/// use address(1) because it's the ecrecover precompile and therefore guaranteed to
/// never have any code on any EVM chain.
address internal constant ESTIMATION_ADDRESS = address(1);
/// @notice Value used for the L2 sender storage slot in both the OptimismPortal and the
/// CrossDomainMessenger contracts before an actual sender is set. This value is
/// non-zero to reduce the gas cost of message passing transactions.
address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD;
/// @notice The storage slot that holds the address of a proxy implementation.
/// @dev `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`
bytes32 internal constant PROXY_IMPLEMENTATION_ADDRESS =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @notice The storage slot that holds the address of the owner.
/// @dev `bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)`
bytes32 internal constant PROXY_OWNER_ADDRESS = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice The storage slot that holds the guard address in Safe contracts.
/// @dev `keccak256("guard_manager.guard.address")`
bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @notice The address that represents ether when dealing with ERC20 token addresses.
address internal constant ETHER = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice The address that represents the system caller responsible for L1 attributes
/// transactions.
address internal constant DEPOSITOR_ACCOUNT = 0xDeaDDEaDDeAdDeAdDEAdDEaddeAddEAdDEAd0001;
/// @notice The address used by OPCM to check if the contract is running in a testing
/// environment. This address doesn't have any code on production networks but can be
/// made to have code in tests with cheatcodes.
address internal constant TESTING_ENVIRONMENT_ADDRESS = address(0xbeefcafe);
/// @notice Special constant key for the PermittedProxyDeployment instruction.
string internal constant PERMITTED_PROXY_DEPLOYMENT_KEY = "PermittedProxyDeployment";
/// @notice Special constant value for the PermittedProxyDeployment instruction to permit all
/// contracts to be deployed. Used for initial deployments only.
bytes internal constant PERMIT_ALL_CONTRACTS_INSTRUCTION = bytes("ALL");
/// @notice The L2ToL2CrossDomainMessenger's expiry period on production networks: the interop
/// message expiry window of 7 days plus a day of margin.
uint256 internal constant L2_TO_L2_MESSAGE_EXPIRY_PERIOD = 8 days;
/// @notice Current bundle artifact path for Network Upgrade Transaction bundles.
string internal constant CURRENT_BUNDLE_PATH = "snapshots/upgrades/current-upgrade-bundle.json";
/// @notice Placeholder anchor root historically used for permissioned initial deployments.
bytes32 internal constant PLACEHOLDER_STARTING_ANCHOR_ROOT = bytes32(hex"dead");
/// @notice Returns the default values for the ResourceConfig. These are the recommended values
/// for a production network.
function DEFAULT_RESOURCE_CONFIG() internal pure returns (IResourceMetering.ResourceConfig memory) {
IResourceMetering.ResourceConfig memory config = IResourceMetering.ResourceConfig({
maxResourceLimit: 20_000_000,
elasticityMultiplier: 10,
baseFeeMaxChangeDenominator: 8,
minimumBaseFee: 1 gwei,
systemTxMaxGas: 1_000_000,
maximumBaseFee: type(uint128).max
});
return config;
}
}
src/libraries/Storage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Storage
/// @notice Storage handles reading and writing to arbitrary storage locations
library Storage {
/// @notice Returns an address stored in an arbitrary storage slot.
/// These storage slots decouple the storage layout from
/// solc's automation.
/// @param _slot The storage slot to retrieve the address from.
function getAddress(bytes32 _slot) internal view returns (address addr_) {
assembly {
addr_ := sload(_slot)
}
}
/// @notice Stores an address in an arbitrary storage slot, `_slot`.
/// @param _slot The storage slot to store the address in.
/// @param _address The protocol version to store
/// @dev WARNING! This function must be used cautiously, as it allows for overwriting addresses
/// in arbitrary storage slots.
function setAddress(bytes32 _slot, address _address) internal {
assembly {
sstore(_slot, _address)
}
}
/// @notice Returns a uint256 stored in an arbitrary storage slot.
/// These storage slots decouple the storage layout from
/// solc's automation.
/// @param _slot The storage slot to retrieve the address from.
function getUint(bytes32 _slot) internal view returns (uint256 value_) {
assembly {
value_ := sload(_slot)
}
}
/// @notice Stores a value in an arbitrary storage slot, `_slot`.
/// @param _slot The storage slot to store the address in.
/// @param _value The protocol version to store
/// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
/// in arbitrary storage slots.
function setUint(bytes32 _slot, uint256 _value) internal {
assembly {
sstore(_slot, _value)
}
}
/// @notice Returns a bytes32 stored in an arbitrary storage slot.
/// These storage slots decouple the storage layout from
/// solc's automation.
/// @param _slot The storage slot to retrieve the address from.
function getBytes32(bytes32 _slot) internal view returns (bytes32 value_) {
assembly {
value_ := sload(_slot)
}
}
/// @notice Stores a bytes32 value in an arbitrary storage slot, `_slot`.
/// @param _slot The storage slot to store the address in.
/// @param _value The bytes32 value to store.
/// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
/// in arbitrary storage slots.
function setBytes32(bytes32 _slot, bytes32 _value) internal {
assembly {
sstore(_slot, _value)
}
}
/// @notice Stores a bool value in an arbitrary storage slot, `_slot`.
/// @param _slot The storage slot to store the bool in.
/// @param _value The bool value to store
/// @dev WARNING! This function must be used cautiously, as it allows for overwriting values
/// in arbitrary storage slots.
function setBool(bytes32 _slot, bool _value) internal {
assembly {
sstore(_slot, _value)
}
}
/// @notice Returns a bool stored in an arbitrary storage slot.
/// @param _slot The storage slot to retrieve the bool from.
function getBool(bytes32 _slot) internal view returns (bool value_) {
assembly {
value_ := sload(_slot)
}
}
}
src/libraries/Types.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Types
/// @notice Contains various types used throughout the Optimism contract system.
library Types {
/// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
/// timestamp that the output root is posted. This timestamp is used to verify that the
/// finalization period has passed since the output root was submitted.
/// @custom:field outputRoot Hash of the L2 output.
/// @custom:field timestamp Timestamp of the L1 block that the output root was submitted in.
/// @custom:field l2BlockNumber L2 block number that the output corresponds to.
struct OutputProposal {
bytes32 outputRoot;
uint128 timestamp;
uint128 l2BlockNumber;
}
/// @notice Struct representing the elements that are hashed together to generate an output root
/// which itself represents a snapshot of the L2 state.
/// @custom:field version Version of the output root.
/// @custom:field stateRoot Root of the state trie at the block of this output.
/// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
/// @custom:field latestBlockhash Hash of the block this output was generated from.
struct OutputRootProof {
bytes32 version;
bytes32 stateRoot;
bytes32 messagePasserStorageRoot;
bytes32 latestBlockhash;
}
/// @notice Struct representing an output root with a chain id.
/// @custom:field chainId The chain ID of the L2 chain that the output root commits to.
/// @custom:field root The output root.
struct OutputRootWithChainId {
uint256 chainId;
bytes32 root;
}
/// @notice Struct representing a super root proof.
/// @custom:field version The version of the super root proof.
/// @custom:field timestamp The timestamp of the super root proof.
/// @custom:field outputRoots The output roots that are included in the super root proof.
struct SuperRootProof {
bytes1 version;
uint64 timestamp;
OutputRootWithChainId[] outputRoots;
}
/// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
/// user (as opposed to a system deposit transaction generated by the system).
/// @custom:field from Address of the sender of the transaction.
/// @custom:field to Address of the recipient of the transaction.
/// @custom:field isCreation True if the transaction is a contract creation.
/// @custom:field value Value to send to the recipient.
/// @custom:field mint Amount of ETH to mint.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
/// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
/// @custom:field logIndex Index of the log in the block the transaction was submitted in.
struct UserDepositTransaction {
address from;
address to;
bool isCreation;
uint256 value;
uint256 mint;
uint64 gasLimit;
bytes data;
bytes32 l1BlockHash;
uint256 logIndex;
}
/// @notice Struct representing a withdrawal transaction.
/// @custom:field nonce Nonce of the withdrawal transaction
/// @custom:field sender Address of the sender of the transaction.
/// @custom:field target Address of the recipient of the transaction.
/// @custom:field value Value to send to the recipient.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
struct WithdrawalTransaction {
uint256 nonce;
address sender;
address target;
uint256 value;
uint256 gasLimit;
bytes data;
}
/// @notice Enum representing where the FeeVault withdraws funds to.
/// @custom:value L1 FeeVault withdraws funds to L1.
/// @custom:value L2 FeeVault withdraws funds to L2.
enum WithdrawalNetwork {
L1,
L2
}
}
src/universal/ProxyAdminOwnedBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;
// Libraries
import { Storage } from "src/libraries/Storage.sol";
import { Constants } from "src/libraries/Constants.sol";
// Interfaces
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IAddressManager } from "interfaces/legacy/IAddressManager.sol";
/// @notice Base contract for ProxyAdmin-owned contracts. This contract is used to introspect
/// compatible Proxy contracts so that their ProxyAdmin and ProxyAdmin owner addresses can
/// be retrieved onchain. Existing Proxy contracts don't have these getters, so we need a
/// base contract instead.
/// @dev WARNING: This contract is ONLY designed to be used with either the Optimism Proxy
/// implementation or the Optimism ResolvedDelegateProxy implementation. It is not safe to use
/// this contract with any other proxy implementation.
/// WARNING: Multiple OP Stack chains may share the same ProxyAdmin owner address.
abstract contract ProxyAdminOwnedBase {
/// @notice Thrown when the ProxyAdmin owner of the current contract is not the same as the
/// ProxyAdmin owner of the other Proxy address provided.
error ProxyAdminOwnedBase_NotSharedProxyAdminOwner();
/// @notice Thrown when the caller is not the ProxyAdmin owner.
error ProxyAdminOwnedBase_NotProxyAdminOwner();
/// @notice Thrown when the caller is not the ProxyAdmin.
error ProxyAdminOwnedBase_NotProxyAdmin();
/// @notice Thrown when the caller is not the ProxyAdmin owner or the ProxyAdmin.
error ProxyAdminOwnedBase_NotProxyAdminOrProxyAdminOwner();
/// @notice Thrown when the ProxyAdmin owner of the current contract is not found.
error ProxyAdminOwnedBase_ProxyAdminNotFound();
/// @notice Thrown when the current contract is not a ResolvedDelegateProxy.
error ProxyAdminOwnedBase_NotResolvedDelegateProxy();
/// @notice Getter for the owner of the ProxyAdmin.
function proxyAdminOwner() public view returns (address) {
return proxyAdmin().owner();
}
/// @notice Getter for the ProxyAdmin contract that owns this Proxy contract.
function proxyAdmin() public view returns (IProxyAdmin) {
// First check for a non-zero address in the reserved slot.
address proxyAdminAddress = Storage.getAddress(Constants.PROXY_OWNER_ADDRESS);
if (proxyAdminAddress != address(0)) {
return IProxyAdmin(proxyAdminAddress);
}
// Otherwise, we'll try to read the AddressManager slot.
// First we make sure this is almost certainly a ResolvedDelegateProxy. We only have a
// single ResolvedDelegateProxy and it's for the L1CrossDomainMessenger, so we'll check
// that the storage slot for the mapping at slot 0 returns the string
// "OVM_L1CrossDomainMessenger". We need to use Solidity's rules for how strings are stored
// in storage slots to do this.
if (
Storage.getBytes32(keccak256(abi.encode(address(this), uint256(0))))
!= bytes32(
uint256(bytes32("OVM_L1CrossDomainMessenger"))
| uint256(bytes("OVM_L1CrossDomainMessenger").length * 2)
)
) {
revert ProxyAdminOwnedBase_NotResolvedDelegateProxy();
}
// Ok, now we'll try to read the AddressManager slot.
address addressManagerAddress = Storage.getAddress(keccak256(abi.encode(address(this), uint256(1))));
if (addressManagerAddress != address(0)) {
return IProxyAdmin(IAddressManager(addressManagerAddress).owner());
}
// We should revert here, we couldn't find a non-zero owner address.
revert ProxyAdminOwnedBase_ProxyAdminNotFound();
}
/// @notice Reverts if the ProxyAdmin owner of the current contract is not the same as the
/// ProxyAdmin owner of the other Proxy address provided. Useful asserting that both
/// the current contract and the other Proxy share the same security model.+
function _assertSharedProxyAdminOwner(address _proxy) internal view {
if (proxyAdminOwner() != ProxyAdminOwnedBase(_proxy).proxyAdminOwner()) {
revert ProxyAdminOwnedBase_NotSharedProxyAdminOwner();
}
}
/// @notice Reverts if the caller is not the ProxyAdmin owner.
function _assertOnlyProxyAdminOwner() internal view {
if (proxyAdminOwner() != msg.sender) {
revert ProxyAdminOwnedBase_NotProxyAdminOwner();
}
}
/// @notice Reverts if the caller is not the ProxyAdmin.
function _assertOnlyProxyAdmin() internal view {
if (address(proxyAdmin()) != msg.sender) {
revert ProxyAdminOwnedBase_NotProxyAdmin();
}
}
function _assertOnlyProxyAdminOrProxyAdminOwner() internal view {
if (address(proxyAdmin()) != msg.sender && proxyAdminOwner() != msg.sender) {
revert ProxyAdminOwnedBase_NotProxyAdminOrProxyAdminOwner();
}
}
}
src/universal/ReinitializableBase.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
/// @title ReinitializableBase
/// @notice A base contract for reinitializable contracts that exposes a version number.
abstract contract ReinitializableBase {
/// @notice Thrown when the initialization version is zero.
error ReinitializableBase_ZeroInitVersion();
/// @notice Current initialization version.
uint8 internal immutable INIT_VERSION;
/// @param _initVersion Current initialization version.
constructor(uint8 _initVersion) {
// Sanity check, we should never have a zero init version.
if (_initVersion == 0) revert ReinitializableBase_ZeroInitVersion();
INIT_VERSION = _initVersion;
}
/// @notice Getter for the current initialization version.
/// @return The current initialization version.
function initVersion() public view returns (uint8) {
return INIT_VERSION;
}
}
src/universal/WETH98.sol
// SPDX-License-Identifier: GPL-3.0
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Based on WETH9 by Dapphub.
// Modified by OP Labs.
pragma solidity 0.8.15;
/// @title WETH98
/// @notice WETH98 is a version of WETH9 upgraded for Solidity 0.8.x.
/// Some functions were changed to virtual to allow for overriding in other WETH implementations.
contract WETH98 {
/// @notice Returns the number of decimals the token uses.
/// @return The number of decimals the token uses.
uint8 public constant decimals = 18;
mapping(address => uint256) internal _balanceOf;
mapping(address => mapping(address => uint256)) internal _allowance;
/// @notice Emitted when an approval is made.
/// @param src The address that approved the transfer.
/// @param guy The address that was approved to transfer.
/// @param wad The amount that was approved to transfer.
event Approval(address indexed src, address indexed guy, uint256 wad);
/// @notice Emitted when a transfer is made.
/// @param src The address that transferred the WETH.
/// @param dst The address that received the WETH.
/// @param wad The amount of WETH that was transferred.
event Transfer(address indexed src, address indexed dst, uint256 wad);
/// @notice Emitted when a deposit is made.
/// @param dst The address that deposited the WETH.
/// @param wad The amount of WETH that was deposited.
event Deposit(address indexed dst, uint256 wad);
/// @notice Emitted when a withdrawal is made.
/// @param src The address that withdrew the WETH.
/// @param wad The amount of WETH that was withdrawn.
event Withdrawal(address indexed src, uint256 wad);
/// @notice Pipes to deposit.
receive() external payable {
deposit();
}
/// @notice Pipes to deposit.
fallback() external payable {
deposit();
}
/// @notice Returns the name of the token.
/// @return name_ The name of the token.
function name() external view virtual returns (string memory) {
return "Wrapped Ether";
}
/// @notice Returns the symbol of the token.
/// @return symbol_ The symbol of the token.
function symbol() external view virtual returns (string memory) {
return "WETH";
}
/// @notice Returns the amount of WETH that the spender can transfer on behalf of the owner.
/// @param owner The address that owns the WETH.
/// @param spender The address that is approved to transfer the WETH.
/// @return The amount of WETH that the spender can transfer on behalf of the owner.
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowance[owner][spender];
}
/// @notice Returns the balance of the given address.
/// @param src The address to query the balance of.
/// @return The balance of the given address.
function balanceOf(address src) public view returns (uint256) {
return _balanceOf[src];
}
/// @notice Allows WETH to be deposited by sending ether to the contract.
function deposit() public payable virtual {
_balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
/// @notice Withdraws an amount of ETH.
/// @param wad The amount of ETH to withdraw.
function withdraw(uint256 wad) public virtual {
require(_balanceOf[msg.sender] >= wad);
_balanceOf[msg.sender] -= wad;
payable(msg.sender).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
/// @notice Returns the total supply of WETH.
/// @return The total supply of WETH.
function totalSupply() external view returns (uint256) {
return address(this).balance;
}
/// @notice Approves the given address to transfer the WETH on behalf of the caller.
/// @param guy The address that is approved to transfer the WETH.
/// @param wad The amount that is approved to transfer.
/// @return True if the approval was successful.
function approve(address guy, uint256 wad) public virtual returns (bool) {
_allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
/// @notice Transfers the given amount of WETH to the given address.
/// @param dst The address to transfer the WETH to.
/// @param wad The amount of WETH to transfer.
/// @return True if the transfer was successful.
function transfer(address dst, uint256 wad) external returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
/// @notice Transfers the given amount of WETH from the given address to the given address.
/// @param src The address to transfer the WETH from.
/// @param dst The address to transfer the WETH to.
/// @param wad The amount of WETH to transfer.
/// @return True if the transfer was successful.
function transferFrom(address src, address dst, uint256 wad) public returns (bool) {
require(_balanceOf[src] >= wad);
uint256 senderAllowance = allowance(src, msg.sender);
if (src != msg.sender && senderAllowance != type(uint256).max) {
require(senderAllowance >= wad);
_allowance[src][msg.sender] -= wad;
}
_balanceOf[src] -= wad;
_balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 999999,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-v5/=lib/openzeppelin-contracts-v5/contracts/",
"@rari-capital/solmate/=lib/solmate/",
"@lib-keccak/=lib/lib-keccak/contracts/lib/",
"@solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"safe-contracts/=lib/safe-contracts/contracts/",
"kontrol-cheatcodes/=lib/kontrol-cheatcodes/src/",
"interfaces/=interfaces/",
"lib/lib-keccak/:solady/=lib/lib-keccak/lib/solady/",
"lib/lib-keccak/:solady/=lib/lib-keccak/lib/solady/",
"@solady-test/=lib/lib-keccak/lib/solady/test/",
"erc4626-tests/=lib/openzeppelin-contracts-v5/lib/erc4626-tests/",
"lib-keccak/=lib/lib-keccak/contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v5/=lib/openzeppelin-contracts-v5/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solady/=lib/solady/",
"solmate/=lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.