Verified contractPartialMIT
OPContractsManagerV2
Address0x7d060b2f703c7a32bb0d3775da2e6c4cc0cddd56
- 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, 200 runs
- EVM version
- london
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,480,491
- Creation transaction
- 0x8bdc724520…538a15a07f
51 files
- src/L1/opcm/OPContractsManagerV2.solmain55.81 KB
- interfaces/L1/IBridgeHook.sol571 B
- interfaces/L1/IETHLockbox.sol1.99 KB
- interfaces/L1/IL1CrossDomainMessenger.sol1.41 KB
- interfaces/L1/IL1ERC721Bridge.sol1.73 KB
- interfaces/L1/IL1StandardBridge.sol2.91 KB
- interfaces/L1/IOPContractsManagerStandardValidator.sol4.97 KB
- interfaces/L1/IOptimismPortal2.sol7.22 KB
- interfaces/L1/IResourceMetering.sol680 B
- interfaces/L1/ISuperchainConfig.sol1.57 KB
- interfaces/L1/ISystemConfig.sol5.89 KB
- interfaces/L1/opcm/IOPContractsManagerContainer.sol1.55 KB
- interfaces/L1/opcm/IOPContractsManagerMigrationValidator.sol3.76 KB
- interfaces/L1/opcm/IOPContractsManagerMigrator.sol4.41 KB
- interfaces/L1/opcm/IOPContractsManagerUtils.sol5.39 KB
- interfaces/L1/opcm/IStandardValidatorUtils.sol3.98 KB
- interfaces/cannon/IMIPS64.sol1.22 KB
- interfaces/cannon/IPreimageOracle.sol4.43 KB
- interfaces/dispute/IAnchorStateRegistry.sol3.72 KB
- interfaces/dispute/IBigStepper.sol3.46 KB
- interfaces/dispute/IDelayedWETH.sol2.66 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/ICrossDomainMessenger.sol2.14 KB
- interfaces/universal/IERC721Bridge.sol1.43 KB
- interfaces/universal/IOptimismMintableERC20Factory.sol1.36 KB
- 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
- interfaces/universal/IStandardBridge.sol2.27 KB
- lib/lib-keccak/contracts/lib/LibKeccak.sol18.07 KB
- lib/solady/src/utils/JSONParserLib.sol36.08 KB
- lib/solady/src/utils/LibString.sol51.93 KB
- src/L1/opcm/OPContractsManagerUtilsCaller.sol13.7 KB
- src/L1/opcm/StandardValidatorUtils.sol23.67 KB
- src/cannon/libraries/CannonTypes.sol3.87 KB
- src/dispute/lib/LibPosition.sol9.48 KB
- src/dispute/lib/LibUDT.sol9.01 KB
- src/dispute/lib/Types.sol5.95 KB
- src/libraries/Blueprint.sol10.44 KB
- src/libraries/BridgeHookTypes.sol2.08 KB
- src/libraries/Bytes.sol6.72 KB
- src/libraries/Constants.sol5.65 KB
- src/libraries/DevFeatures.sol4.46 KB
- src/libraries/Features.sol2.59 KB
- src/libraries/SemverComp.sol4.85 KB
- src/libraries/Types.sol4.23 KB
src/L1/opcm/OPContractsManagerV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
// Contracts
import { OPContractsManagerUtilsCaller } from "src/L1/opcm/OPContractsManagerUtilsCaller.sol";
import { IOPContractsManagerMigrator } from "interfaces/L1/opcm/IOPContractsManagerMigrator.sol";
// Libraries
import { Blueprint } from "src/libraries/Blueprint.sol";
import { GameType, GameTypes, Proposal } from "src/dispute/lib/Types.sol";
import { SemverComp } from "src/libraries/SemverComp.sol";
import { Features } from "src/libraries/Features.sol";
import { DevFeatures } from "src/libraries/DevFeatures.sol";
import { Constants } from "src/libraries/Constants.sol";
// Interfaces
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IResourceMetering } from "interfaces/L1/IResourceMetering.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { IAddressManager } from "interfaces/legacy/IAddressManager.sol";
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IOptimismPortal2 as IOptimismPortal } from "interfaces/L1/IOptimismPortal2.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IL1CrossDomainMessenger } from "interfaces/L1/IL1CrossDomainMessenger.sol";
import { IL1ERC721Bridge } from "interfaces/L1/IL1ERC721Bridge.sol";
import { IL1StandardBridge } from "interfaces/L1/IL1StandardBridge.sol";
import { IOptimismMintableERC20Factory } from "interfaces/universal/IOptimismMintableERC20Factory.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { IBridgeHook } from "interfaces/L1/IBridgeHook.sol";
import { IOPContractsManagerContainer } from "interfaces/L1/opcm/IOPContractsManagerContainer.sol";
import { IOPContractsManagerStandardValidator } from "interfaces/L1/IOPContractsManagerStandardValidator.sol";
import { IOPContractsManagerUtils } from "interfaces/L1/opcm/IOPContractsManagerUtils.sol";
/// @title OPContractsManagerV2
/// @notice OPContractsManagerV2 is an enhanced version of OPContractsManager. OPContractsManagerV2
/// provides a simplified, minimized way of handling upgrades and deployments of OP Stack
/// chains. Each official release of the OP Stack contracts is packaged with its own unique
/// instance of OPContractsManagerV2 that handles the state transition for that particular
/// release.
/// @dev When adding a new dispute game type, if your dispute game requires configuration that
/// differs from configuration used by other dispute game types, you will need to add a new
/// configuration struct and then add parsing logic for that struct in the _makeGameArgs
/// function. You will also need to return the correct game implementation in _getGameImpl.
/// @dev When adding a net-new input, simply add the input to FullConfig and add the corresponding
/// logic for loading that input in _loadFullConfig. NOTE that when adding a completely new
/// input, users upgrading an existing chain will need to supply that input in the form of an
/// override as part of the UpgradeInput struct.
/// @dev If you were going to build a V3 of OPCM, you probably want to make this look a lot more
/// like Terraform. The V2 design is trending in the direction of being Terraform-like, but it
/// doesn't quite get there yet in an attempt to be a more incremental improvement over the V1
/// design. Look at _apply, squint, and imagine that it can output an upgrade plan rather than
/// actually executing the upgrade, and then you'll see how it can be improved.
contract OPContractsManagerV2 is ISemver, OPContractsManagerUtilsCaller {
/// @notice Contracts that represent the Superchain system.
struct SuperchainContracts {
ISuperchainConfig superchainConfig;
}
/// @notice Contracts that represent the full chain system.
struct ChainContracts {
ISystemConfig systemConfig;
IProxyAdmin proxyAdmin;
IAddressManager addressManager;
IL1CrossDomainMessenger l1CrossDomainMessenger;
IL1ERC721Bridge l1ERC721Bridge;
IL1StandardBridge l1StandardBridge;
IOptimismPortal optimismPortal;
IETHLockbox ethLockbox;
IOptimismMintableERC20Factory optimismMintableERC20Factory;
IDisputeGameFactory disputeGameFactory;
IAnchorStateRegistry anchorStateRegistry;
IDelayedWETH delayedWETH;
}
/// @notice Full chain management configuration.
struct FullConfig {
// Basic deployment configuration.
string saltMixer;
ISuperchainConfig superchainConfig;
// System role configuration.
address proxyAdminOwner;
address systemConfigOwner;
address unsafeBlockSigner;
address batcher;
// Anchor state configuration.
Proposal startingAnchorRoot;
GameType startingRespectedGameType;
// L2 system configuration.
uint32 basefeeScalar;
uint32 blobBasefeeScalar;
uint64 gasLimit;
uint256 l2ChainId;
IResourceMetering.ResourceConfig resourceConfig;
// Dispute game configuration.
IOPContractsManagerUtils.DisputeGameConfig[] disputeGameConfigs;
// CGT
bool useCustomGasToken;
// Withdrawal timing configuration. Stored per chain on the portal, the
// AnchorStateRegistry and the DelayedWETH, and bounded by the implementations' min/max
// immutables.
uint256 proofMaturityDelaySeconds;
uint256 disputeGameFinalityDelaySeconds;
uint256 withdrawalDelaySeconds;
}
/// @notice Partial input required for an upgrade.
struct UpgradeInput {
ISystemConfig systemConfig;
IOPContractsManagerUtils.DisputeGameConfig[] disputeGameConfigs;
IOPContractsManagerUtils.ExtraInstruction[] extraInstructions;
}
/// @notice Input for upgrading Superchain contracts.
struct SuperchainUpgradeInput {
ISuperchainConfig superchainConfig;
IOPContractsManagerUtils.ExtraInstruction[] extraInstructions;
}
/// @notice Number of dispute game configs a full config must supply.
uint256 internal constant VALID_GAME_TYPE_COUNT = 6;
/// @notice The valid game types, packed low-to-high as six uint32s in the order the dispute
/// game configs must be supplied: CANNON, PERMISSIONED_CANNON, CANNON_KONA,
/// SUPER_PERMISSIONED, SUPER_CANNON_KONA, ZK_DISPUTE_GAME.
uint256 internal constant VALID_GAME_TYPES = 0x0000000a_00000009_00000005_00000008_00000001_00000000;
/// @notice Thrown when the SuperchainConfig needs to be upgraded.
error OPContractsManagerV2_SuperchainConfigNeedsUpgrade();
/// @notice Thrown when an invalid game config is provided.
error OPContractsManagerV2_InvalidGameConfigs();
/// @notice Thrown when an invalid upgrade input is provided.
error OPContractsManagerV2_InvalidUpgradeInput();
/// @notice Thrown when ETHLockbox feature state is inconsistent with loaded contracts.
error OPContractsManagerV2_InvalidEthLockbox();
/// @notice Thrown when an invalid upgrade instruction is provided.
error OPContractsManagerV2_InvalidUpgradeInstruction(string _key);
/// @notice Thrown when duplicate upgrade instruction keys are provided.
error OPContractsManagerV2_DuplicateUpgradeInstruction(string _key);
/// @notice Thrown when a function that must be delegatecalled is called directly.
error OPContractsManagerV2_OnlyDelegateCall();
/// @notice Thrown when a chain attempts to upgrade to custom gas token after initial deployment.
error OPContractsManagerV2_CannotUpgradeToCustomGasToken();
/// @notice Thrown when an invalid upgrade sequence is provided.
error OPContractsManagerV2_InvalidUpgradeSequence(string _lastVersion, string _thisVersion);
/// @notice Thrown when an enabled game type resolves to a zero implementation in the container.
error OPContractsManagerV2_ZeroGameImplementation(GameType _gameType);
/// @notice Thrown when a withdrawal delay in the config is zero.
error OPContractsManagerV2_InvalidDelayConfig();
/// @notice Address of the Standard Validator for this OPCM release.
IOPContractsManagerStandardValidator public immutable opcmStandardValidator;
/// @notice Address of the Migrator contract for this OPCM release.
IOPContractsManagerMigrator public immutable opcmMigrator;
/// @notice Immutable reference to this OPCM contract so that the address of this contract can
/// be used when this contract is DELEGATECALLed.
OPContractsManagerV2 public immutable opcmV2;
/// @notice The version of the OPCM contract.
/// WARNING: OPCM versioning rules differ from other contracts:
/// - Major bump: New required sequential upgrade
/// - Minor bump: Replacement OPCM for same upgrade
/// - Patch bump: Development changes (expected for normal dev work)
/// @custom:semver 10.0.0
function version() public pure returns (string memory) {
return "10.0.0";
}
/// @param _standardValidator The standard validator for this OPCM release.
/// @param _migrator The migrator contract for this OPCM release.
/// @param _utils The utility functions for the OPContractsManager.
constructor(
IOPContractsManagerStandardValidator _standardValidator,
IOPContractsManagerMigrator _migrator,
IOPContractsManagerUtils _utils
)
OPContractsManagerUtilsCaller(_utils)
{
opcmStandardValidator = _standardValidator;
opcmMigrator = _migrator;
opcmV2 = this;
}
///////////////////////////////////////////////////////////////////////////
// PUBLIC CHAIN MANAGEMENT FUNCTIONS //
///////////////////////////////////////////////////////////////////////////
/// @notice Upgrades the Superchain contracts. Currently this is limited to the
/// SuperchainConfig contract, but may eventually expand to include other
/// Superchain-wide contracts.
/// @param _inp The input for the Superchain upgrade.
function upgradeSuperchain(SuperchainUpgradeInput calldata _inp) external returns (SuperchainContracts memory) {
_onlyDelegateCall();
// NOTE: Since this function is very minimal and only upgrades the SuperchainConfig
// contract, not bothering to fully follow the pattern of the normal chain upgrade flow.
// If we expand the scope of this function to add other Superchain-wide contracts, we'll
// probably want to start following a similar pattern to the chain upgrade flow.
// Upgrade the SuperchainConfig.
_upgrade(
IProxyAdmin(_inp.superchainConfig.proxyAdmin()),
address(_inp.superchainConfig),
implementations().superchainConfigImpl,
abi.encodeCall(ISuperchainConfig.initialize, (_inp.superchainConfig.guardian()))
);
// Return the Superchain contracts.
return SuperchainContracts({ superchainConfig: _inp.superchainConfig });
}
/// @notice Deploys a new chain from full config.
/// @param _cfg The full chain deployment configuration.
/// @return The chain contracts.
function deploy(FullConfig memory _cfg) external returns (ChainContracts memory) {
// Include msg.sender in the salt mixer to prevent cross-caller CREATE2 collisions.
string memory saltMixer = string(bytes.concat(bytes20(msg.sender), bytes(_cfg.saltMixer)));
// Deploy is the ONLY place where we allow the "ALL" permission for proxy deployment.
IOPContractsManagerUtils.ExtraInstruction[] memory instructions =
new IOPContractsManagerUtils.ExtraInstruction[](1);
instructions[0] = IOPContractsManagerUtils.ExtraInstruction({
key: Constants.PERMITTED_PROXY_DEPLOYMENT_KEY, data: Constants.PERMIT_ALL_CONTRACTS_INSTRUCTION
});
// Load the chain contracts.
ChainContracts memory cts =
_loadChainContracts(ISystemConfig(address(0)), _cfg.l2ChainId, saltMixer, instructions);
// Execute the deployment.
return _apply(_cfg, cts, true);
}
/// @notice Upgrades a chain based on the upgrade input.
/// @dev This function only performs standard contract upgrades. Interop activation is a
/// one-off migration step handled by OPContractsManagerMigrator.migrate().
/// @param _inp The chain upgrade input.
/// @return The upgraded chain contracts.
function upgrade(UpgradeInput memory _inp) external returns (ChainContracts memory) {
_onlyDelegateCall();
// Sanity check that the SystemConfig isn't address(0). We use address(0) as a special
// value to indicate that this is an initial deployment, so we definitely don't want to
// allow it here.
if (address(_inp.systemConfig) == address(0)) {
revert OPContractsManagerV2_InvalidUpgradeInput();
}
// Assert that the upgrade instructions are valid.
// NOTE for developers: We use the concept of upgrade instructions to help maintain the
// principle that OPCM should be updated at the time that the feature is being developed
// and not again later for "maintenance" work. For example, if you are adding a net-new
// input to the SystemConfig contract, OPCMv1 would require that you also modify the
// UpgradeInput struct to include that input. You would then later need to go back and
// remove the input from the struct in some later upgrade. With OPCMv2, you can simply
// update the _loadFullConfig function to include your new input and have users supply an
// override for that particular upgrade (the upgrade won't work without the override)
// without any need to later come back and remove the input from the struct or ever even
// change the interface of OPCMv2 in the first place.
_assertValidUpgradeInstructions(_inp.extraInstructions);
// Load the chain contracts.
ChainContracts memory cts =
_loadChainContracts(_inp.systemConfig, _inp.systemConfig.l2ChainId(), "salt mixer", _inp.extraInstructions);
// Load the full config.
FullConfig memory cfg = _loadFullConfig(_inp, cts);
// Execute the upgrade.
return _apply(cfg, cts, false);
}
/// @notice Migrates one or more OP Stack chains to use the Super Root dispute games and shared
/// dispute game contracts.
/// @dev WARNING: This is a one-way operation. You cannot easily undo this operation without a
/// smart contract upgrade. Do not call this function unless you are 100% confident that
/// you know what you're doing and that you are prepared to fully execute this migration.
/// You SHOULD NOT CALL THIS FUNCTION IN PRODUCTION unless you are absolutely sure that
/// you know what you are doing.
/// @dev WARNING: Executing this function WILL result in all prior withdrawal proofs being
/// invalidated. Users will have to submit new proofs for their withdrawals in the
/// OptimismPortal contract. THIS IS EXPECTED BEHAVIOR.
/// @dev NOTE: Unlike other functions in OPCM, this is a one-off function used to serve the
/// temporary need to support the interop migration action. It will likely be removed in
/// the near future once interop support is baked more directly into OPCM. It does NOT
/// look or function like all of the other functions in OPCMv2.
/// @param _input The input parameters for the migration.
function migrate(IOPContractsManagerMigrator.MigrateInput calldata _input) public {
_onlyDelegateCall();
// Migration assumes every chain is already on this OPCM's release.
for (uint256 i = 0; i < _input.chainSystemConfigs.length; i++) {
if (!isPermittedMigrateSequence(_input.chainSystemConfigs[i])) {
revert OPContractsManagerV2_InvalidUpgradeSequence(
_input.chainSystemConfigs[i].lastUsedOPCMVersion(), _version()
);
}
}
// Delegatecall to the migrator contract.
(bool success, bytes memory result) =
address(opcmMigrator).delegatecall(abi.encodeCall(IOPContractsManagerMigrator.migrate, (_input)));
if (!success) {
assembly {
revert(add(result, 0x20), mload(result))
}
}
}
///////////////////////////////////////////////////////////////////////////
// INTERNAL CHAIN MANAGEMENT FUNCTIONS //
///////////////////////////////////////////////////////////////////////////
/// @notice Asserts that the upgrade instructions array is valid.
/// @dev Developers don't need to touch this function, modify _isPermittedInstruction instead.
/// @param _extraInstructions The extra upgrade instructions for the chain.
function _assertValidUpgradeInstructions(IOPContractsManagerUtils.ExtraInstruction[] memory _extraInstructions)
internal
view
{
for (uint256 i = 0; i < _extraInstructions.length; i++) {
// Check for duplicate instruction keys. PermittedProxyDeployment is exempt because
// multiple proxy deployments may need to be permitted in a single upgrade.
if (!_isMatchingInstructionByKey(_extraInstructions[i], Constants.PERMITTED_PROXY_DEPLOYMENT_KEY)) {
for (uint256 j = i + 1; j < _extraInstructions.length; j++) {
if (keccak256(bytes(_extraInstructions[i].key)) == keccak256(bytes(_extraInstructions[j].key))) {
revert OPContractsManagerV2_DuplicateUpgradeInstruction(_extraInstructions[i].key);
}
}
}
// Check that the instruction is permitted.
if (!_isPermittedInstruction(_extraInstructions[i])) {
revert OPContractsManagerV2_InvalidUpgradeInstruction(_extraInstructions[i].key);
}
}
}
/// @notice Checks if an upgrade instruction is permitted.
/// @param _instruction The upgrade instruction to check.
/// @return True if the instruction is permitted, false otherwise.
function _isPermittedInstruction(IOPContractsManagerUtils.ExtraInstruction memory _instruction)
internal
view
returns (bool)
{
// NOTE (IMPORTANT FOR DEVELOPERS): You MAY need to allow permitted instructions here for
// your specific upgrade. For example, if you are adding a new contract that needs to be
// deployed you will need to add an allowance so that the proxy can be deployed.
// Allowances MUST always be restricted to one specific upgrade. Here we maintain this
// restriction by checking that the version is less than the NEXT release version. Once
// developers start working on the next release this will automatically become false so
// even if the code is somehow forgotten it will not actually apply to the deployment. Make
// sure to REMOVE the allowance once the upgrade is complete.
// Allow overriding the starting respected game type during upgrades. This is needed when
// disabling the currently-respected game type, since the validation requires the starting
// respected game type to correspond to an enabled game config.
if (_isMatchingInstructionByKey(_instruction, "overrides.cfg.startingRespectedGameType")) {
return true;
}
// Always return false by default.
return false;
}
/// @notice Loads (or builds) the chain contracts from whatever exists.
/// @param _systemConfig The SystemConfig contract.
/// @param _l2ChainId The L2 chain ID.
/// @param _saltMixer The salt mixer for creating new proxies if needed.
/// @param _extraInstructions The extra upgrade instructions for the chain.
/// @return The chain contracts.
function _loadChainContracts(
ISystemConfig _systemConfig,
uint256 _l2ChainId,
string memory _saltMixer,
IOPContractsManagerUtils.ExtraInstruction[] memory _extraInstructions
)
internal
returns (ChainContracts memory)
{
// If the systemConfig is not initialized, we assume that the entire chain is new.
bool isInitialDeployment = address(_systemConfig) == address(0);
// ProxyAdmin, AddressManager, and SystemConfig are the three special cases where we handle
// them differently than everything else because they're fundamental. Without these three
// contracts we can't get anything else.
IProxyAdmin proxyAdmin;
IAddressManager addressManager;
ISystemConfig systemConfig;
if (isInitialDeployment) {
// Deploy the ProxyAdmin.
proxyAdmin = IProxyAdmin(
Blueprint.deployFrom(
blueprints().proxyAdmin,
_computeSalt(_l2ChainId, _saltMixer, "ProxyAdmin"),
abi.encode(address(this))
)
);
// Deploy the AddressManager.
addressManager = IAddressManager(
Blueprint.deployFrom(
blueprints().addressManager, _computeSalt(_l2ChainId, _saltMixer, "AddressManager"), abi.encode()
)
);
// Set the AddressManager on the ProxyAdmin.
proxyAdmin.setAddressManager(addressManager);
// Transfer ownership of the AddressManager to the ProxyAdmin.
addressManager.transferOwnership(address(proxyAdmin));
// Deploy the SystemConfig.
systemConfig = ISystemConfig(
Blueprint.deployFrom(
blueprints().proxy,
_computeSalt(_l2ChainId, _saltMixer, "SystemConfig"),
abi.encode(address(proxyAdmin))
)
);
} else {
// Load-or-deploy pattern just generally doesn't make a lot of sense here. You could
// theoretically do it, but not worth the complexity. Having this special handling for
// how we load these three contracts is just cleaner/simpler.
proxyAdmin = _systemConfig.proxyAdmin();
addressManager = proxyAdmin.addressManager();
systemConfig = _systemConfig;
}
// Set up the deploy args once, keeps the code cleaner.
IOPContractsManagerUtils.ProxyDeployArgs memory proxyDeployArgs = IOPContractsManagerUtils.ProxyDeployArgs({
proxyAdmin: proxyAdmin, addressManager: addressManager, l2ChainId: _l2ChainId, saltMixer: _saltMixer
});
// Now also load the portal, which contains the last few contract references. We do this
// before we set up the rest of the struct so we can reference it.
IOptimismPortal optimismPortal = IOptimismPortal(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.optimismPortal.selector,
proxyDeployArgs,
"OptimismPortal",
_extraInstructions
)
);
// Load or deploy the ETHLockbox.
IETHLockbox ethLockbox = IETHLockbox(
_loadOrDeployProxy(
address(optimismPortal),
optimismPortal.ethLockbox.selector,
proxyDeployArgs,
"ETHLockbox",
_extraInstructions
)
);
// For every other contract, we load-or-build the proxy. Each contract has a theoretical
// source where the address would be found. If the address isn't found there, we assume the
// address needs to be constructed.
// NOTE: We call _loadOrDeployProxy for each contract (rather than iterating over some sort
// of array) because (1) it's far easier to implement in Solidity and (2) it makes the code
// easier to understand.
return ChainContracts({
systemConfig: systemConfig,
proxyAdmin: proxyAdmin,
addressManager: addressManager,
optimismPortal: optimismPortal,
ethLockbox: ethLockbox,
l1CrossDomainMessenger: IL1CrossDomainMessenger(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.l1CrossDomainMessenger.selector,
proxyDeployArgs,
"L1CrossDomainMessenger",
_extraInstructions
)
),
l1ERC721Bridge: IL1ERC721Bridge(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.l1ERC721Bridge.selector,
proxyDeployArgs,
"L1ERC721Bridge",
_extraInstructions
)
),
l1StandardBridge: IL1StandardBridge(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.l1StandardBridge.selector,
proxyDeployArgs,
"L1StandardBridge",
_extraInstructions
)
),
optimismMintableERC20Factory: IOptimismMintableERC20Factory(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.optimismMintableERC20Factory.selector,
proxyDeployArgs,
"OptimismMintableERC20Factory",
_extraInstructions
)
),
disputeGameFactory: IDisputeGameFactory(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.disputeGameFactory.selector,
proxyDeployArgs,
"DisputeGameFactory",
_extraInstructions
)
),
anchorStateRegistry: IAnchorStateRegistry(
_loadOrDeployProxy(
address(optimismPortal),
optimismPortal.anchorStateRegistry.selector,
proxyDeployArgs,
"AnchorStateRegistry",
_extraInstructions
)
),
delayedWETH: IDelayedWETH(
_loadOrDeployProxy(
address(systemConfig),
systemConfig.delayedWETH.selector,
proxyDeployArgs,
"DelayedWETH",
_extraInstructions
)
)
});
}
/// @notice Loads the full config from the upgrade input.
/// @param _upgradeInput The upgrade input.
/// @param _chainContracts The chain contracts.
/// @return The full config.
function _loadFullConfig(
UpgradeInput memory _upgradeInput,
ChainContracts memory _chainContracts
)
internal
view
returns (FullConfig memory)
{
// Load the full config.
return FullConfig({
disputeGameConfigs: _upgradeInput.disputeGameConfigs,
saltMixer: string(bytes.concat(bytes32(uint256(uint160(address(_chainContracts.systemConfig)))))),
superchainConfig: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.superchainConfig.selector,
"overrides.cfg.superchainConfig",
_upgradeInput.extraInstructions
),
(ISuperchainConfig)
),
proxyAdminOwner: abi.decode(
_loadBytes(
address(_chainContracts.optimismPortal),
_chainContracts.optimismPortal.proxyAdminOwner.selector,
"overrides.cfg.proxyAdminOwner",
_upgradeInput.extraInstructions
),
(address)
),
systemConfigOwner: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.owner.selector,
"overrides.cfg.systemConfigOwner",
_upgradeInput.extraInstructions
),
(address)
),
unsafeBlockSigner: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.unsafeBlockSigner.selector,
"overrides.cfg.unsafeBlockSigner",
_upgradeInput.extraInstructions
),
(address)
),
batcher: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.batcherHash.selector,
"overrides.cfg.batcher",
_upgradeInput.extraInstructions
),
(address)
),
basefeeScalar: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.basefeeScalar.selector,
"overrides.cfg.basefeeScalar",
_upgradeInput.extraInstructions
),
(uint32)
),
blobBasefeeScalar: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.blobbasefeeScalar.selector,
"overrides.cfg.blobBasefeeScalar",
_upgradeInput.extraInstructions
),
(uint32)
),
gasLimit: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.gasLimit.selector,
"overrides.cfg.gasLimit",
_upgradeInput.extraInstructions
),
(uint64)
),
l2ChainId: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.l2ChainId.selector,
"overrides.cfg.l2ChainId",
_upgradeInput.extraInstructions
),
(uint256)
),
resourceConfig: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.resourceConfig.selector,
"overrides.cfg.resourceConfig",
_upgradeInput.extraInstructions
),
(IResourceMetering.ResourceConfig)
),
startingAnchorRoot: abi.decode(
_loadBytes(
address(_chainContracts.anchorStateRegistry),
_chainContracts.anchorStateRegistry.getStartingAnchorRoot.selector,
"overrides.cfg.startingAnchorRoot",
_upgradeInput.extraInstructions
),
(Proposal)
),
startingRespectedGameType: abi.decode(
_loadBytes(
address(_chainContracts.anchorStateRegistry),
_chainContracts.anchorStateRegistry.respectedGameType.selector,
"overrides.cfg.startingRespectedGameType",
_upgradeInput.extraInstructions
),
(GameType)
),
useCustomGasToken: abi.decode(
_loadBytes(
address(_chainContracts.systemConfig),
_chainContracts.systemConfig.isCustomGasToken.selector,
"overrides.cfg.useCustomGasToken",
_upgradeInput.extraInstructions
),
(bool)
),
// NOTE: The delays are read before any implementation is swapped, so on the first upgrade
// to a release with per-chain delays they return the legacy immutable values from the same selectors, which
// are then carried forward into proxy storage. The keys are deliberately not
// allow-listed in _isPermittedInstruction. An upgrade always leaves the live values
// which can only be changed by the L1PAO setters.
proofMaturityDelaySeconds: abi.decode(
_loadBytes(
address(_chainContracts.optimismPortal),
_chainContracts.optimismPortal.proofMaturityDelaySeconds.selector,
"overrides.cfg.proofMaturityDelaySeconds",
_upgradeInput.extraInstructions
),
(uint256)
),
disputeGameFinalityDelaySeconds: abi.decode(
_loadBytes(
address(_chainContracts.anchorStateRegistry),
_chainContracts.anchorStateRegistry.disputeGameFinalityDelaySeconds.selector,
"overrides.cfg.disputeGameFinalityDelaySeconds",
_upgradeInput.extraInstructions
),
(uint256)
),
withdrawalDelaySeconds: abi.decode(
_loadBytes(
address(_chainContracts.delayedWETH),
_chainContracts.delayedWETH.delay.selector,
"overrides.cfg.withdrawalDelaySeconds",
_upgradeInput.extraInstructions
),
(uint256)
)
});
}
/// @notice Validates the deployment/upgrade config.
/// @param _cfg The full config.
/// @param _isInitialDeployment Whether or not this is an initial deployment.
function _assertValidFullConfig(FullConfig memory _cfg, bool _isInitialDeployment) internal view {
// We must have a config for each valid game type.
if (_cfg.disputeGameConfigs.length != VALID_GAME_TYPE_COUNT) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
// An initial anchor must have a nonzero root and leave room for a uint64 successor.
if (
_isInitialDeployment
&& (_cfg.startingAnchorRoot.root.raw() == bytes32(0)
|| _cfg.startingAnchorRoot.l2SequenceNumber >= type(uint64).max)
) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
// Withdrawal delays must be set. Bounds are enforced by the implementations' initializers
// so that the bounds live in exactly one place.
if (
_cfg.proofMaturityDelaySeconds == 0 || _cfg.disputeGameFinalityDelaySeconds == 0
|| _cfg.withdrawalDelaySeconds == 0
) {
revert OPContractsManagerV2_InvalidDelayConfig();
}
bool superRootGamesMigrationEnabled = isDevFeatureEnabled(DevFeatures.SUPER_ROOT_GAMES_MIGRATION);
// Iterate over each provided config and confirm that it matches the expected game type.
// This places a requirement on the user to order the configs properly but that's
// probably a good thing, keeps the config consistent.
for (uint256 i = 0; i < _cfg.disputeGameConfigs.length; i++) {
uint32 rawGameType = uint32(VALID_GAME_TYPES >> (i * 32));
bool isCannonGame = rawGameType == GameTypes.CANNON.raw();
bool isPermissionedCannonGame = rawGameType == GameTypes.PERMISSIONED_CANNON.raw();
bool isCannonKonaGame = rawGameType == GameTypes.CANNON_KONA.raw();
bool isSuperPermissionedGame = rawGameType == GameTypes.SUPER_PERMISSIONED.raw();
bool isSuperCannonKonaGame = rawGameType == GameTypes.SUPER_CANNON_KONA.raw();
bool isZkDisputeGame = rawGameType == GameTypes.ZK_DISPUTE_GAME.raw();
if (_cfg.disputeGameConfigs[i].gameType.raw() != rawGameType) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
// Init bond validation, folded into one check:
// 1. A disabled game must have a 0 init bond.
// 2. SUPER_PERMISSIONED must have a 0 init bond, it never uses bonds.
// 3. An enabled game other than SUPER_PERMISSIONED must have a non-zero init bond.
// The two ways to violate it:
// usesBond == true && initBond == 0 -> check 3
// usesBond == false && initBond != 0 -> checks 1, 2
bool usesBond = _cfg.disputeGameConfigs[i].enabled && !isSuperPermissionedGame;
if (usesBond == (_cfg.disputeGameConfigs[i].initBond == 0)) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
// Initial deployments must select game types compatible with the active mode.
// Upgrade inputs define their game types. Super root migration removes output root support.
// DeployOPChain adds the permissioned fallback. StandardValidator checks it. OPCM does not require it.
bool validForInitialDeploy = superRootGamesMigrationEnabled
? (isSuperPermissionedGame || isSuperCannonKonaGame)
: (isPermissionedCannonGame || isCannonKonaGame);
if (_isInitialDeployment && _cfg.disputeGameConfigs[i].enabled && !validForInitialDeploy) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
if (_cfg.disputeGameConfigs[i].enabled && (isCannonGame || isCannonKonaGame || isSuperCannonKonaGame)) {
if (
_isInitialDeployment
&& _cfg.startingAnchorRoot.root.raw() == Constants.PLACEHOLDER_STARTING_ANCHOR_ROOT
) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
// If a permissionless game is being enabled the prestate must be not empty, otherwise revert.
IOPContractsManagerUtils.FaultDisputeGameConfig memory faultGameConfig =
abi.decode(_cfg.disputeGameConfigs[i].gameArgs, (IOPContractsManagerUtils.FaultDisputeGameConfig));
if (faultGameConfig.absolutePrestate.raw() == bytes32(0)) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
}
// The ZK game is permissionless too. Its absolute prestate is the verification key, and
// its durations and challenger bond bound the challenge game, so reject configs that
// make it unplayable or trivially winnable.
if (_cfg.disputeGameConfigs[i].enabled && isZkDisputeGame) {
if (!_isValidZKDisputeGameConfig(_cfg.disputeGameConfigs[i].gameArgs)) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
}
}
// Validate that the starting respected game type corresponds to an enabled game config.
bool startingGameTypeFound = false;
for (uint256 i = 0; i < _cfg.disputeGameConfigs.length; i++) {
if (
_cfg.disputeGameConfigs[i].gameType.raw() == _cfg.startingRespectedGameType.raw()
&& _cfg.disputeGameConfigs[i].enabled
) {
startingGameTypeFound = true;
break;
}
}
if (!startingGameTypeFound) {
revert OPContractsManagerV2_InvalidGameConfigs();
}
}
/// @notice Executes the deployment/upgrade action.
/// @param _cfg The full config.
/// @param _cts The chain contracts.
/// @param _isInitialDeployment Whether or not this is an initial deployment.
/// @return The chain contracts.
function _apply(
FullConfig memory _cfg,
ChainContracts memory _cts,
bool _isInitialDeployment
)
internal
returns (ChainContracts memory)
{
// Validate the config.
_assertValidFullConfig(_cfg, _isInitialDeployment);
// Load the implementations.
IOPContractsManagerContainer.Implementations memory impls = implementations();
// Make sure the provided SuperchainConfig is up to date.
if (SemverComp.lt(_cfg.superchainConfig.version(), ISuperchainConfig(impls.superchainConfigImpl).version())) {
revert OPContractsManagerV2_SuperchainConfigNeedsUpgrade();
}
// Chains prior to OPCMv2 don't yet have a functional lastUsedOPCMVersion function on the
// SystemConfig contract. The first deployment of OPCMv2 will make this function available
// and subsequent deployments will then use this function to verify the system is
// progressing from one OPCM to the next. We only care about this for upgrades, you can
// perform an initial deployment from any OPCM.
if (!_isInitialDeployment && !isPermittedUpgradeSequence(_cts.systemConfig)) {
revert OPContractsManagerV2_InvalidUpgradeSequence(_cts.systemConfig.lastUsedOPCMVersion(), _version());
}
// Update the SystemConfig.
_upgrade(
_cts.proxyAdmin,
address(_cts.systemConfig),
impls.systemConfigImpl,
_encodeSystemConfigInit(
SystemConfigInitArgs({
owner: _cfg.systemConfigOwner,
basefeeScalar: _cfg.basefeeScalar,
blobbasefeeScalar: _cfg.blobBasefeeScalar,
batcherHash: bytes32(uint256(uint160(_cfg.batcher))),
gasLimit: _cfg.gasLimit,
unsafeBlockSigner: _cfg.unsafeBlockSigner,
resourceConfig: _cfg.resourceConfig,
addrs: ISystemConfig.Addresses({
l1CrossDomainMessenger: address(_cts.l1CrossDomainMessenger),
l1ERC721Bridge: address(_cts.l1ERC721Bridge),
l1StandardBridge: address(_cts.l1StandardBridge),
optimismPortal: address(_cts.optimismPortal),
optimismMintableERC20Factory: address(_cts.optimismMintableERC20Factory),
delayedWETH: address(_cts.delayedWETH),
opcm: address(opcmV2)
}),
l2ChainId: _cfg.l2ChainId,
superchainConfig: _cfg.superchainConfig
})
)
);
// Enable ETHLockbox before updating the portal.
bool wasEthLockboxEnabled = _cts.systemConfig.isFeatureEnabled(Features.ETH_LOCKBOX);
// The flag can be enabled without a configured lockbox. Check the old portal before
// reinitializing it, but skip the getter on initial deployments where it is not initialized.
bool wasUsingEthLockbox =
!_isInitialDeployment && wasEthLockboxEnabled && address(_cts.optimismPortal.ethLockbox()) != address(0);
if (address(_cts.ethLockbox) == address(0)) {
revert OPContractsManagerV2_InvalidEthLockbox();
}
if (!wasEthLockboxEnabled) {
_cts.systemConfig.setFeature(Features.ETH_LOCKBOX, true);
}
// Update the OptimismPortal.
// TODO(optimism-private#744): A zero bridge hook keeps the portal's current hook; the OPCM
// does not configure hooks yet.
_upgrade(
_cts.proxyAdmin,
address(_cts.optimismPortal),
impls.optimismPortalImpl,
abi.encodeCall(
IOptimismPortal.initialize,
(
_cts.systemConfig,
_cts.anchorStateRegistry,
_cts.ethLockbox,
_cfg.proofMaturityDelaySeconds,
IBridgeHook(address(0))
)
)
);
// NOTE: Same general pattern, we call _upgrade for each contract rather than
// iterating over some sort of array because it's easier to implement and understand.
// Update the ETHLockbox.
IOptimismPortal[] memory portals = new IOptimismPortal[](1);
portals[0] = _cts.optimismPortal;
_upgrade(
_cts.proxyAdmin,
address(_cts.ethLockbox),
impls.ethLockboxImpl,
abi.encodeCall(IETHLockbox.initialize, (_cts.systemConfig.superchainConfig(), portals))
);
// Custom gas token chains keep custody in the portal and do not migrate ETH.
if (!wasUsingEthLockbox && !_cfg.useCustomGasToken) {
_cts.optimismPortal.migrateLiquidity();
}
// Update the L1CrossDomainMessenger.
// NOTE: L1CrossDomainMessenger initializer is at slot 0, offset 20.
_upgrade(
_cts.proxyAdmin,
address(_cts.l1CrossDomainMessenger),
impls.l1CrossDomainMessengerImpl,
abi.encodeCall(IL1CrossDomainMessenger.initialize, (_cts.systemConfig, _cts.optimismPortal)),
bytes32(0),
20
);
// Update the L1StandardBridge.
_upgrade(
_cts.proxyAdmin,
address(_cts.l1StandardBridge),
impls.l1StandardBridgeImpl,
abi.encodeCall(IL1StandardBridge.initialize, (_cts.l1CrossDomainMessenger, _cts.systemConfig))
);
// Update the L1ERC721Bridge.
_upgrade(
_cts.proxyAdmin,
address(_cts.l1ERC721Bridge),
impls.l1ERC721BridgeImpl,
abi.encodeCall(IL1ERC721Bridge.initialize, (_cts.l1CrossDomainMessenger, _cts.systemConfig))
);
// Update the OptimismMintableERC20Factory.
_upgrade(
_cts.proxyAdmin,
address(_cts.optimismMintableERC20Factory),
impls.optimismMintableERC20FactoryImpl,
abi.encodeCall(IOptimismMintableERC20Factory.initialize, (address(_cts.l1StandardBridge)))
);
// Update the DisputeGameFactory.
_upgrade(
_cts.proxyAdmin,
address(_cts.disputeGameFactory),
impls.disputeGameFactoryImpl,
abi.encodeCall(IDisputeGameFactory.initialize, (address(this)))
);
// Update the DelayedWETH.
_upgrade(
_cts.proxyAdmin,
address(_cts.delayedWETH),
impls.delayedWETHImpl,
abi.encodeCall(IDelayedWETH.initialize, (_cts.ethLockbox, _cfg.withdrawalDelaySeconds))
);
// Update the AnchorStateRegistry.
_upgrade(
_cts.proxyAdmin,
address(_cts.anchorStateRegistry),
impls.anchorStateRegistryImpl,
abi.encodeCall(
IAnchorStateRegistry.initialize,
(
_cts.ethLockbox,
_cts.disputeGameFactory,
_cfg.startingAnchorRoot,
_cfg.startingRespectedGameType,
_cfg.disputeGameFinalityDelaySeconds
)
)
);
// Update the DisputeGame config and implementations.
// NOTE: We assert in _assertValidFullConfig that we have a configuration for all valid game
// types so we can be confident that we're setting/unsetting everything we care about.
for (uint256 i = 0; i < _cfg.disputeGameConfigs.length; i++) {
// Game implementation and arguments default to empty values. If the game is disabled,
// we'll use these empty values to unset the game in the factory.
IDisputeGame gameImpl = IDisputeGame(address(0));
bytes memory gameArgs = bytes("");
// If the game is enabled, grab the implementation and craft the game arguments.
if (_cfg.disputeGameConfigs[i].enabled) {
gameImpl = _getGameImpl(_cfg.disputeGameConfigs[i].gameType);
if (address(gameImpl) == address(0) || address(gameImpl).code.length == 0) {
revert OPContractsManagerV2_ZeroGameImplementation(_cfg.disputeGameConfigs[i].gameType);
}
gameArgs = _makeGameArgs(
_cfg.l2ChainId, _cts.anchorStateRegistry, _cts.delayedWETH, _cfg.disputeGameConfigs[i]
);
}
// Set the game implementation and arguments.
// NOTE: If the game is disabled, we'll set the implementation to address(0) and the
// arguments to bytes(""), disabling the game.
_cts.disputeGameFactory.setImplementation(_cfg.disputeGameConfigs[i].gameType, gameImpl, gameArgs);
_cts.disputeGameFactory
.setInitBond(_cfg.disputeGameConfigs[i].gameType, _cfg.disputeGameConfigs[i].initBond);
}
// SUPER_CANNON has been retired from OPCMv2's deploy/upgrade allow-list. Some chains may
// still have a non-zero gameImpls(SUPER_CANNON) registered from a prior OPCM. Clear it
// unconditionally so the post-upgrade state matches the StandardValidator's expectation
// (SCDG-SHAPE / SCDG-NOSHAPE both require gameImpls(SUPER_CANNON) == address(0)). On
// initial deployment the DisputeGameFactory was just initialized and the slot is already
// zero, so this is a no-op state-wise (only emits a redundant event).
_cts.disputeGameFactory.setImplementation(GameTypes.SUPER_CANNON, IDisputeGame(address(0)), hex"");
_cts.disputeGameFactory.setInitBond(GameTypes.SUPER_CANNON, 0);
// If the custom gas token feature was requested, enable it in the SystemConfig.
// If the cgt is enabled, we skip this step.
if (_cfg.useCustomGasToken && !_cts.systemConfig.isCustomGasToken()) {
// NOTE: Enabling the custom gas token feature is only allowed during initial deployment to prevent
// chains from enabling it during upgrades. Passing in true for this flag during an upgrade is considered an
// error and will revert.
// Revert only if trying to upgrade from CGT disabled to CGT enabled.
if (!_isInitialDeployment) {
revert OPContractsManagerV2_CannotUpgradeToCustomGasToken();
}
_cts.systemConfig.setFeature(Features.CUSTOM_GAS_TOKEN, true);
}
// If critical transfer is allowed, transfer ownership of the DisputeGameFactory and
// ProxyAdmin to the PAO. During deployments, this means transferring ownership from the
// OPCM contract to the target PAO. During upgrades, this would theoretically mean
// transferring ownership from the existing PAO to itself, which would be a no-op. In an
// abundance of caution to prevent accidental unexpected transfers of ownership, we use a
// boolean flag to control whether this transfer is allowed which should ONLY be used for
// the initial deployment and no other management/upgrade action.
if (_isInitialDeployment) {
// Transfer ownership of the DisputeGameFactory to the proxyAdminOwner.
_cts.disputeGameFactory.transferOwnership(address(_cfg.proxyAdminOwner));
// Transfer ownership of the ProxyAdmin to the proxyAdminOwner.
_cts.proxyAdmin.transferOwnership(_cfg.proxyAdminOwner);
}
// Return contracts as the execution output.
return _cts;
}
///////////////////////////////////////////////////////////////////////////
// PUBLIC UTILITY FUNCTIONS //
///////////////////////////////////////////////////////////////////////////
/// @notice Checks if the upgrade sequence from the last used OPCM to this OPCM is permitted.
/// This function is public to allow tests to verify upgrade sequence logic directly
/// by mocking the OPCM version and calling this function, rather than running the full
/// upgrade flow. This avoids the need for special testing flags that bypass validation.
/// @param _systemConfig The SystemConfig contract to check the upgrade sequence for.
/// @return True if the upgrade sequence is permitted, false otherwise.
function isPermittedUpgradeSequence(ISystemConfig _systemConfig) public view returns (bool) {
return _isPermittedUpgradeSequence(_systemConfig, address(opcmV2));
}
/// @notice Returns whether a chain is on this OPCM's release and may be migrated.
/// Unlike isPermittedUpgradeSequence this refuses the next major version case.
/// @param _systemConfig The SystemConfig of the chain to check.
/// @return True if the chain may be migrated by this OPCM.
function isPermittedMigrateSequence(ISystemConfig _systemConfig) public view returns (bool) {
return _isPermittedMigrateSequence(_systemConfig, address(opcmV2));
}
/// @notice Returns the blueprint contract addresses.
function blueprints() public view returns (IOPContractsManagerContainer.Blueprints memory) {
return contractsContainer().blueprints();
}
/// @notice Returns the implementation contract addresses.
function implementations() public view returns (IOPContractsManagerContainer.Implementations memory) {
return contractsContainer().implementations();
}
/// @notice Returns the status of a development feature.
/// @param _feature The feature to check.
/// @return True if the feature is enabled, false otherwise.
function isDevFeatureEnabled(bytes32 _feature) public view returns (bool) {
return contractsContainer().isDevFeatureEnabled(_feature);
}
///////////////////////////////////////////////////////////////////////////
// INTERNAL UTILITY FUNCTIONS //
///////////////////////////////////////////////////////////////////////////
/// @notice Reverts if the function is being called directly rather than via delegatecall.
function _onlyDelegateCall() internal view {
if (address(this) == address(opcmV2)) {
revert OPContractsManagerV2_OnlyDelegateCall();
}
}
/// @notice Helper for retrieving the version of the OPCM contract.
/// @dev We use opcmV2.version() because it allows us to properly mock the version function
/// in tests without running into issues because this contract is being DELEGATECALLed.
/// @return The version of the OPCM contract.
function _version() internal view returns (string memory) {
return opcmV2.version();
}
/// @notice Returns the contracts container.
/// @return The contracts container.
function contractsContainer() public view returns (IOPContractsManagerContainer) {
return opcmUtils.contractsContainer();
}
/// @notice Returns the development feature bitmap.
/// @return The development feature bitmap.
function devFeatureBitmap() public view returns (bytes32) {
return contractsContainer().devFeatureBitmap();
}
}
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/IL1CrossDomainMessenger.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ICrossDomainMessenger } from "interfaces/universal/ICrossDomainMessenger.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IOptimismPortal2 as IOptimismPortal } from "interfaces/L1/IOptimismPortal2.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IL1CrossDomainMessenger is ICrossDomainMessenger, IProxyAdminOwnedBase {
error ReinitializableBase_ZeroInitVersion();
error L1CrossDomainMessenger_InteropNotEnabled();
error L1CrossDomainMessenger_NotInteropMessenger();
error L1CrossDomainMessenger_Paused();
function PORTAL() external view returns (IOptimismPortal);
function initialize(ISystemConfig _systemConfig, IOptimismPortal _portal) external;
function initVersion() external view returns (uint8);
function portal() external view returns (IOptimismPortal);
function systemConfig() external view returns (ISystemConfig);
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function relayUndeliveredMessage(bytes32 _messageHash, uint256 _undeliveredAt) external;
function syncETHLiquidityPause() external;
function __constructor__() external;
}
interfaces/L1/IL1ERC721Bridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC721Bridge } from "interfaces/universal/IERC721Bridge.sol";
import { ICrossDomainMessenger } from "interfaces/universal/ICrossDomainMessenger.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IL1ERC721Bridge is IERC721Bridge, IProxyAdminOwnedBase {
error ReinitializableBase_ZeroInitVersion();
function initVersion() external view returns (uint8);
function bridgeERC721(
address _localToken,
address _remoteToken,
uint256 _tokenId,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function bridgeERC721To(
address _localToken,
address _remoteToken,
address _to,
uint256 _tokenId,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function deposits(address, address, uint256) external view returns (bool);
function finalizeBridgeERC721(
address _localToken,
address _remoteToken,
address _from,
address _to,
uint256 _tokenId,
bytes memory _extraData
)
external;
function initialize(ICrossDomainMessenger _messenger, ISystemConfig _systemConfig) external;
function paused() external view returns (bool);
function systemConfig() external view returns (ISystemConfig);
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__() external;
}
interfaces/L1/IL1StandardBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { BridgeHookTypes } from "src/libraries/BridgeHookTypes.sol";
import { IStandardBridge } from "interfaces/universal/IStandardBridge.sol";
import { ICrossDomainMessenger } from "interfaces/universal/ICrossDomainMessenger.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IL1StandardBridge is IStandardBridge, IProxyAdminOwnedBase {
error ReinitializableBase_ZeroInitVersion();
event ERC20DepositInitiated(
address indexed l1Token,
address indexed l2Token,
address indexed from,
address to,
uint256 amount,
bytes extraData
);
event ERC20WithdrawalFinalized(
address indexed l1Token,
address indexed l2Token,
address indexed from,
address to,
uint256 amount,
bytes extraData
);
event ETHDepositInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData);
event ETHWithdrawalFinalized(address indexed from, address indexed to, uint256 amount, bytes extraData);
function initVersion() external view returns (uint8);
function depositERC20(
address _l1Token,
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function depositERC20To(
address _l1Token,
address _l2Token,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function depositETH(uint32 _minGasLimit, bytes memory _extraData) external payable;
function depositETHTo(address _to, uint32 _minGasLimit, bytes memory _extraData) external payable;
function finalizeERC20Withdrawal(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes memory _extraData
)
external;
function finalizeETHWithdrawal(
address _from,
address _to,
uint256 _amount,
bytes memory _extraData
)
external
payable;
function initialize(ICrossDomainMessenger _messenger, ISystemConfig _systemConfig) external;
function l2TokenBridge() external view returns (address);
function systemConfig() external view returns (ISystemConfig);
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function holdERC20(BridgeHookTypes.Direction _direction, bytes calldata _message) external;
function restoreERC20(BridgeHookTypes.Direction _direction, bytes calldata _message) external;
function __constructor__() external;
}
interfaces/L1/IOPContractsManagerStandardValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Interfaces
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IStandardValidatorUtils } from "interfaces/L1/opcm/IStandardValidatorUtils.sol";
import { IOPContractsManagerMigrationValidator } from "interfaces/L1/opcm/IOPContractsManagerMigrationValidator.sol";
interface IOPContractsManagerStandardValidator {
struct Implementations {
address l1ERC721BridgeImpl;
address optimismPortalImpl;
address ethLockboxImpl;
address systemConfigImpl;
address optimismMintableERC20FactoryImpl;
address l1CrossDomainMessengerImpl;
address l1StandardBridgeImpl;
address disputeGameFactoryImpl;
address anchorStateRegistryImpl;
address delayedWETHImpl;
address mipsImpl;
address faultDisputeGameImpl;
address permissionedDisputeGameImpl;
address superFaultDisputeGameImpl;
address superPermissionedDisputeGameImpl;
address zkDisputeGameImpl;
address sp1PlonkAdapterImpl;
}
struct ValidationInput {
ISystemConfig sysCfg;
bytes32 absolutePrestate;
uint256 l2ChainID;
address proposer;
}
struct ValidationInputDev {
ISystemConfig sysCfg;
bytes32 cannonPrestate;
bytes32 cannonKonaPrestate;
bytes32 zkPrestate;
uint256 l2ChainID;
address proposer;
}
struct ValidationOverrides {
address l1PAOMultisig;
address challenger;
}
error InvalidGameArgsLength();
function version() external view returns (string memory);
function anchorStateRegistryImpl() external view returns (address);
function challenger() external view returns (address);
function delayedWETHImpl() external view returns (address);
function devFeatureBitmap() external view returns (bytes32);
function disputeGameFactoryImpl() external view returns (address);
function l1CrossDomainMessengerImpl() external view returns (address);
function l1ERC721BridgeImpl() external view returns (address);
function l1PAOMultisig() external view returns (address);
function l1StandardBridgeImpl() external view returns (address);
function mipsImpl() external view returns (address);
function faultDisputeGameImpl() external view returns (address);
function permissionedDisputeGameImpl() external view returns (address);
function superFaultDisputeGameImpl() external view returns (address);
function superPermissionedDisputeGameImpl() external view returns (address);
function zkDisputeGameImpl() external view returns (address);
function sp1PlonkAdapterImpl() external view returns (address);
function optimismMintableERC20FactoryImpl() external view returns (address);
function optimismPortalImpl() external view returns (address);
function ethLockboxImpl() external view returns (address);
function preimageOracleVersion() external pure returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function systemConfigImpl() external view returns (address);
function standardValidatorUtils() external view returns (IStandardValidatorUtils);
function migrationValidator() external view returns (IOPContractsManagerMigrationValidator);
function validateMigratedChain(
IOPContractsManagerMigrationValidator.MigrationValidationInput memory _input,
bool _allowFailure
)
external
view
returns (string memory);
function validateMigratedChainWithOverrides(
IOPContractsManagerMigrationValidator.MigrationValidationInput memory _input,
bool _allowFailure,
ValidationOverrides memory _overrides
)
external
view
returns (string memory);
function validateWithOverrides(
ValidationInput memory _input,
bool _allowFailure,
ValidationOverrides memory _overrides
)
external
view
returns (string memory);
function validate(ValidationInput memory _input, bool _allowFailure) external view returns (string memory);
function validateWithOverrides(
ValidationInputDev memory _input,
bool _allowFailure,
ValidationOverrides memory _overrides
)
external
view
returns (string memory);
function validate(ValidationInputDev memory _input, bool _allowFailure) external view returns (string memory);
function __constructor__(
IStandardValidatorUtils _standardValidatorUtils,
IOPContractsManagerMigrationValidator _migrationValidator,
Implementations memory _implementations,
ISuperchainConfig _superchainConfig,
address _l1PAOMultisig,
address _challenger,
bytes32 _devFeatureBitmap
)
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_L1CDMCallFailed();
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_InvalidBridgeHookState();
error OptimismPortal_NotBridgeHook();
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 BridgeHookSet(IBridgeHook indexed bridgeHook);
event BridgeHookRemoved(IBridgeHook indexed bridgeHook);
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,
IBridgeHook _bridgeHook
)
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 removeHook() external;
function heldDeposits(bytes32) external view returns (bool);
function heldWithdrawals(bytes32) 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 PrivateConfigUpdate(
uint256 indexed version, uint256 indexed chainId, UpdateType indexed updateType, bytes data
);
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 privateConfig(uint256, UpdateType) external view returns (bytes memory);
function setPrivateConfig(uint256 _chainId, UpdateType _updateType, bytes calldata _data) external;
function isCustomGasToken() external view returns (bool);
function __constructor__() external;
}
interfaces/L1/opcm/IOPContractsManagerContainer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOPContractsManagerContainer {
struct Blueprints {
address addressManager;
address proxy;
address proxyAdmin;
address l1ChugSplashProxy;
address resolvedDelegateProxy;
}
struct Implementations {
address superchainConfigImpl;
address l1ERC721BridgeImpl;
address optimismPortalImpl;
address ethLockboxImpl;
address systemConfigImpl;
address optimismMintableERC20FactoryImpl;
address l1CrossDomainMessengerImpl;
address l1StandardBridgeImpl;
address disputeGameFactoryImpl;
address anchorStateRegistryImpl;
address delayedWETHImpl;
address mipsImpl;
address faultDisputeGameImpl;
address permissionedDisputeGameImpl;
address superFaultDisputeGameImpl;
address superPermissionedDisputeGameImpl;
address zkDisputeGameImpl;
address storageSetterImpl;
address sp1PlonkAdapterImpl;
}
error OPContractsManagerContainer_DevFeatureInProd();
function blueprints() external view returns (Blueprints memory);
function implementations() external view returns (Implementations memory);
function isDevFeatureEnabled(bytes32 _feature) external view returns (bool);
function devFeatureBitmap() external view returns (bytes32);
function __constructor__(Blueprints memory _blueprints, Implementations memory _implementations, bytes32 _devFeatureBitmap) external;
}
interfaces/L1/opcm/IOPContractsManagerMigrationValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Interfaces
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { GameType, Proposal } from "src/dispute/lib/Types.sol";
import { IOPContractsManagerStandardValidator } from "interfaces/L1/IOPContractsManagerStandardValidator.sol";
import { IStandardValidatorUtils } from "interfaces/L1/opcm/IStandardValidatorUtils.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
interface IOPContractsManagerMigrationValidator {
error InvalidGameArgsLength();
/// @notice A chain's pre-migration contracts.
struct LegacyChainContracts {
IDisputeGameFactory disputeGameFactory;
IETHLockbox ethLockbox;
IDelayedWETH delayedWETH;
IAnchorStateRegistry anchorStateRegistry;
}
/// @notice Addresses of the shared contracts the migration was meant to produce.
struct ExpectedSharedContracts {
IAnchorStateRegistry anchorStateRegistry;
IETHLockbox ethLockbox;
address delayedWETH;
}
/// @notice A game type's intended init bond on the shared DisputeGameFactory.
struct ExpectedInitBond {
GameType gameType;
uint256 initBond;
}
struct MigrationValidationInput {
/// @notice Should be sourced in the same way as expectedShared below.
IDisputeGameFactory dgf;
ISystemConfig[] chainSystemConfigs;
/// @notice Each chain's pre-migration contracts, must be in the same order as chainSystemConfigs.
LegacyChainContracts[] legacyChainContracts;
/// @notice The caller MUST source these independently of the migration's resulting state,
/// otherwise the validation is meaningless as it would validate the contracts
/// against their own state.
ExpectedSharedContracts expectedShared;
ExpectedInitBond[] expectedInitBonds;
Proposal startingAnchorRoot;
GameType startingRespectedGameType;
bytes32 cannonKonaPrestate;
address proposer;
}
/// @notice Shared implementation addresses used when validating proxy → impl pairings.
/// Includes the StandardValidatorUtils helper used for super-game drill-down checks.
struct SharedImplementations {
address disputeGameFactoryImpl;
address anchorStateRegistryImpl;
address ethLockboxImpl;
address delayedWETHImpl;
address mipsImpl;
address superFaultDisputeGameImpl;
address superPermissionedDisputeGameImpl;
IStandardValidatorUtils standardValidatorUtils;
}
/// @notice Shared roles and config values used during migration validation.
struct SharedConfig {
address l1PAOMultisig;
ISuperchainConfig superchainConfig;
}
function validateMigration(
MigrationValidationInput memory _input,
bool _allowFailure,
SharedImplementations memory _impls,
SharedConfig memory _cfg
)
external
view
returns (string memory);
function validateMigrationWithOverrides(
MigrationValidationInput memory _input,
bool _allowFailure,
IOPContractsManagerStandardValidator.ValidationOverrides memory _overrides,
SharedImplementations memory _impls,
SharedConfig memory _cfg
)
external
view
returns (string memory);
function __constructor__() external;
}
interfaces/L1/opcm/IOPContractsManagerMigrator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { GameType, Proposal } from "src/dispute/lib/Types.sol";
// Interfaces
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IOPContractsManagerContainer } from "interfaces/L1/opcm/IOPContractsManagerContainer.sol";
import { IOPContractsManagerUtils } from "interfaces/L1/opcm/IOPContractsManagerUtils.sol";
interface IOPContractsManagerMigrator {
/// @notice Input for migrating one or more OP Stack chains to use the Super Root dispute games
/// and shared dispute game contracts.
struct MigrateInput {
ISystemConfig[] chainSystemConfigs;
IOPContractsManagerUtils.DisputeGameConfig[] disputeGameConfigs;
Proposal startingAnchorRoot;
GameType startingRespectedGameType;
}
/// @notice Thrown when a chain's ProxyAdmin owner does not match the other chains.
error OPContractsManagerMigrator_ProxyAdminOwnerMismatch();
/// @notice Thrown when a chain's SuperchainConfig does not match the other chains.
error OPContractsManagerMigrator_SuperchainConfigMismatch();
/// @notice Thrown when the starting respected game type is not a valid super game type.
error OPContractsManagerMigrator_InvalidStartingRespectedGameType();
/// @notice Thrown when attempting to migrate a CGT chain.
error OPContractsManagerMigrator_CustomGasTokenNotSupported();
/// @notice Thrown when attempting to migrate a chain whose portal has a bridge hook.
error OPContractsManagerMigrator_BridgeHookNotSupported();
/// @notice Thrown when the chainSystemConfigs array is empty.
error OPContractsManagerMigrator_NoChains();
/// @notice Thrown when a chain is paused before migration mutates its portal.
error OPContractsManagerMigrator_SystemPaused();
error OPContractsManagerMigrator_ChainAlreadyMigrated();
error OPContractsManagerMigrator_SuperchainConfigNeedsUpgrade();
/// @notice Thrown when a chain's SystemConfig reports an l2ChainId of zero.
error OPContractsManagerMigrator_ZeroL2ChainId();
/// @notice Thrown when two chains share the same l2ChainId.
error OPContractsManagerMigrator_DuplicateL2ChainId();
/// @notice Thrown when chainSystemConfigs are not provided in ascending order by l2ChainId.
error OPContractsManagerMigrator_ChainIdsNotAscending();
/// @notice Thrown when a dispute game config has an init bond that its game type does not
/// allow: non-zero for SUPER_PERMISSIONED, which does not use bonds, or zero for any
/// other game type.
error OPContractsManagerMigrator_InvalidInitBond();
/// @notice Thrown when a permissionless fault game config has a zero absolute prestate.
error OPContractsManagerMigrator_InvalidAbsolutePrestate();
/// @notice Thrown when a ZK_DISPUTE_GAME config has a zero absolute prestate, a zero or
/// greater-than-uint32-max challenge or prove duration, or a zero challenger bond.
error OPContractsManagerMigrator_InvalidZKDisputeGameConfig();
/// @notice Thrown when a dispute game config is for a game type that does not use super roots.
error OPContractsManagerMigrator_InvalidGameType();
/// @notice Thrown when a dispute game config is not enabled. Migration registers every config
/// it is given, so a disabled config would be registered anyway.
error OPContractsManagerMigrator_DisputeGameNotEnabled();
error OPContractsManagerMigrator_InvalidStartingAnchorRoot();
error OPContractsManagerMigrator_DisputeGameFinalityDelayMismatch();
error OPContractsManagerMigrator_WithdrawalDelayMismatch();
error SemverComp_InvalidSemverParts();
/// @notice Returns the container of blueprint and implementation contract addresses.
function contractsContainer() external view returns (IOPContractsManagerContainer);
/// @notice Returns the address of the OPContractsManagerUtils contract.
function opcmUtils() external view returns (IOPContractsManagerUtils);
/// @notice Migrates one or more OP Stack chains to use the Super Root dispute games and shared
/// dispute game contracts.
/// @param _input The input parameters for the migration.
function migrate(MigrateInput calldata _input) external;
function __constructor__(IOPContractsManagerUtils _utils) external;
}
interfaces/L1/opcm/IOPContractsManagerUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IOPContractsManagerContainer } from "interfaces/L1/opcm/IOPContractsManagerContainer.sol";
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IAddressManager } from "interfaces/legacy/IAddressManager.sol";
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { Claim, Duration, GameType } from "src/dispute/lib/Types.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
interface IOPContractsManagerUtils {
struct ProxyDeployArgs {
IProxyAdmin proxyAdmin;
IAddressManager addressManager;
uint256 l2ChainId;
string saltMixer;
}
struct ExtraInstruction {
string key;
bytes data;
}
/// @notice Configuration struct for the FaultDisputeGame.
struct FaultDisputeGameConfig {
Claim absolutePrestate;
}
/// @notice Configuration struct for the PermissionedDisputeGame.
struct PermissionedDisputeGameConfig {
Claim absolutePrestate;
address proposer;
address challenger;
}
/// @notice Configuration struct for the SuperPermissionedDisputeGame.
struct SuperPermissionedDisputeGameConfig {
address proposer;
}
/// @notice Configuration struct for the ZKDisputeGame.
struct ZKDisputeGameConfig {
Claim absolutePrestate;
Duration maxChallengeDuration;
Duration maxProveDuration;
uint256 challengerBond;
}
/// @notice Generic dispute game configuration data.
struct DisputeGameConfig {
bool enabled;
uint256 initBond;
GameType gameType;
bytes gameArgs;
}
event ProxyCreation(string name, address proxy);
error OPContractsManagerUtils_DowngradeNotAllowed(address _contract);
error OPContractsManagerUtils_ExtraTagInProd(address _contract);
error OPContractsManagerUtils_OZv5InitializableUnsupported();
error OPContractsManagerUtils_ConfigLoadFailed(string _name);
error OPContractsManagerUtils_ProxyMustLoad(string _name);
error OPContractsManagerUtils_UnsupportedGameType();
error OPContractsManagerUtils_InvalidZKGameArgsLength(uint256 length);
error ReservedBitsSet();
error UnsupportedERCVersion(uint8 version);
error SemverComp_InvalidSemverParts();
error DeploymentFailed();
error UnexpectedPreambleData(bytes data);
error NotABlueprint();
error EmptyInitcode();
error BytesArrayTooLong();
error IdentityPrecompileCallFailed();
function implementations() external view returns (IOPContractsManagerContainer.Implementations memory);
function blueprints() external view returns (IOPContractsManagerContainer.Blueprints memory);
function contractsContainer() external view returns (IOPContractsManagerContainer);
function chainIdToBatchInboxAddress(uint256 _l2ChainId) external pure returns (address);
function computeSalt(
uint256 _l2ChainId,
string memory _saltMixer,
string memory _contractName
)
external
pure
returns (bytes32);
function isMatchingInstructionByKey(
ExtraInstruction memory _instruction,
string memory _key
)
external
pure
returns (bool);
function isMatchingInstruction(
ExtraInstruction memory _instruction,
string memory _key,
bytes memory _data
)
external
pure
returns (bool);
function hasInstruction(
ExtraInstruction[] memory _instructions,
string memory _key,
bytes memory _data
)
external
pure
returns (bool);
function getInstructionByKey(
ExtraInstruction[] memory _instructions,
string memory _key
)
external
pure
returns (ExtraInstruction memory);
function loadBytes(
address _source,
bytes4 _selector,
string memory _name,
ExtraInstruction[] memory _instructions
)
external
view
returns (bytes memory);
function loadOrDeployProxy(
address _source,
bytes4 _selector,
ProxyDeployArgs memory _args,
string memory _contractName,
ExtraInstruction[] memory _instructions
)
external
returns (address payable);
function upgrade(
IProxyAdmin _proxyAdmin,
address _target,
address _implementation,
bytes memory _data,
bytes32 _slot,
uint8 _offset
)
external;
function getGameImpl(GameType _gameType) external view returns (IDisputeGame);
function makeGameArgs(
uint256 _l2ChainId,
IAnchorStateRegistry _anchorStateRegistry,
IDelayedWETH _delayedWETH,
DisputeGameConfig memory _gcfg
)
external
view
returns (bytes memory);
function isPermittedUpgradeSequence(ISystemConfig _systemConfig, address _opcm) external view returns (bool);
function isPermittedMigrateSequence(ISystemConfig _systemConfig, address _opcm) external view returns (bool);
function __constructor__(IOPContractsManagerContainer _contractsContainer) external;
}
interfaces/L1/opcm/IStandardValidatorUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IPreimageOracle } from "interfaces/cannon/IPreimageOracle.sol";
import { IMIPS64 } from "interfaces/cannon/IMIPS64.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import {
DisputeGameValidationArgs,
DisputeGameImpls,
DisputeGameConfig,
SuperPermissionedDisputeGameValidationArgs,
SuperPermissionedDisputeGameImpls
} from "src/L1/opcm/StandardValidatorUtils.sol";
interface IStandardValidatorUtils {
function __constructor__() external;
function assertValidSuperchainConfig(
string memory _errors,
ISuperchainConfig _superchainConfig
)
external
view
returns (string memory);
function assertValidProxyAdmin(
string memory _errors,
IProxyAdmin _admin,
address _l1PAOMultisig
)
external
view
returns (string memory);
function assertValidSuperRootDisputeGames(
string memory _errors,
ISystemConfig _sysCfg
)
external
view
returns (string memory);
function assertValidNonSuperRootDisputeGames(
string memory _errors,
ISystemConfig _sysCfg
)
external
view
returns (string memory);
function assertValidMipsVm(
string memory _errors,
IMIPS64 _mips,
address _mipsImpl,
string memory _errorPrefix
)
external
view
returns (string memory);
function assertValidOptimismMintableERC20Factory(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl
)
external
view
returns (string memory);
function assertValidDisputeGameFactory(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl,
address _l1PAOMultisig
)
external
view
returns (string memory);
function assertValidOptimismPortal(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl
)
external
view
returns (string memory);
function assertValidPreimageOracle(
string memory _errors,
IPreimageOracle _oracle,
string memory _errorPrefix
)
external
view
returns (string memory);
function assertValidDelayedWETH(
string memory _errors,
ISystemConfig _sysCfg,
IDelayedWETH _weth,
IProxyAdmin _admin,
address _l1PAOMultisig,
address _delayedWETHImpl,
string memory _errorPrefix
)
external
view
returns (string memory);
function assertValidAnchorStateRegistry(
string memory _errors,
ISystemConfig _sysCfg,
IDisputeGameFactory _dgf,
IAnchorStateRegistry _asr,
IProxyAdmin _admin,
address _anchorStateRegistryImpl,
string memory _errorPrefix
)
external
view
returns (string memory);
function assertValidDisputeGame(
DisputeGameValidationArgs memory _args,
DisputeGameImpls memory _impls,
DisputeGameConfig memory _cfg
)
external
view
returns (string memory errors_);
function assertValidSuperPermissionedDisputeGame(
SuperPermissionedDisputeGameValidationArgs memory _args,
SuperPermissionedDisputeGameImpls memory _impls
)
external
view
returns (string memory errors_);
}
interfaces/cannon/IMIPS64.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IPreimageOracle } from "interfaces/cannon/IPreimageOracle.sol";
/// @title IMIPS64
/// @notice Interface for the MIPS64 contract.
interface IMIPS64 is ISemver {
struct State {
bytes32 memRoot;
bytes32 preimageKey;
uint32 preimageOffset;
uint32 pc;
uint32 nextPC;
uint32 lo;
uint32 hi;
uint32 heap;
uint8 exitCode;
bool exited;
uint64 step;
uint32[32] registers;
}
error InvalidExitedValue();
error InvalidPC();
error InvalidSecondMemoryProof();
error UnsupportedStateVersion();
error InvalidMemoryProof();
error InvalidRMWInstruction();
function version() external view returns (string memory);
function oracle() external view returns (IPreimageOracle oracle_);
function stateVersion() external view returns (uint256 stateVersion_);
function step(bytes memory _stateData, bytes memory _proof, bytes32 _localContext) external returns (bytes32 postState_);
function __constructor__(IPreimageOracle _oracle, uint256 _stateVersion) external;
}
interfaces/cannon/IPreimageOracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { LibKeccak } from "@lib-keccak/LibKeccak.sol";
import { LPPMetaData } from "src/cannon/libraries/CannonTypes.sol";
interface IPreimageOracle {
struct Leaf {
bytes input;
uint256 index;
bytes32 stateCommitment;
}
error ActiveProposal();
error AlreadyFinalized();
error AlreadyInitialized();
error BadProposal();
error BondTransferFailed();
error InsufficientBond();
error InvalidInputSize();
error InvalidPreimage();
error InvalidProof();
error NotEOA();
error NotInitialized();
error PartOffsetOOB();
error PostStateMatches();
error StatesNotContiguous();
error TreeSizeOverflow();
error WrongStartingBlock();
function KECCAK_TREE_DEPTH() external view returns (uint256);
function MAX_LEAF_COUNT() external view returns (uint256);
function MIN_BOND_SIZE() external view returns (uint256);
function PRECOMPILE_CALL_RESERVED_GAS() external view returns (uint256);
function addLeavesLPP(
uint256 _uuid,
uint256 _inputStartBlock,
bytes memory _input,
bytes32[] memory _stateCommitments,
bool _finalize
)
external;
function challengeFirstLPP(
address _claimant,
uint256 _uuid,
Leaf memory _postState,
bytes32[] memory _postStateProof
)
external;
function challengeLPP(
address _claimant,
uint256 _uuid,
LibKeccak.StateMatrix memory _stateMatrix,
Leaf memory _preState,
bytes32[] memory _preStateProof,
Leaf memory _postState,
bytes32[] memory _postStateProof
)
external;
function challengePeriod() external view returns (uint256 challengePeriod_);
function getTreeRootLPP(address _owner, uint256 _uuid) external view returns (bytes32 treeRoot_);
function initLPP(uint256 _uuid, uint32 _partOffset, uint32 _claimedSize) external payable;
function loadBlobPreimagePart(
uint256 _z,
uint256 _y,
bytes memory _commitment,
bytes memory _proof,
uint256 _partOffset
)
external;
function loadKeccak256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
function loadLocalData(
uint256 _ident,
bytes32 _localContext,
bytes32 _word,
uint256 _size,
uint256 _partOffset
)
external
returns (bytes32 key_);
function loadPrecompilePreimagePart(
uint256 _partOffset,
address _precompile,
uint64 _requiredGas,
bytes memory _input
)
external;
function loadSha256PreimagePart(uint256 _partOffset, bytes memory _preimage) external;
function minProposalSize() external view returns (uint256 minProposalSize_);
function preimageLengths(bytes32) external view returns (uint256);
function preimagePartOk(bytes32, uint256) external view returns (bool);
function preimageParts(bytes32, uint256) external view returns (bytes32);
function proposalBlocks(address, uint256, uint256) external view returns (uint64);
function proposalBlocksLen(address _claimant, uint256 _uuid) external view returns (uint256 len_);
function proposalBonds(address, uint256) external view returns (uint256);
function proposalBranches(address, uint256, uint256) external view returns (bytes32);
function proposalCount() external view returns (uint256 count_);
function proposalMetadata(address, uint256) external view returns (LPPMetaData);
function proposalParts(address, uint256) external view returns (bytes32);
function proposals(uint256) external view returns (address claimant, uint256 uuid); // nosemgrep:
// sol-style-return-arg-fmt
function readPreimage(bytes32 _key, uint256 _offset) external view returns (bytes32 dat_, uint256 datLen_);
function squeezeLPP(
address _claimant,
uint256 _uuid,
LibKeccak.StateMatrix memory _stateMatrix,
Leaf memory _preState,
bytes32[] memory _preStateProof,
Leaf memory _postState,
bytes32[] memory _postStateProof
)
external;
function version() external view returns (string memory);
function zeroHashes(uint256) external view returns (bytes32);
function __constructor__(uint256 _minProposalSize, uint256 _challengePeriod) external;
}
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/IBigStepper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IPreimageOracle } from "interfaces/cannon/IPreimageOracle.sol";
/// @title IBigStepper
/// @notice Describes a state machine that can perform a single instruction step, provided a prestate and an optional
/// proof.
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⠶⢅⠒⢄⢔⣶⡦⣤⡤⠄⣀⠀⠀⠀⠀⠀⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠨⡏⠀⠀⠈⠢⣙⢯⣄⠀⢨⠯⡺⡘⢄⠀⠀⠀⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣶⡆⠀⠀⠀⠀⠈⠓⠬⡒⠡⣀⢙⡜⡀⠓⠄⠀⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡷⠿⣧⣀⡀⠀⠀⠀⠀⠀⠀⠉⠣⣞⠩⠥⠀⠼⢄⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀⠉⢹⣶⠒⠒⠂⠈⠉⠁⠘⡆⠀⣿⣿⠫⡄⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⢶⣤⣀⡀⠀⠀⢸⡿⠀⠀⠀⠀⠀⢀⠞⠀⠀⢡⢨⢀⡄⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡒⣿⢿⡤⠝⡣⠉⠁⠚⠛⠀⠤⠤⣄⡰⠁⠀⠀⠀⠉⠙⢸⠀⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⡤⢯⡌⡿⡇⠘⡷⠀⠁⠀⠀⢀⣰⠢⠲⠛⣈⣸⠦⠤⠶⠴⢬⣐⣊⡂⠀
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⡪⡗⢫⠞⠀⠆⣀⠻⠤⠴⠐⠚⣉⢀⠦⠂⠋⠁⠀⠁⠀⠀⠀⠀⢋⠉⠇⠀
/// ⠀⠀⠀⠀⣀⡤⠐⠒⠘⡹⠉⢸⠇⠸⠀⠀⠀⠀⣀⣤⠴⠚⠉⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠀⣾⠀
/// ⠀⠀⠀⡰⠀⠉⠉⠀⠁⠀⠀⠈⢇⠈⠒⠒⠘⠈⢀⢡⡂⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠀⢸⡄
/// ⠀⠀⠸⣿⣆⠤⢀⡀⠀⠀⠀⠀⢘⡌⠀⠀⣀⣀⣀⡈⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀⢸⡇
/// ⠀⠀⢸⣀⠀⠉⠒⠐⠛⠋⠭⠭⠍⠉⠛⠒⠒⠒⠀⠒⠚⠛⠛⠛⠩⠭⠭⠭⠭⠤⠤⠤⠤⠤⠭⠭⠉⠓⡆
/// ⠀⠀⠘⠿⣷⣶⣤⣤⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣤⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡇
/// ⠀⠀⠀⠀⠀⠉⠙⠛⠛⠻⠿⢿⣿⣿⣷⣶⣶⣶⣤⣤⣀⣁⣛⣃⣒⠿⠿⠿⠤⠠⠄⠤⠤⢤⣛⣓⣂⣻⡇
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠉⠉⠙⠛⠻⠿⠿⠿⢿⣿⣿⣿⣷⣶⣶⣾⣿⣿⣿⣿⠿⠟⠁
/// ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠈⠉⠉⠉⠉⠁⠀⠀⠀⠀⠀
interface IBigStepper {
/// @notice Performs the state transition from a given prestate and returns the hash of the post state witness.
/// @param _stateData The raw opaque prestate data.
/// @param _proof Opaque proof data, can be used to prove things about the prestate in relation to the state of the
/// interface's implementation.
/// @param _localContext The local key context for the preimage oracle. Optional, can be set as a constant if the
/// implementation only requires one set of local keys.
/// @return postState_ The hash of the post state witness after the state transition.
function step(
bytes calldata _stateData,
bytes calldata _proof,
bytes32 _localContext
)
external
returns (bytes32 postState_);
/// @notice Returns the preimage oracle used by the state machine.
function oracle() external view returns (IPreimageOracle oracle_);
}
interfaces/dispute/IDelayedWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IDelayedWETH is IProxyAdminOwnedBase {
error DelayedWETH_InvalidDelay();
error DelayedWETH_InvalidDelayBounds();
error ReinitializableBase_ZeroInitVersion();
struct WithdrawalRequest {
uint256 amount;
uint256 timestamp;
}
event DelaySet(uint256 delay);
event Initialized(uint8 version);
fallback() external payable;
receive() external payable;
function initVersion() external view returns (uint8);
function ethLockbox() external view returns (IETHLockbox);
function delay() external view returns (uint256);
function minDelay() external view returns (uint256);
function maxDelay() external view returns (uint256);
function hold(address _guy) external;
function hold(address _guy, uint256 _wad) external;
function initialize(IETHLockbox _ethLockbox, uint256 _delay) external;
function recover(uint256 _wad) external;
function setDelay(uint256 _delay) external;
function unlock(address _guy, uint256 _wad) external;
function withdraw(address _guy, uint256 _wad) external;
function withdrawals(address, address) external view returns (uint256 amount, uint256 timestamp);
function version() external view returns (string memory);
function withdraw(uint256 _wad) external;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address src) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function deposit() external payable;
function totalSupply() external view returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(address src, address dst, uint256 wad) external returns (bool);
function config() external view returns (ISuperchainConfig);
function __constructor__(uint256 _minDelay, uint256 _maxDelay) 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/ICrossDomainMessenger.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ICrossDomainMessenger {
event FailedRelayedMessage(bytes32 indexed msgHash);
event Initialized(uint8 version);
event RelayedMessage(bytes32 indexed msgHash);
event SentMessage(address indexed target, address sender, bytes message, uint256 messageNonce, uint256 gasLimit);
event SentMessageExtension1(address indexed sender, uint256 value);
function MESSAGE_VERSION() external view returns (uint16);
function MIN_GAS_CALLDATA_OVERHEAD() external view returns (uint64);
function MIN_GAS_DYNAMIC_OVERHEAD_DENOMINATOR() external view returns (uint64);
function MIN_GAS_DYNAMIC_OVERHEAD_NUMERATOR() external view returns (uint64);
function OTHER_MESSENGER() external view returns (ICrossDomainMessenger);
function RELAY_CALL_OVERHEAD() external view returns (uint64);
function RELAY_CONSTANT_OVERHEAD() external view returns (uint64);
function RELAY_GAS_CHECK_BUFFER() external view returns (uint64);
function RELAY_RESERVED_GAS() external view returns (uint64);
function TX_BASE_GAS() external view returns (uint64);
function FLOOR_CALLDATA_OVERHEAD() external view returns (uint64);
function ENCODING_OVERHEAD() external view returns (uint64);
function baseGas(bytes memory _message, uint32 _minGasLimit) external pure returns (uint64);
function failedMessages(bytes32) external view returns (bool);
function messageNonce() external view returns (uint256);
function otherMessenger() external view returns (ICrossDomainMessenger);
function paused() external view returns (bool);
function relayMessage(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _minGasLimit,
bytes memory _message
)
external
payable;
function sendMessage(address _target, bytes memory _message, uint32 _minGasLimit) external payable;
function successfulMessages(bytes32) external view returns (bool);
function xDomainMessageSender() external view returns (address);
function __constructor__() external;
}
interfaces/universal/IERC721Bridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ICrossDomainMessenger } from "interfaces/universal/ICrossDomainMessenger.sol";
interface IERC721Bridge {
event ERC721BridgeFinalized(
address indexed localToken,
address indexed remoteToken,
address indexed from,
address to,
uint256 tokenId,
bytes extraData
);
event ERC721BridgeInitiated(
address indexed localToken,
address indexed remoteToken,
address indexed from,
address to,
uint256 tokenId,
bytes extraData
);
event Initialized(uint8 version);
function MESSENGER() external view returns (ICrossDomainMessenger);
function OTHER_BRIDGE() external view returns (IERC721Bridge);
function bridgeERC721(
address _localToken,
address _remoteToken,
uint256 _tokenId,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function bridgeERC721To(
address _localToken,
address _remoteToken,
address _to,
uint256 _tokenId,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function messenger() external view returns (ICrossDomainMessenger);
function otherBridge() external view returns (IERC721Bridge);
function paused() external view returns (bool);
function __constructor__() external;
}
interfaces/universal/IOptimismMintableERC20Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface IOptimismMintableERC20Factory is IProxyAdminOwnedBase {
event Initialized(uint8 version);
event OptimismMintableERC20Created(address indexed localToken, address indexed remoteToken, address deployer);
event StandardL2TokenCreated(address indexed remoteToken, address indexed localToken);
function BRIDGE() external view returns (address);
function bridge() external view returns (address);
function createOptimismMintableERC20(
address _remoteToken,
string memory _name,
string memory _symbol
)
external
returns (address);
function createOptimismMintableERC20WithDecimals(
address _remoteToken,
string memory _name,
string memory _symbol,
uint8 _decimals
)
external
returns (address);
function createStandardL2Token(
address _remoteToken,
string memory _name,
string memory _symbol
)
external
returns (address);
function deployments(address) external view returns (address);
function initialize(address _bridge) external;
function version() external view returns (string memory);
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);
}
interfaces/universal/IStandardBridge.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ICrossDomainMessenger } from "interfaces/universal/ICrossDomainMessenger.sol";
interface IStandardBridge {
event ERC20BridgeFinalized(
address indexed localToken,
address indexed remoteToken,
address indexed from,
address to,
uint256 amount,
bytes extraData
);
event ERC20BridgeInitiated(
address indexed localToken,
address indexed remoteToken,
address indexed from,
address to,
uint256 amount,
bytes extraData
);
event ETHBridgeFinalized(address indexed from, address indexed to, uint256 amount, bytes extraData);
event ETHBridgeInitiated(address indexed from, address indexed to, uint256 amount, bytes extraData);
event Initialized(uint8 version);
receive() external payable;
function MESSENGER() external view returns (ICrossDomainMessenger);
function OTHER_BRIDGE() external view returns (IStandardBridge);
function bridgeERC20(
address _localToken,
address _remoteToken,
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function bridgeERC20To(
address _localToken,
address _remoteToken,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes memory _extraData
)
external;
function bridgeETH(uint32 _minGasLimit, bytes memory _extraData) external payable;
function bridgeETHTo(address _to, uint32 _minGasLimit, bytes memory _extraData) external payable;
function deposits(address, address) external view returns (uint256);
function finalizeBridgeERC20(
address _localToken,
address _remoteToken,
address _from,
address _to,
uint256 _amount,
bytes memory _extraData
)
external;
function finalizeBridgeETH(address _from, address _to, uint256 _amount, bytes memory _extraData) external payable;
function messenger() external view returns (ICrossDomainMessenger);
function otherBridge() external view returns (IStandardBridge);
function paused() external view returns (bool);
function __constructor__() external;
}
lib/lib-keccak/contracts/lib/LibKeccak.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title LibKeccak
/// @notice An EVM implementation of the Keccak-f[1600] permutation.
/// @author clabby <https://github.com/clabby>
/// @custom:attribution geohot <https://github.com/geohot>
library LibKeccak {
/// @notice The block size of the Keccak-f[1600] permutation, 1088 bits (136 bytes).
uint256 internal constant BLOCK_SIZE_BYTES = 136;
/// @notice The round constants for the keccak256 hash function. Packed in memory for efficient reading during the
/// permutation.
bytes internal constant ROUND_CONSTANTS = abi.encode(
0x00000000000000010000000000008082800000000000808a8000000080008000, // r1,r2,r3,r4
0x000000000000808b000000008000000180000000800080818000000000008009, // r5,r6,r7,r8
0x000000000000008a00000000000000880000000080008009000000008000000a, // r9,r10,r11,r12
0x000000008000808b800000000000008b80000000000080898000000000008003, // r13,r14,r15,r16
0x80000000000080028000000000000080000000000000800a800000008000000a, // r17,r18,r19,r20
0x8000000080008081800000000000808000000000800000018000000080008008 // r21,r22,r23,r24
);
/// @notice A mask for 64-bit values.
uint64 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
/// @notice The 5x5 state matrix for the keccak-f[1600] permutation.
struct StateMatrix {
uint64[25] state;
}
/// @notice Performs the Keccak-f[1600] permutation on the given 5x5 state matrix.
function permutation(StateMatrix memory _stateMatrix) internal pure {
// Pull the round constants into memory to avoid reallocation in the unrolled permutation loop.
bytes memory roundConstants = ROUND_CONSTANTS;
assembly {
// Add 32 to the state matrix pointer to skip the data location field.
let stateMatrixPtr := add(_stateMatrix, 0x20)
let rcPtr := add(roundConstants, 0x20)
// set a state element in the passed `StateMatrix` struct memory ptr.
function setStateElem(ptr, idx, data) {
mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
}
// fetch a state element from the passed `StateMatrix` struct memory ptr.
function stateElem(ptr, idx) -> elem {
elem := mload(add(ptr, shl(0x05, idx)))
}
// 64 bit logical shift
function shl64(a, b) -> val {
val := and(shl(a, b), U64_MASK)
}
// Performs an indivudual rho + pi computation, to be used in the full `thetaRhoPi` chain.
function rhoPi(ptr, destIdx, srcIdx, fact, dt) {
let xs1 := xor(stateElem(ptr, srcIdx), dt)
let res := xor(shl(fact, xs1), shr(sub(64, fact), xs1))
setStateElem(ptr, destIdx, res)
}
// xor a column in the state matrix
function xorColumn(ptr, col) -> val {
val :=
xor(
xor(xor(stateElem(ptr, col), stateElem(ptr, add(col, 5))), stateElem(ptr, add(col, 10))),
xor(stateElem(ptr, add(col, 15)), stateElem(ptr, add(col, 20)))
)
}
// Performs the `theta`, `rho`, and `pi` steps of the Keccak-f[1600] permutation on
// the passed `StateMatrix` struct memory ptr.
function thetaRhoPi(ptr) {
// Theta
let C0 := xorColumn(ptr, 0)
let C1 := xorColumn(ptr, 1)
let C2 := xorColumn(ptr, 2)
let C3 := xorColumn(ptr, 3)
let C4 := xorColumn(ptr, 4)
let D0 := xor(xor(shl64(1, C1), shr(63, C1)), C4)
let D1 := xor(xor(shl64(1, C2), shr(63, C2)), C0)
let D2 := xor(xor(shl64(1, C3), shr(63, C3)), C1)
let D3 := xor(xor(shl64(1, C4), shr(63, C4)), C2)
let D4 := xor(xor(shl64(1, C0), shr(63, C0)), C3)
let xs1 := xor(stateElem(ptr, 1), D1)
let A1 := xor(shl(1, xs1), shr(63, xs1))
let _ptr := ptr
setStateElem(_ptr, 0, xor(stateElem(_ptr, 0), D0))
rhoPi(_ptr, 1, 6, 44, D1)
rhoPi(_ptr, 6, 9, 20, D4)
rhoPi(_ptr, 9, 22, 61, D2)
rhoPi(_ptr, 22, 14, 39, D4)
rhoPi(_ptr, 14, 20, 18, D0)
rhoPi(_ptr, 20, 2, 62, D2)
rhoPi(_ptr, 2, 12, 43, D2)
rhoPi(_ptr, 12, 13, 25, D3)
rhoPi(_ptr, 13, 19, 8, D4)
rhoPi(_ptr, 19, 23, 56, D3)
rhoPi(_ptr, 23, 15, 41, D0)
rhoPi(_ptr, 15, 4, 27, D4)
rhoPi(_ptr, 4, 24, 14, D4)
rhoPi(_ptr, 24, 21, 2, D1)
rhoPi(_ptr, 21, 8, 55, D3)
rhoPi(_ptr, 8, 16, 45, D1)
rhoPi(_ptr, 16, 5, 36, D0)
rhoPi(_ptr, 5, 3, 28, D3)
rhoPi(_ptr, 3, 18, 21, D3)
rhoPi(_ptr, 18, 17, 15, D2)
rhoPi(_ptr, 17, 11, 10, D1)
rhoPi(_ptr, 11, 7, 6, D2)
rhoPi(_ptr, 7, 10, 3, D0)
setStateElem(_ptr, 10, A1)
}
// Inner `chi` function, unrolled in `chi` for performance.
function innerChi(ptr, start) {
let A0 := stateElem(ptr, start)
let A1 := stateElem(ptr, add(start, 1))
let A2 := stateElem(ptr, add(start, 2))
let A3 := stateElem(ptr, add(start, 3))
let A4 := stateElem(ptr, add(start, 4))
setStateElem(ptr, start, xor(A0, and(not(A1), A2)))
setStateElem(ptr, add(start, 1), xor(A1, and(not(A2), A3)))
setStateElem(ptr, add(start, 2), xor(A2, and(not(A3), A4)))
setStateElem(ptr, add(start, 3), xor(A3, and(not(A4), A0)))
setStateElem(ptr, add(start, 4), xor(A4, and(not(A0), A1)))
}
// Performs the `chi` step of the Keccak-f[1600] permutation on the passed `StateMatrix` struct memory ptr
function chi(ptr) {
innerChi(ptr, 0)
innerChi(ptr, 5)
innerChi(ptr, 10)
innerChi(ptr, 15)
innerChi(ptr, 20)
}
// Perform the full Keccak-f[1600] permutation on a `StateMatrix` struct memory ptr for a given round.
function permute(ptr, roundsPtr, round) {
// Theta, Rho, Pi, Chi
thetaRhoPi(ptr)
chi(ptr)
// Iota
let roundConst := shr(192, mload(add(roundsPtr, shl(0x03, round))))
setStateElem(ptr, 0, xor(stateElem(ptr, 0), roundConst))
}
// Unroll the permutation loop.
permute(stateMatrixPtr, rcPtr, 0)
permute(stateMatrixPtr, rcPtr, 1)
permute(stateMatrixPtr, rcPtr, 2)
permute(stateMatrixPtr, rcPtr, 3)
permute(stateMatrixPtr, rcPtr, 4)
permute(stateMatrixPtr, rcPtr, 5)
permute(stateMatrixPtr, rcPtr, 6)
permute(stateMatrixPtr, rcPtr, 7)
permute(stateMatrixPtr, rcPtr, 8)
permute(stateMatrixPtr, rcPtr, 9)
permute(stateMatrixPtr, rcPtr, 10)
permute(stateMatrixPtr, rcPtr, 11)
permute(stateMatrixPtr, rcPtr, 12)
permute(stateMatrixPtr, rcPtr, 13)
permute(stateMatrixPtr, rcPtr, 14)
permute(stateMatrixPtr, rcPtr, 15)
permute(stateMatrixPtr, rcPtr, 16)
permute(stateMatrixPtr, rcPtr, 17)
permute(stateMatrixPtr, rcPtr, 18)
permute(stateMatrixPtr, rcPtr, 19)
permute(stateMatrixPtr, rcPtr, 20)
permute(stateMatrixPtr, rcPtr, 21)
permute(stateMatrixPtr, rcPtr, 22)
permute(stateMatrixPtr, rcPtr, 23)
}
}
/// @notice Absorb a fixed-sized block into the sponge.
function absorb(StateMatrix memory _stateMatrix, bytes memory _input) internal pure {
assembly {
// The input must be 1088 bits long.
if iszero(eq(mload(_input), BLOCK_SIZE_BYTES)) { revert(0, 0) }
let dataPtr := add(_input, 0x20)
let statePtr := add(_stateMatrix, 0x20)
// set a state element in the passed `StateMatrix` struct memory ptr.
function setStateElem(ptr, idx, data) {
mstore(add(ptr, shl(0x05, idx)), and(data, U64_MASK))
}
// fetch a state element from the passed `StateMatrix` struct memory ptr.
function stateElem(ptr, idx) -> elem {
elem := mload(add(ptr, shl(0x05, idx)))
}
// Inner sha3 absorb XOR function
function absorbInner(stateMatrixPtr, inputPtr, idx) {
let boWord := mload(add(inputPtr, shl(3, idx)))
let res :=
or(
or(
or(shl(56, byte(7, boWord)), shl(48, byte(6, boWord))),
or(shl(40, byte(5, boWord)), shl(32, byte(4, boWord)))
),
or(
or(shl(24, byte(3, boWord)), shl(16, byte(2, boWord))),
or(shl(8, byte(1, boWord)), byte(0, boWord))
)
)
setStateElem(stateMatrixPtr, idx, xor(stateElem(stateMatrixPtr, idx), res))
}
// Unroll the input XOR loop.
absorbInner(statePtr, dataPtr, 0)
absorbInner(statePtr, dataPtr, 1)
absorbInner(statePtr, dataPtr, 2)
absorbInner(statePtr, dataPtr, 3)
absorbInner(statePtr, dataPtr, 4)
absorbInner(statePtr, dataPtr, 5)
absorbInner(statePtr, dataPtr, 6)
absorbInner(statePtr, dataPtr, 7)
absorbInner(statePtr, dataPtr, 8)
absorbInner(statePtr, dataPtr, 9)
absorbInner(statePtr, dataPtr, 10)
absorbInner(statePtr, dataPtr, 11)
absorbInner(statePtr, dataPtr, 12)
absorbInner(statePtr, dataPtr, 13)
absorbInner(statePtr, dataPtr, 14)
absorbInner(statePtr, dataPtr, 15)
absorbInner(statePtr, dataPtr, 16)
}
}
/// @notice Squeezes the final keccak256 digest from the passed `StateMatrix`.
function squeeze(StateMatrix memory _stateMatrix) internal pure returns (bytes32 hash_) {
assembly {
// 64 bit logical shift
function shl64(a, b) -> val {
val := and(shl(a, b), U64_MASK)
}
// convert a big endian 64-bit value to a little endian 64-bit value.
function toLE(beVal) -> leVal {
beVal := or(and(shl64(8, beVal), 0xFF00FF00FF00FF00), and(shr(8, beVal), 0x00FF00FF00FF00FF))
beVal := or(and(shl64(16, beVal), 0xFFFF0000FFFF0000), and(shr(16, beVal), 0x0000FFFF0000FFFF))
leVal := or(shl64(32, beVal), shr(32, beVal))
}
// fetch a state element from the passed `StateMatrix` struct memory ptr.
function stateElem(ptr, idx) -> elem {
elem := mload(add(ptr, shl(0x05, idx)))
}
let stateMatrixPtr := add(_stateMatrix, 0x20)
hash_ :=
or(
or(shl(192, toLE(stateElem(stateMatrixPtr, 0))), shl(128, toLE(stateElem(stateMatrixPtr, 1)))),
or(shl(64, toLE(stateElem(stateMatrixPtr, 2))), toLE(stateElem(stateMatrixPtr, 3)))
)
}
}
/// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
function pad(bytes calldata _data) internal pure returns (bytes memory padded_) {
assembly {
padded_ := mload(0x40)
// Grab the original length of `_data`
let len := _data.length
let dataPtr := add(padded_, 0x20)
let endPtr := add(dataPtr, len)
// Copy the data into memory.
calldatacopy(dataPtr, _data.offset, len)
let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
switch modBlockSize
case false {
// Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
// not update the free memory pointer when allocating memory, for example with external calls. To do
// this, we read out-of-bounds from the calldata, which will always return 0 bytes.
calldatacopy(endPtr, calldatasize(), BLOCK_SIZE_BYTES)
// If the input is a perfect multiple of the block size, then we add a full extra block of padding.
mstore8(endPtr, 0x01)
mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
// Update the length of the data to include the padding.
mstore(padded_, add(len, BLOCK_SIZE_BYTES))
}
default {
// If the input is not a perfect multiple of the block size, then we add a partial block of padding.
// This should entail a set bit after the input, followed by as many zero bits as necessary to fill
// the block, followed by a single 1 bit in the lowest-order bit of the final block.
let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
let newLen := add(len, remaining)
let paddedEndPtr := add(dataPtr, newLen)
// Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
// possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
// when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
// calldata, which will always return 0 bytes.
let partialRemainder := sub(paddedEndPtr, endPtr)
calldatacopy(endPtr, calldatasize(), partialRemainder)
// Store the padding bits.
mstore8(sub(paddedEndPtr, 0x01), 0x80)
mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
// Update the length of the data to include the padding. The length should be a multiple of the
// block size after this.
mstore(padded_, newLen)
}
// Update the free memory pointer.
mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
}
}
/// @notice Pads input data to an even multiple of the Keccak-f[1600] permutation block size, 1088 bits (136 bytes).
function padMemory(bytes memory _data) internal pure returns (bytes memory padded_) {
assembly {
padded_ := mload(0x40)
// Grab the original length of `_data`
let len := mload(_data)
let dataPtr := add(padded_, 0x20)
let endPtr := add(dataPtr, len)
// Copy the data.
let originalDataPtr := add(_data, 0x20)
for { let i := 0x00 } lt(i, len) { i := add(i, 0x20) } {
mstore(add(dataPtr, i), mload(add(originalDataPtr, i)))
}
let modBlockSize := mod(len, BLOCK_SIZE_BYTES)
switch modBlockSize
case false {
// Clean the full padding block. It is possible that this memory is dirty, since solidity sometimes does
// not update the free memory pointer when allocating memory, for example with external calls. To do
// this, we read out-of-bounds from the calldata, which will always return 0 bytes.
calldatacopy(endPtr, calldatasize(), BLOCK_SIZE_BYTES)
// If the input is a perfect multiple of the block size, then we add a full extra block of padding.
mstore8(sub(add(endPtr, BLOCK_SIZE_BYTES), 0x01), 0x80)
mstore8(endPtr, 0x01)
// Update the length of the data to include the padding.
mstore(padded_, add(len, BLOCK_SIZE_BYTES))
}
default {
// If the input is not a perfect multiple of the block size, then we add a partial block of padding.
// This should entail a set bit after the input, followed by as many zero bits as necessary to fill
// the block, followed by a single 1 bit in the lowest-order bit of the final block.
let remaining := sub(BLOCK_SIZE_BYTES, modBlockSize)
let newLen := add(len, remaining)
let paddedEndPtr := add(dataPtr, newLen)
// Clean the remainder to ensure that the intermediate data between the padding bits is 0. It is
// possible that this memory is dirty, since solidity sometimes does not update the free memory pointer
// when allocating memory, for example with external calls. To do this, we read out-of-bounds from the
// calldata, which will always return 0 bytes.
let partialRemainder := sub(paddedEndPtr, endPtr)
calldatacopy(endPtr, calldatasize(), partialRemainder)
// Store the padding bits.
mstore8(sub(paddedEndPtr, 0x01), 0x80)
mstore8(endPtr, or(byte(0x00, mload(endPtr)), 0x01))
// Update the length of the data to include the padding. The length should be a multiple of the
// block size after this.
mstore(padded_, newLen)
}
// Update the free memory pointer.
mstore(0x40, add(padded_, and(add(mload(padded_), 0x3F), not(0x1F))))
}
}
}
lib/solady/src/utils/JSONParserLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for parsing JSONs.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/JSONParserLib.sol)
library JSONParserLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The input is invalid.
error ParsingFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// There are 6 types of variables in JSON (excluding undefined).
/// @dev For denoting that an item has not been initialized.
/// A item returned from `parse` will never be of an undefined type.
/// Parsing a invalid JSON string will simply revert.
uint8 internal constant TYPE_UNDEFINED = 0;
/// @dev Type representing an array (e.g. `[1,2,3]`).
uint8 internal constant TYPE_ARRAY = 1;
/// @dev Type representing an object (e.g. `{"a":"A","b":"B"}`).
uint8 internal constant TYPE_OBJECT = 2;
/// @dev Type representing a number (e.g. `-1.23e+21`).
uint8 internal constant TYPE_NUMBER = 3;
/// @dev Type representing a string (e.g. `"hello"`).
uint8 internal constant TYPE_STRING = 4;
/// @dev Type representing a boolean (i.e. `true` or `false`).
uint8 internal constant TYPE_BOOLEAN = 5;
/// @dev Type representing null (i.e. `null`).
uint8 internal constant TYPE_NULL = 6;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev A pointer to a parsed JSON node.
struct Item {
// Do NOT modify the `_data` directly.
uint256 _data;
}
// Private constants for packing `_data`.
uint256 private constant _BITPOS_STRING = 32 * 7 - 8;
uint256 private constant _BITPOS_KEY_LENGTH = 32 * 6 - 8;
uint256 private constant _BITPOS_KEY = 32 * 5 - 8;
uint256 private constant _BITPOS_VALUE_LENGTH = 32 * 4 - 8;
uint256 private constant _BITPOS_VALUE = 32 * 3 - 8;
uint256 private constant _BITPOS_CHILD = 32 * 2 - 8;
uint256 private constant _BITPOS_SIBLING_OR_PARENT = 32 * 1 - 8;
uint256 private constant _BITMASK_POINTER = 0xffffffff;
uint256 private constant _BITMASK_TYPE = 7;
uint256 private constant _KEY_INITED = 1 << 3;
uint256 private constant _VALUE_INITED = 1 << 4;
uint256 private constant _CHILDREN_INITED = 1 << 5;
uint256 private constant _PARENT_IS_ARRAY = 1 << 6;
uint256 private constant _PARENT_IS_OBJECT = 1 << 7;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* JSON PARSING OPERATION */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Parses the JSON string `s`, and returns the root.
/// Reverts if `s` is not a valid JSON as specified in RFC 8259.
/// Object items WILL simply contain all their children, inclusive of repeated keys,
/// in the same order which they appear in the JSON string.
///
/// Note: For efficiency, this function WILL NOT make a copy of `s`.
/// The parsed tree WILL contain offsets to `s`.
/// Do NOT pass in a string that WILL be modified later on.
function parse(string memory s) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // We will use our own allocation instead.
}
bytes32 r = _query(_toInput(s), 255);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* JSON ITEM OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note:
// - An item is a node in the JSON tree.
// - The value of a string item WILL be double-quoted, JSON encoded.
// - We make a distinction between `index` and `key`.
// - Items in arrays are located by `index` (uint256).
// - Items in objects are located by `key` (string).
// - Keys are always strings, double-quoted, JSON encoded.
//
// These design choices are made to balance between efficiency and ease-of-use.
/// @dev Returns the string value of the item.
/// This is its exact string representation in the original JSON string.
/// The returned string WILL have leading and trailing whitespace trimmed.
/// All inner whitespace WILL be preserved, exactly as it is in the original JSON string.
/// If the item's type is string, the returned string WILL be double-quoted, JSON encoded.
///
/// Note: This function lazily instantiates and caches the returned string.
/// Do NOT modify the returned string.
function value(Item memory item) internal pure returns (string memory result) {
bytes32 r = _query(_toInput(item), 0);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/// @dev Returns the index of the item in the array.
/// It the item's parent is not an array, returns 0.
function index(Item memory item) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if and(mload(item), _PARENT_IS_ARRAY) {
result := and(_BITMASK_POINTER, shr(_BITPOS_KEY, mload(item)))
}
}
}
/// @dev Returns the key of the item in the object.
/// It the item's parent is not an object, returns an empty string.
/// The returned string WILL be double-quoted, JSON encoded.
///
/// Note: This function lazily instantiates and caches the returned string.
/// Do NOT modify the returned string.
function key(Item memory item) internal pure returns (string memory result) {
if (item._data & _PARENT_IS_OBJECT != 0) {
bytes32 r = _query(_toInput(item), 1);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
}
/// @dev Returns the key of the item in the object.
/// It the item is neither an array nor object, returns an empty array.
///
/// Note: This function lazily instantiates and caches the returned array.
/// Do NOT modify the returned array.
function children(Item memory item) internal pure returns (Item[] memory result) {
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := r
}
}
/// @dev Returns the number of children.
/// It the item is neither an array nor object, returns zero.
function size(Item memory item) internal pure returns (uint256 result) {
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := mload(r)
}
}
/// @dev Returns the item at index `i` for (array).
/// If `item` is not an array, the result's type WILL be undefined.
/// If there is no item with the index, the result's type WILL be undefined.
function at(Item memory item, uint256 i) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We'll allocate manually.
}
bytes32 r = _query(_toInput(item), 3);
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(r, 0x20), shl(5, i)))
if iszero(and(lt(i, mload(r)), eq(and(mload(item), _BITMASK_TYPE), TYPE_ARRAY))) {
result := 0x60 // Reset to the zero pointer.
}
}
}
/// @dev Returns the item at key `k` for (object).
/// If `item` is not an object, the result's type WILL be undefined.
/// The key MUST be double-quoted, JSON encoded. This is for efficiency reasons.
/// - Correct : `item.at('"k"')`.
/// - Wrong : `item.at("k")`.
/// For duplicated keys, the last item with the key WILL be returned.
/// If there is no item with the key, the result's type WILL be undefined.
function at(Item memory item, string memory k) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We'll allocate manually.
result := 0x60 // Initialize to the zero pointer.
}
if (isObject(item)) {
bytes32 kHash = keccak256(bytes(k));
Item[] memory r = children(item);
// We'll just do a linear search. The alternatives are very bloated.
for (uint256 i = r.length << 5; i != 0;) {
/// @solidity memory-safe-assembly
assembly {
item := mload(add(r, i))
i := sub(i, 0x20)
}
if (keccak256(bytes(key(item))) != kHash) continue;
result = item;
break;
}
}
}
/// @dev Returns the item's type.
function getType(Item memory item) internal pure returns (uint8 result) {
result = uint8(item._data & _BITMASK_TYPE);
}
/// Note: All types are mutually exclusive.
/// @dev Returns whether the item is of type undefined.
function isUndefined(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_UNDEFINED;
}
/// @dev Returns whether the item is of type array.
function isArray(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_ARRAY;
}
/// @dev Returns whether the item is of type object.
function isObject(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_OBJECT;
}
/// @dev Returns whether the item is of type number.
function isNumber(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_NUMBER;
}
/// @dev Returns whether the item is of type string.
function isString(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_STRING;
}
/// @dev Returns whether the item is of type boolean.
function isBoolean(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_BOOLEAN;
}
/// @dev Returns whether the item is of type null.
function isNull(Item memory item) internal pure returns (bool result) {
result = item._data & _BITMASK_TYPE == TYPE_NULL;
}
/// @dev Returns the item's parent.
/// If the item does not have a parent, the result's type will be undefined.
function parent(Item memory item) internal pure returns (Item memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Free the default allocation. We've already allocated.
result := and(shr(_BITPOS_SIBLING_OR_PARENT, mload(item)), _BITMASK_POINTER)
if iszero(result) { result := 0x60 } // Reset to the zero pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UTILITY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Parses an unsigned integer from a string (in decimal, i.e. base 10).
/// Reverts if `s` is not a valid uint256 string matching the RegEx `^[0-9]+$`,
/// or if the parsed number is too big for a uint256.
function parseUint(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let preMulOverflowThres := div(not(0), 10)
for { let i := 0 } 1 {} {
i := add(i, 1)
let digit := sub(and(mload(add(s, i)), 0xff), 48)
let mulOverflowed := gt(result, preMulOverflowThres)
let product := mul(10, result)
result := add(product, digit)
n := mul(n, iszero(or(or(mulOverflowed, lt(result, product)), gt(digit, 9))))
if iszero(lt(i, n)) { break }
}
if iszero(n) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Parses a signed integer from a string (in decimal, i.e. base 10).
/// Reverts if `s` is not a valid int256 string matching the RegEx `^[+-]?[0-9]+$`,
/// or if the parsed number is too big for a int256.
function parseInt(string memory s) internal pure returns (int256 result) {
uint256 n = bytes(s).length;
uint256 sign;
uint256 isNegative;
/// @solidity memory-safe-assembly
assembly {
if n {
let c := and(mload(add(s, 1)), 0xff)
isNegative := eq(c, 45)
if or(eq(c, 43), isNegative) {
sign := c
s := add(s, 1)
mstore(s, sub(n, 1))
}
if iszero(or(sign, lt(sub(c, 48), 10))) { s := 0x60 }
}
}
uint256 x = parseUint(s);
/// @solidity memory-safe-assembly
assembly {
if shr(255, x) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
if sign {
mstore(s, sign)
s := sub(s, 1)
mstore(s, n)
}
result := xor(x, mul(xor(x, add(not(x), 1)), isNegative))
}
}
/// @dev Parses an unsigned integer from a string (in hexadecimal, i.e. base 16).
/// Reverts if `s` is not a valid uint256 hex string matching the RegEx
/// `^(0[xX])?[0-9a-fA-F]+$`, or if the parsed number is too big for a uint256.
function parseUintFromHex(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
// Skip two if starts with '0x' or '0X'.
let i := shl(1, and(eq(0x3078, or(shr(240, mload(add(s, 0x20))), 0x20)), gt(n, 1)))
for {} 1 {} {
i := add(i, 1)
let c :=
byte(
and(0x1f, shr(and(mload(add(s, i)), 0xff), 0x3e4088843e41bac000000000000)),
0x3010a071000000b0104040208000c05090d060e0f
)
n := mul(n, iszero(or(iszero(c), shr(252, result))))
result := add(shl(4, result), sub(c, 1))
if iszero(lt(i, n)) { break }
}
if iszero(n) {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Decodes a JSON encoded string.
/// The string MUST be double-quoted, JSON encoded.
/// Reverts if the string is invalid.
/// As you can see, it's pretty complex for a deceptively simple looking task.
function decodeString(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
function fail() {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
function decodeUnicodeEscapeSequence(pIn_, end_) -> _unicode, _pOut {
_pOut := add(pIn_, 4)
let b_ := iszero(gt(_pOut, end_))
let t_ := mload(pIn_) // Load the whole word.
for { let i_ := 0 } iszero(eq(i_, 4)) { i_ := add(i_, 1) } {
let c_ := sub(byte(i_, t_), 48)
if iszero(and(shr(c_, 0x7e0000007e03ff), b_)) { fail() } // Not hexadecimal.
c_ := sub(c_, add(mul(gt(c_, 16), 7), shl(5, gt(c_, 48))))
_unicode := add(shl(4, _unicode), c_)
}
}
function decodeUnicodeCodePoint(pIn_, end_) -> _unicode, _pOut {
_unicode, _pOut := decodeUnicodeEscapeSequence(pIn_, end_)
if iszero(or(lt(_unicode, 0xd800), gt(_unicode, 0xdbff))) {
let t_ := mload(_pOut) // Load the whole word.
end_ := mul(end_, eq(shr(240, t_), 0x5c75)) // Fail if not starting with '\\u'.
t_, _pOut := decodeUnicodeEscapeSequence(add(_pOut, 2), end_)
_unicode := add(0x10000, add(shl(10, and(0x3ff, _unicode)), and(0x3ff, t_)))
}
}
function appendCodePointAsUTF8(pIn_, c_) -> _pOut {
if iszero(gt(c_, 0x7f)) {
mstore8(pIn_, c_)
_pOut := add(pIn_, 1)
leave
}
mstore8(0x1f, c_)
mstore8(0x1e, shr(6, c_))
if iszero(gt(c_, 0x7ff)) {
mstore(pIn_, shl(240, or(0xc080, and(0x1f3f, mload(0x00)))))
_pOut := add(pIn_, 2)
leave
}
mstore8(0x1d, shr(12, c_))
if iszero(gt(c_, 0xffff)) {
mstore(pIn_, shl(232, or(0xe08080, and(0x0f3f3f, mload(0x00)))))
_pOut := add(pIn_, 3)
leave
}
mstore8(0x1c, shr(18, c_))
mstore(pIn_, shl(224, or(0xf0808080, and(0x073f3f3f, mload(0x00)))))
_pOut := add(pIn_, shl(2, lt(c_, 0x110000)))
}
function chr(p_) -> _c {
_c := byte(0, mload(p_))
}
let n := mload(s)
let end := add(add(s, n), 0x1f)
if iszero(and(gt(n, 1), eq(0x2222, or(and(0xff00, mload(add(s, 2))), chr(end))))) {
fail() // Fail if not double-quoted.
}
let out := add(mload(0x40), 0x20)
for { let curr := add(s, 0x21) } iszero(eq(curr, end)) {} {
let c := chr(curr)
curr := add(curr, 1)
// Not '\\'.
if iszero(eq(c, 92)) {
// Not '"'.
if iszero(eq(c, 34)) {
mstore8(out, c)
out := add(out, 1)
continue
}
curr := end
}
if iszero(eq(curr, end)) {
let escape := chr(curr)
curr := add(curr, 1)
// '"', '/', '\\'.
if and(shr(escape, 0x100000000000800400000000), 1) {
mstore8(out, escape)
out := add(out, 1)
continue
}
// 'u'.
if eq(escape, 117) {
escape, curr := decodeUnicodeCodePoint(curr, end)
out := appendCodePointAsUTF8(out, escape)
continue
}
// `{'b':'\b', 'f':'\f', 'n':'\n', 'r':'\r', 't':'\t'}`.
escape := byte(sub(escape, 85), 0x080000000c000000000000000a0000000d0009)
if escape {
mstore8(out, escape)
out := add(out, 1)
continue
}
}
fail()
break
}
mstore(out, 0) // Zeroize the last slot.
result := mload(0x40)
mstore(result, sub(out, add(result, 0x20))) // Store the length.
mstore(0x40, add(out, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Performs a query on the input with the given mode.
function _query(bytes32 input, uint256 mode) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
function fail() {
mstore(0x00, 0x10182796) // `ParsingFailed()`.
revert(0x1c, 0x04)
}
function chr(p_) -> _c {
_c := byte(0, mload(p_))
}
function skipWhitespace(pIn_, end_) -> _pOut {
for { _pOut := pIn_ } 1 { _pOut := add(_pOut, 1) } {
if iszero(and(shr(chr(_pOut), 0x100002600), 1)) { leave } // Not in ' \n\r\t'.
}
}
function setP(packed_, bitpos_, p_) -> _packed {
// Perform an out-of-gas revert if `p_` exceeds `_BITMASK_POINTER`.
returndatacopy(returndatasize(), returndatasize(), gt(p_, _BITMASK_POINTER))
_packed := or(and(not(shl(bitpos_, _BITMASK_POINTER)), packed_), shl(bitpos_, p_))
}
function getP(packed_, bitpos_) -> _p {
_p := and(_BITMASK_POINTER, shr(bitpos_, packed_))
}
function mallocItem(s_, packed_, pStart_, pCurr_, type_) -> _item {
_item := mload(0x40)
// forgefmt: disable-next-item
packed_ := setP(setP(packed_, _BITPOS_VALUE, sub(pStart_, add(s_, 0x20))),
_BITPOS_VALUE_LENGTH, sub(pCurr_, pStart_))
mstore(_item, or(packed_, type_))
mstore(0x40, add(_item, 0x20)) // Allocate memory.
}
function parseValue(s_, sibling_, pIn_, end_) -> _item, _pOut {
let packed_ := setP(mload(0x00), _BITPOS_SIBLING_OR_PARENT, sibling_)
_pOut := skipWhitespace(pIn_, end_)
if iszero(lt(_pOut, end_)) { leave }
for { let c_ := chr(_pOut) } 1 {} {
// If starts with '"'.
if eq(c_, 34) {
let pStart_ := _pOut
_pOut := parseStringSub(s_, packed_, _pOut, end_)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_STRING)
break
}
// If starts with '['.
if eq(c_, 91) {
_item, _pOut := parseArray(s_, packed_, _pOut, end_)
break
}
// If starts with '{'.
if eq(c_, 123) {
_item, _pOut := parseObject(s_, packed_, _pOut, end_)
break
}
// If starts with any in '0123456789-'.
if and(shr(c_, shl(45, 0x1ff9)), 1) {
_item, _pOut := parseNumber(s_, packed_, _pOut, end_)
break
}
if iszero(gt(add(_pOut, 4), end_)) {
let pStart_ := _pOut
let w_ := shr(224, mload(_pOut))
// 'true' in hex format.
if eq(w_, 0x74727565) {
_pOut := add(_pOut, 4)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_BOOLEAN)
break
}
// 'null' in hex format.
if eq(w_, 0x6e756c6c) {
_pOut := add(_pOut, 4)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_NULL)
break
}
}
if iszero(gt(add(_pOut, 5), end_)) {
let pStart_ := _pOut
let w_ := shr(216, mload(_pOut))
// 'false' in hex format.
if eq(w_, 0x66616c7365) {
_pOut := add(_pOut, 5)
_item := mallocItem(s_, packed_, pStart_, _pOut, TYPE_BOOLEAN)
break
}
}
fail()
break
}
_pOut := skipWhitespace(_pOut, end_)
}
function parseArray(s_, packed_, pIn_, end_) -> _item, _pOut {
let j_ := 0
for { _pOut := add(pIn_, 1) } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(_pOut, end_)) { fail() }
if iszero(_item) {
_pOut := skipWhitespace(_pOut, end_)
if eq(chr(_pOut), 93) { break } // ']'.
}
_item, _pOut := parseValue(s_, _item, _pOut, end_)
if _item {
// forgefmt: disable-next-item
mstore(_item, setP(or(_PARENT_IS_ARRAY, mload(_item)),
_BITPOS_KEY, j_))
j_ := add(j_, 1)
let c_ := chr(_pOut)
if eq(c_, 93) { break } // ']'.
if eq(c_, 44) { continue } // ','.
}
_pOut := end_
}
_pOut := add(_pOut, 1)
packed_ := setP(packed_, _BITPOS_CHILD, _item)
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_ARRAY)
}
function parseObject(s_, packed_, pIn_, end_) -> _item, _pOut {
for { _pOut := add(pIn_, 1) } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(_pOut, end_)) { fail() }
if iszero(_item) {
_pOut := skipWhitespace(_pOut, end_)
if eq(chr(_pOut), 125) { break } // '}'.
}
_pOut := skipWhitespace(_pOut, end_)
let pKeyStart_ := _pOut
let pKeyEnd_ := parseStringSub(s_, _item, _pOut, end_)
_pOut := skipWhitespace(pKeyEnd_, end_)
// If ':'.
if eq(chr(_pOut), 58) {
_item, _pOut := parseValue(s_, _item, add(_pOut, 1), end_)
if _item {
// forgefmt: disable-next-item
mstore(_item, setP(setP(or(_PARENT_IS_OBJECT, mload(_item)),
_BITPOS_KEY_LENGTH, sub(pKeyEnd_, pKeyStart_)),
_BITPOS_KEY, sub(pKeyStart_, add(s_, 0x20))))
let c_ := chr(_pOut)
if eq(c_, 125) { break } // '}'.
if eq(c_, 44) { continue } // ','.
}
}
_pOut := end_
}
_pOut := add(_pOut, 1)
packed_ := setP(packed_, _BITPOS_CHILD, _item)
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_OBJECT)
}
function checkStringU(p_, o_) {
// If not in '0123456789abcdefABCDEF', revert.
if iszero(and(shr(sub(chr(add(p_, o_)), 48), 0x7e0000007e03ff), 1)) { fail() }
if iszero(eq(o_, 5)) { checkStringU(p_, add(o_, 1)) }
}
function parseStringSub(s_, packed_, pIn_, end_) -> _pOut {
if iszero(lt(pIn_, end_)) { fail() }
for { _pOut := add(pIn_, 1) } 1 {} {
let c_ := chr(_pOut)
if eq(c_, 34) { break } // '"'.
// Not '\'.
if iszero(eq(c_, 92)) {
_pOut := add(_pOut, 1)
continue
}
c_ := chr(add(_pOut, 1))
// '"', '\', '//', 'b', 'f', 'n', 'r', 't'.
if and(shr(sub(c_, 34), 0x510110400000000002001), 1) {
_pOut := add(_pOut, 2)
continue
}
// 'u'.
if eq(c_, 117) {
checkStringU(_pOut, 2)
_pOut := add(_pOut, 6)
continue
}
_pOut := end_
break
}
if iszero(lt(_pOut, end_)) { fail() }
_pOut := add(_pOut, 1)
}
function skip0To9s(pIn_, end_, atLeastOne_) -> _pOut {
for { _pOut := pIn_ } 1 { _pOut := add(_pOut, 1) } {
if iszero(lt(sub(chr(_pOut), 48), 10)) { break } // Not '0'..'9'.
}
if and(atLeastOne_, eq(pIn_, _pOut)) { fail() }
}
function parseNumber(s_, packed_, pIn_, end_) -> _item, _pOut {
_pOut := pIn_
if eq(chr(_pOut), 45) { _pOut := add(_pOut, 1) } // '-'.
if iszero(lt(sub(chr(_pOut), 48), 10)) { fail() } // Not '0'..'9'.
let c_ := chr(_pOut)
_pOut := add(_pOut, 1)
if iszero(eq(c_, 48)) { _pOut := skip0To9s(_pOut, end_, 0) } // Not '0'.
if eq(chr(_pOut), 46) { _pOut := skip0To9s(add(_pOut, 1), end_, 1) } // '.'.
let t_ := mload(_pOut)
// 'E', 'e'.
if eq(or(0x20, byte(0, t_)), 101) {
// forgefmt: disable-next-item
_pOut := skip0To9s(add(byte(sub(byte(1, t_), 14), 0x010001), // '+', '-'.
add(_pOut, 1)), end_, 1)
}
_item := mallocItem(s_, packed_, pIn_, _pOut, TYPE_NUMBER)
}
function copyStr(s_, offset_, len_) -> _sCopy {
_sCopy := mload(0x40)
s_ := add(s_, offset_)
let w_ := not(0x1f)
for { let i_ := and(add(len_, 0x1f), w_) } 1 {} {
mstore(add(_sCopy, i_), mload(add(s_, i_)))
i_ := add(i_, w_) // `sub(i_, 0x20)`.
if iszero(i_) { break }
}
mstore(_sCopy, len_) // Copy the length.
mstore(add(add(_sCopy, 0x20), len_), 0) // Zeroize the last slot.
mstore(0x40, add(add(_sCopy, 0x40), len_)) // Allocate memory.
}
function value(item_) -> _value {
let packed_ := mload(item_)
_value := getP(packed_, _BITPOS_VALUE) // The offset in the string.
if iszero(and(_VALUE_INITED, packed_)) {
let s_ := getP(packed_, _BITPOS_STRING)
_value := copyStr(s_, _value, getP(packed_, _BITPOS_VALUE_LENGTH))
packed_ := setP(packed_, _BITPOS_VALUE, _value)
mstore(s_, or(_VALUE_INITED, packed_))
}
}
function children(item_) -> _arr {
_arr := 0x60 // Initialize to the zero pointer.
let packed_ := mload(item_)
for {} iszero(gt(and(_BITMASK_TYPE, packed_), TYPE_OBJECT)) {} {
if or(iszero(packed_), iszero(item_)) { break }
if and(packed_, _CHILDREN_INITED) {
_arr := getP(packed_, _BITPOS_CHILD)
break
}
_arr := mload(0x40)
let o_ := add(_arr, 0x20)
for { let h_ := getP(packed_, _BITPOS_CHILD) } h_ {} {
mstore(o_, h_)
let q_ := mload(h_)
let y_ := getP(q_, _BITPOS_SIBLING_OR_PARENT)
mstore(h_, setP(q_, _BITPOS_SIBLING_OR_PARENT, item_))
h_ := y_
o_ := add(o_, 0x20)
}
let w_ := not(0x1f)
let n_ := add(w_, sub(o_, _arr))
mstore(_arr, shr(5, n_))
mstore(0x40, o_) // Allocate memory.
packed_ := setP(packed_, _BITPOS_CHILD, _arr)
mstore(item_, or(_CHILDREN_INITED, packed_))
// Reverse the array.
if iszero(lt(n_, 0x40)) {
let lo_ := add(_arr, 0x20)
let hi_ := add(_arr, n_)
for {} 1 {} {
let temp_ := mload(lo_)
mstore(lo_, mload(hi_))
mstore(hi_, temp_)
hi_ := add(hi_, w_)
lo_ := add(lo_, 0x20)
if iszero(lt(lo_, hi_)) { break }
}
}
break
}
}
function getStr(item_, bitpos_, bitposLength_, bitmaskInited_) -> _result {
_result := 0x60 // Initialize to the zero pointer.
let packed_ := mload(item_)
if or(iszero(item_), iszero(packed_)) { leave }
_result := getP(packed_, bitpos_)
if iszero(and(bitmaskInited_, packed_)) {
let s_ := getP(packed_, _BITPOS_STRING)
_result := copyStr(s_, _result, getP(packed_, bitposLength_))
mstore(item_, or(bitmaskInited_, setP(packed_, bitpos_, _result)))
}
}
switch mode
// Get value.
case 0 { result := getStr(input, _BITPOS_VALUE, _BITPOS_VALUE_LENGTH, _VALUE_INITED) }
// Get key.
case 1 { result := getStr(input, _BITPOS_KEY, _BITPOS_KEY_LENGTH, _KEY_INITED) }
// Get children.
case 3 { result := children(input) }
// Parse.
default {
let p := add(input, 0x20)
let e := add(p, mload(input))
if iszero(eq(p, e)) {
let c := chr(e)
mstore8(e, 34) // Place a '"' at the end to speed up parsing.
// The `34 << 248` makes `mallocItem` preserve '"' at the end.
mstore(0x00, setP(shl(248, 34), _BITPOS_STRING, input))
result, p := parseValue(input, 0, p, e)
mstore8(e, c) // Restore the original char at the end.
}
if or(lt(p, e), iszero(result)) { fail() }
}
}
}
/// @dev Casts the input to a bytes32.
function _toInput(string memory input) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := input
}
}
/// @dev Casts the input to a bytes32.
function _toInput(Item memory input) private pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := input
}
}
}
lib/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory str) {
if (value >= 0) {
return toString(uint256(value));
}
unchecked {
str = toString(uint256(-value));
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let length := mload(str) // Load the string length.
mstore(str, 0x2d) // Store the '-' character.
str := sub(str, 1) // Move back the string pointer by a byte.
mstore(str, add(length, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2 + 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value, length);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 length)
internal
pure
returns (string memory str)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(str, add(length, length))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(str, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := add(mload(str), 2) // Compute the length.
mstore(add(str, o), 0x3078) // Write the "0x" prefix, accounting for leading zero.
str := sub(add(str, o), 2) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(str, 0x20))), 0x30) // Whether leading zero is present.
let strLength := mload(str) // Get the length.
str := add(str, o) // Move the pointer, accounting for leading zero.
mstore(str, sub(strLength, o)) // Write the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
str := add(mload(0x40), 0x80)
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory str) {
str = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(str, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
str := mload(0x40)
// Allocate the memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(str, 0x80))
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
str := add(str, 2)
mstore(str, 40)
let o := add(str, 0x20)
mstore(add(o, 40), 0)
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory str) {
str = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
let length := mload(raw)
str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(str, add(length, length)) // Store the length of the output.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let o := add(str, 0x20)
let end := add(raw, length)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let mask := shl(7, div(not(0), 255))
result := 1
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.
function replace(string memory subject, string memory search, string memory replacement)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(result, o), mload(add(replacement, o)))
o := add(o, 0x20)
if iszero(lt(o, replacementLength)) { break }
}
result := add(result, replacementLength)
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
}
let resultRemainder := result
result := add(mload(0x40), 0x20)
let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
// Copy the rest of the string one word at a time.
for {} lt(subject, subjectEnd) {} {
mstore(resultRemainder, mload(subject))
resultRemainder := add(resultRemainder, 0x20)
subject := add(subject, 0x20)
}
result := sub(result, 0x20)
let last := add(add(result, 0x20), k) // Zeroize the slot after the string.
mstore(last, 0)
mstore(0x40, add(last, 0x20)) // Allocate the memory.
mstore(result, k) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for { let subjectLength := mload(subject) } 1 {} {
if iszero(mload(search)) {
if iszero(gt(from, subjectLength)) {
result := from
break
}
result := subjectLength
break
}
let searchLength := mload(search)
let subjectStart := add(subject, 0x20)
result := not(0) // Initialize to `NOT_FOUND`.
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(add(search, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }
if iszero(lt(searchLength, 0x20)) {
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = indexOf(subject, search, 0);
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let searchLength := mload(search)
if gt(searchLength, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), searchLength)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(subject, search, uint256(int256(-1)));
}
/// @dev Returns true if `search` is found in `subject`, false otherwise.
function contains(string memory subject, string memory search) internal pure returns (bool) {
return indexOf(subject, search) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `search`.
function startsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
iszero(gt(searchLength, mload(subject))),
eq(
keccak256(add(subject, 0x20), searchLength),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns whether `subject` ends with `search`.
function endsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
let subjectLength := mload(subject)
// Whether `search` is not longer than `subject`.
let withinRange := iszero(gt(searchLength, subjectLength))
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
withinRange,
eq(
keccak256(
// `subject + 0x20 + max(subjectLength - searchLength, 0)`.
add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),
searchLength
),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(or(iszero(times), iszero(subjectLength))) {
subject := add(subject, 0x20)
result := mload(0x40)
let output := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(output, o), mload(add(subject, o)))
o := add(o, 0x20)
if iszero(lt(o, subjectLength)) { break }
}
output := add(output, subjectLength)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(output, 0) // Zeroize the slot after the string.
let resultLength := sub(output, add(result, 0x20))
mstore(result, resultLength) // Store the length.
// Allocate the memory.
mstore(0x40, add(result, add(resultLength, 0x20)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(gt(subjectLength, end)) { end := subjectLength }
if iszero(gt(subjectLength, start)) { start := subjectLength }
if lt(start, end) {
result := mload(0x40)
let resultLength := sub(end, start)
mstore(result, resultLength)
subject := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
mstore(add(result, o), mload(add(subject, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(result, 0x20), resultLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(result, and(add(resultLength, 0x3f), w)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start)
internal
pure
returns (string memory result)
{
result = slice(subject, start, uint256(int256(-1)));
}
/// @dev Returns all the indices of `search` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory search)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
if iszero(gt(searchLength, subjectLength)) {
subject := add(subject, 0x20)
search := add(search, 0x20)
result := add(mload(0x40), 0x20)
let subjectStart := subject
let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Append to `result`.
mstore(result, sub(subject, subjectStart))
result := add(result, 0x20)
// Advance `subject` by `searchLength`.
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
let resultEnd := result
// Assign `result` to the free memory pointer.
result := mload(0x40)
// Store the length of `result`.
mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(resultEnd, 0x20))
}
}
}
/// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
let prevIndex := 0
for {} 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let elementLength := sub(index, prevIndex)
mstore(element, elementLength)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(elementLength, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(element, 0x20), elementLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(elementLength, 0x3f), w)))
// Store the `element` into the array.
mstore(indexPtr, element)
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
result := mload(0x40)
let aLength := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLength, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLength := mload(b)
let output := add(result, aLength)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLength, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLength := add(aLength, bLength)
let last := add(add(result, 0x20), totalLength)
// Zeroize the slot after the string.
mstore(last, 0)
// Stores the length.
mstore(result, totalLength)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, and(add(last, 0x1f), w))
}
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
for { let o := length } 1 {} {
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
if iszero(o) { break }
}
result := mload(0x40)
mstore(result, length) // Store the length.
let last := add(add(result, 0x20), length)
mstore(last, 0) // Zeroize the slot after the string.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n)
let o := add(result, 0x20)
mstore(o, s)
mstore(add(o, n), 0)
mstore(0x40, add(result, 0x40))
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(result, c)
result := add(result, 1)
continue
}
let t := shr(248, mload(c))
mstore(result, mload(and(t, 0x1f)))
result := add(result, shr(5, t))
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(result, c)
result := add(result, 1)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), c)
result := add(result, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(result, mload(0x19)) // "\\u00XX".
result := add(result, 6)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), mload(add(c, 8)))
result := add(result, 2)
}
if addDoubleQuotes {
mstore8(result, 34)
result := add(1, result)
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
result := mload(0x40)
// Allocate 2 words (1 for the length, 1 for the bytes).
mstore(0x40, add(result, 0x40))
// Zeroize the length slot.
mstore(result, 0)
// Store the length and bytes.
mstore(add(result, 0x1f), packed)
// Right pad with zeroes.
mstore(add(add(result, 0x20), mload(result)), 0)
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLength := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes of `a` and `b`.
or(
shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),
mload(sub(add(b, 0x1e), aLength))
),
// `totalLength != 0 && totalLength < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLength, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
resultA := mload(0x40)
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retSize), 0)
// Store the return offset.
mstore(retStart, 0x20)
// End the transaction, returning the string.
return(retStart, retSize)
}
}
}
src/L1/opcm/OPContractsManagerUtilsCaller.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { GameType } from "src/dispute/lib/Types.sol";
// Interfaces
import { IOPContractsManagerUtils } from "interfaces/L1/opcm/IOPContractsManagerUtils.sol";
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IResourceMetering } from "interfaces/L1/IResourceMetering.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
/// @title OPContractsManagerUtilsCaller
/// @notice OPContractsManagerUtilsCaller is an abstract contract that exists to hide all of the
/// complexity of cheaply calling the OPContractsManagerUtils contract. Most of this logic
/// could simply live inside of the OPContractsManagerV2 contract directly, but it helps to
/// keep the OPContractsManagerV2 contract cleaner and more readable by moving this here.
/// @dev OPContractsManagerUtilsCaller and OPContractsManagerUtils operate together in a way almost
/// identical to an "external library" contract. You could use a real external library, but
/// this is much easier for humans to read and for us to validate offchain.
abstract contract OPContractsManagerUtilsCaller {
/// @notice Arguments for SystemConfig.initialize, mirroring that function's signature so the
/// encoding lives in one place.
struct SystemConfigInitArgs {
address owner;
uint32 basefeeScalar;
uint32 blobbasefeeScalar;
bytes32 batcherHash;
uint64 gasLimit;
address unsafeBlockSigner;
IResourceMetering.ResourceConfig resourceConfig;
ISystemConfig.Addresses addrs;
uint256 l2ChainId;
ISuperchainConfig superchainConfig;
}
/// @notice Address of the OPContractsManagerUtils contract.
IOPContractsManagerUtils public immutable opcmUtils;
/// @param _utils Address of the OPContractsManagerUtils contract.
constructor(IOPContractsManagerUtils _utils) {
opcmUtils = _utils;
}
/// @notice Builds SystemConfig.initialize calldata.
/// @param _args The initializer arguments.
/// @return Calldata for SystemConfig.initialize.
function _encodeSystemConfigInit(SystemConfigInitArgs memory _args) internal pure returns (bytes memory) {
return abi.encodeCall(
ISystemConfig.initialize,
(
_args.owner,
_args.basefeeScalar,
_args.blobbasefeeScalar,
_args.batcherHash,
_args.gasLimit,
_args.unsafeBlockSigner,
_args.resourceConfig,
_args.addrs,
_args.l2ChainId,
_args.superchainConfig
)
);
}
/// @notice Checks that ZKDisputeGame args can produce a playable game. The absolute prestate is
/// the verification key, so it must be set. Durations must be non-zero and capped at
/// uint32 max so that `block.timestamp + duration` cannot overflow the game's uint64
/// deadline cast, which would place the deadline in the past. A zero challenger bond
/// would make challenges free.
/// @param _gameArgs The ABI-encoded IOPContractsManagerUtils.ZKDisputeGameConfig.
/// @return True if the config is valid, false otherwise.
function _isValidZKDisputeGameConfig(bytes memory _gameArgs) internal pure returns (bool) {
IOPContractsManagerUtils.ZKDisputeGameConfig memory cfg =
abi.decode(_gameArgs, (IOPContractsManagerUtils.ZKDisputeGameConfig));
return cfg.absolutePrestate.raw() != bytes32(0) && cfg.maxChallengeDuration.raw() > 0
&& cfg.maxChallengeDuration.raw() <= type(uint32).max && cfg.maxProveDuration.raw() > 0
&& cfg.maxProveDuration.raw() <= type(uint32).max && cfg.challengerBond > 0;
}
/// @notice Helper for computing a salt for a contract deployment.
/// @param _l2ChainId The L2 chain ID of the chain being deployed to.
/// @param _saltMixer The salt mixer to use for the deployment.
/// @param _contractName The name of the contract to deploy.
/// @return The computed salt.
function _computeSalt(
uint256 _l2ChainId,
string memory _saltMixer,
string memory _contractName
)
internal
view
returns (bytes32)
{
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.computeSalt, (_l2ChainId, _saltMixer, _contractName))),
(bytes32)
);
}
/// @notice Helper for checking whether a chain may be upgraded by this OPCM.
/// @param _systemConfig The SystemConfig of the chain to check.
/// @param _opcm The OPCM performing the upgrade.
/// @return True if the upgrade sequence is permitted.
function _isPermittedUpgradeSequence(ISystemConfig _systemConfig, address _opcm) internal view returns (bool) {
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.isPermittedUpgradeSequence, (_systemConfig, _opcm))),
(bool)
);
}
/// @notice Helper for checking whether a chain is on this OPCM's release and may be migrated.
/// @param _systemConfig The SystemConfig of the chain to check.
/// @param _opcm The OPCM performing the migration.
/// @return True if the chain may be migrated.
function _isPermittedMigrateSequence(ISystemConfig _systemConfig, address _opcm) internal view returns (bool) {
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.isPermittedMigrateSequence, (_systemConfig, _opcm))),
(bool)
);
}
/// @notice Helper function to check if an instruction matches a given key.
/// @param _instruction The instruction to check.
/// @param _key The key of the instruction to check for.
/// @return True if the instruction matches, false otherwise.
function _isMatchingInstructionByKey(
IOPContractsManagerUtils.ExtraInstruction memory _instruction,
string memory _key
)
internal
view
returns (bool)
{
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.isMatchingInstructionByKey, (_instruction, _key))),
(bool)
);
}
/// @notice Helper function to check if an instruction matches a given key and data.
/// @param _instruction The instruction to check.
/// @param _key The key of the instruction to check for.
/// @param _data The data of the instruction to check for.
/// @return True if the instruction matches, false otherwise.
function _isMatchingInstruction(
IOPContractsManagerUtils.ExtraInstruction memory _instruction,
string memory _key,
bytes memory _data
)
internal
view
returns (bool)
{
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.isMatchingInstruction, (_instruction, _key, _data))),
(bool)
);
}
/// @notice Helper function to load data from a source contract as bytes.
/// @param _source The source contract to load the data from.
/// @param _selector The selector of the function to call on the source contract.
/// @param _name The name of the field to load.
/// @param _instructions The extra upgrade instructions for the data load.
/// @return Data retrieved from the source contract.
function _loadBytes(
address _source,
bytes4 _selector,
string memory _name,
IOPContractsManagerUtils.ExtraInstruction[] memory _instructions
)
internal
view
returns (bytes memory)
{
return abi.decode(
_staticcall(abi.encodeCall(IOPContractsManagerUtils.loadBytes, (_source, _selector, _name, _instructions))),
(bytes)
);
}
/// @notice Attempts to load a proxy from a source function where the proxy should be found. If
/// the proxy isn't found at the source, or the call to the source fails, we build a
/// new proxy instead. Calls to source contracts MUST NOT fail under any circumstances
/// other than the function not existing (which can happen in an upgrade scenario).
/// @param _source The source contract to load the proxy from.
/// @param _selector The selector of the function to call on the source contract.
/// @param _args The basic arguments for the proxy deployment.
/// @param _contractName The name of the contract to deploy.
/// @param _instructions The extra upgrade instructions for the proxy deployment.
/// @return The address of the loaded or built proxy.
function _loadOrDeployProxy(
address _source,
bytes4 _selector,
IOPContractsManagerUtils.ProxyDeployArgs memory _args,
string memory _contractName,
IOPContractsManagerUtils.ExtraInstruction[] memory _instructions
)
internal
returns (address payable)
{
return payable(abi.decode(
_delegatecall(
abi.encodeCall(
IOPContractsManagerUtils.loadOrDeployProxy,
(_source, _selector, _args, _contractName, _instructions)
)
),
(address)
));
}
/// @notice Upgrades a contract by resetting the initialized slot and calling the initializer.
/// @param _proxyAdmin The proxy admin of the contract.
/// @param _target The target of the contract.
/// @param _implementation The implementation of the contract.
/// @param _data The data to call the initializer with. Must be called and not left empty.
/// @dev make sure _data is not empty and calls the initializer. otherwise it can lead to
/// unsupported OZ v5 Initializable contracts being used.
function _upgrade(IProxyAdmin _proxyAdmin, address _target, address _implementation, bytes memory _data) internal {
_upgrade(_proxyAdmin, _target, _implementation, _data, bytes32(0), 0);
}
/// @notice Upgrades a contract by resetting the initialized slot and calling the initializer.
/// @param _proxyAdmin The proxy admin of the contract.
/// @param _target The target of the contract.
/// @param _implementation The implementation of the contract.
/// @param _data The data to call the initializer with.
/// @param _slot The slot where the initialized value is located.
/// @param _offset The offset of the initializer value in the slot.
function _upgrade(
IProxyAdmin _proxyAdmin,
address _target,
address _implementation,
bytes memory _data,
bytes32 _slot,
uint8 _offset
)
internal
{
_delegatecall(
abi.encodeCall(
IOPContractsManagerUtils.upgrade, (_proxyAdmin, _target, _implementation, _data, _slot, _offset)
)
);
}
/// @notice Helper calling the utils contract (via delegatecall).
/// @param _data Calldata to send to the utils contract.
/// @return Result of the call.
function _delegatecall(bytes memory _data) internal returns (bytes memory) {
(bool success, bytes memory result) = address(opcmUtils).delegatecall(_data);
if (!success) {
assembly {
revert(add(result, 0x20), mload(result))
}
}
return result;
}
/// @notice Helper calling the utils contract (via staticcall).
/// @param _data Calldata to send to the utils contract.
/// @return Result of the call.
function _staticcall(bytes memory _data) internal view returns (bytes memory) {
(bool success, bytes memory result) = address(opcmUtils).staticcall(_data);
if (!success) {
assembly {
revert(add(result, 0x20), mload(result))
}
}
return result;
}
/// @notice Helper for retrieving the dispute game implementation for a given game type.
/// @param _gameType The game type to retrieve the implementation for.
/// @return The dispute game implementation.
function _getGameImpl(GameType _gameType) internal view returns (IDisputeGame) {
return
abi.decode(_staticcall(abi.encodeCall(IOPContractsManagerUtils.getGameImpl, (_gameType))), (IDisputeGame));
}
/// @notice Helper for creating game constructor arguments.
/// @param _l2ChainId The L2 chain ID.
/// @param _anchorStateRegistry The AnchorStateRegistry to use for dispute games.
/// @param _delayedWETH The DelayedWETH to use for dispute games.
/// @param _gcfg Configuration for the dispute game to create.
/// @return The game constructor arguments.
function _makeGameArgs(
uint256 _l2ChainId,
IAnchorStateRegistry _anchorStateRegistry,
IDelayedWETH _delayedWETH,
IOPContractsManagerUtils.DisputeGameConfig memory _gcfg
)
internal
view
returns (bytes memory)
{
return abi.decode(
_staticcall(
abi.encodeCall(
IOPContractsManagerUtils.makeGameArgs, (_l2ChainId, _anchorStateRegistry, _delayedWETH, _gcfg)
)
),
(bytes)
);
}
}
src/L1/opcm/StandardValidatorUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
// Libraries
import { LibString } from "@solady/utils/LibString.sol";
import { GameType, Claim, GameTypes, Hash } from "src/dispute/lib/Types.sol";
import { Duration } from "src/dispute/lib/LibUDT.sol";
import { Constants } from "src/libraries/Constants.sol";
// Interfaces
import { ISystemConfig } from "interfaces/L1/ISystemConfig.sol";
import { IDisputeGameFactory } from "interfaces/dispute/IDisputeGameFactory.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IOptimismMintableERC20Factory } from "interfaces/universal/IOptimismMintableERC20Factory.sol";
import { IL1StandardBridge } from "interfaces/L1/IL1StandardBridge.sol";
import { IOptimismPortal2 } from "interfaces/L1/IOptimismPortal2.sol";
import { IPreimageOracle } from "interfaces/cannon/IPreimageOracle.sol";
import { IMIPS64 } from "interfaces/cannon/IMIPS64.sol";
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.sol";
import { IBigStepper } from "interfaces/dispute/IBigStepper.sol";
uint256 constant EXPECTED_MAX_GAME_DEPTH = 73;
uint256 constant EXPECTED_SPLIT_DEPTH = 30;
uint256 constant EXPECTED_CLOCK_EXTENSION = 10800;
uint256 constant EXPECTED_MAX_CLOCK_DURATION = 302400;
string constant EXPECTED_PREIMAGE_ORACLE_VERSION = "1.1.5";
uint256 constant EXPECTED_CHALLENGE_PERIOD = 86400;
uint256 constant EXPECTED_MIN_PROPOSAL_SIZE = 126000;
uint256 constant EXPECTED_MIN_PROOF_MATURITY_DELAY_SECONDS = 86400;
uint256 constant EXPECTED_MAX_PROOF_MATURITY_DELAY_SECONDS = 604800;
uint256 constant EXPECTED_MIN_DISPUTE_GAME_FINALITY_DELAY_SECONDS = 43200;
uint256 constant EXPECTED_MAX_DISPUTE_GAME_FINALITY_DELAY_SECONDS = 302400;
uint256 constant EXPECTED_MIN_WITHDRAWAL_DELAY_SECONDS = 43200;
uint256 constant EXPECTED_MAX_WITHDRAWAL_DELAY_SECONDS = 604800;
/// @notice Struct containing the unified game args for a dispute game implementation.
struct DisputeGameImplementation {
address gameAddress;
uint256 maxGameDepth;
uint256 splitDepth;
Duration maxClockDuration;
Duration clockExtension;
GameType gameType;
// extra args
uint256 l2SequenceNumber;
// dispute-game v2 game args
Claim absolutePrestate;
IBigStepper vm;
IAnchorStateRegistry asr;
IDelayedWETH weth;
uint256 l2ChainId;
address challenger;
address proposer;
}
/// @notice Arguments passed to `assertValidDisputeGame`.
struct DisputeGameValidationArgs {
string errors;
ISystemConfig sysCfg;
DisputeGameImplementation game;
bytes32 absolutePrestate;
uint256 l2ChainID;
IProxyAdmin admin;
GameType gameType;
string errorPrefix;
}
/// @notice Struct containing the simplified game args for a super permissioned dispute game implementation.
struct SuperPermissionedDisputeGameImplementation {
address gameAddress;
IAnchorStateRegistry asr;
address proposer;
}
/// @notice Arguments passed to `assertValidSuperPermissionedDisputeGame`.
struct SuperPermissionedDisputeGameValidationArgs {
string errors;
ISystemConfig sysCfg;
SuperPermissionedDisputeGameImplementation game;
IProxyAdmin admin;
address expectedProposer;
string errorPrefix;
}
/// @notice Implementation addresses used when validating a super permissioned dispute game.
struct SuperPermissionedDisputeGameImpls {
address expectedGameImpl;
address anchorStateRegistryImpl;
}
/// @notice Implementation addresses used when validating a dispute game (resolved by caller).
struct DisputeGameImpls {
address expectedGameImpl;
address mipsImpl;
address delayedWETHImpl;
address anchorStateRegistryImpl;
}
/// @notice Config values used when validating a dispute game (resolved by caller).
struct DisputeGameConfig {
address l1PAOMultisig;
}
/// @title StandardValidatorUtils
/// @notice StandardValidatorUtils is a contract that provides some validation logic
/// for the OPContractsManagerStandardValidator to split the bytecode across multiple
/// contracts to meet the EIP-170 bytecode size limit
contract StandardValidatorUtils {
/// @notice Appends `_message` to `_errors` when `_condition` is false; otherwise returns
/// `_errors` unchanged. Used to accumulate validation failures without reverting.
function internalRequire(
bool _condition,
string memory _message,
string memory _errors
)
internal
pure
returns (string memory errors_)
{
if (_condition) {
return _errors;
}
if (bytes(_errors).length == 0) {
errors_ = _message;
} else {
errors_ = string.concat(_errors, ",", _message);
}
}
/// @notice Returns the expected ETHLockbox for a chain.
function expectedETHLockbox(ISystemConfig _sysCfg) internal view returns (address) {
IOptimismPortal2 portal = IOptimismPortal2(payable(_sysCfg.optimismPortal()));
return address(portal.ethLockbox());
}
/// @notice Asserts that the SuperchainConfig contract is valid.
function assertValidSuperchainConfig(
string memory _errors,
ISuperchainConfig _superchainConfig
)
external
view
returns (string memory)
{
_errors = internalRequire(!_superchainConfig.paused(address(0)), "SPRCFG-10", _errors);
return _errors;
}
/// @notice Asserts that the ProxyAdmin contract is valid.
function assertValidProxyAdmin(
string memory _errors,
IProxyAdmin _admin,
address _l1PAOMultisig
)
external
view
returns (string memory)
{
_errors = internalRequire(_admin.owner() == _l1PAOMultisig, "PROXYA-10", _errors);
return _errors;
}
/// @notice Asserts that dispute games are correctly configured for super root mode.
function assertValidSuperRootDisputeGames(
string memory _errors,
ISystemConfig _sysCfg
)
external
view
returns (string memory)
{
IDisputeGameFactory dgf = IDisputeGameFactory(_sysCfg.disputeGameFactory());
_errors = internalRequire(address(dgf.gameImpls(GameTypes.CANNON)) == address(0), "PLDG-SHAPE", _errors);
_errors =
internalRequire(address(dgf.gameImpls(GameTypes.PERMISSIONED_CANNON)) == address(0), "PDDG-SHAPE", _errors);
_errors = internalRequire(address(dgf.gameImpls(GameTypes.CANNON_KONA)) == address(0), "CKDG-SHAPE", _errors);
_errors = internalRequire(address(dgf.gameImpls(GameTypes.SUPER_CANNON)) == address(0), "SCDG-SHAPE", _errors);
_errors =
internalRequire(address(dgf.gameImpls(GameTypes.SUPER_PERMISSIONED)) != address(0), "SPDG-SHAPE", _errors);
// At least one permissionless super game must be registered: SUPER_CANNON_KONA or
// ZK_DISPUTE_GAME.
_errors = internalRequire(
address(dgf.gameImpls(GameTypes.SUPER_CANNON_KONA)) != address(0)
|| address(dgf.gameImpls(GameTypes.ZK_DISPUTE_GAME)) != address(0),
"DF-60",
_errors
);
return _errors;
}
/// @notice Asserts that super game types are NOT registered in non-super-root mode.
function assertValidNonSuperRootDisputeGames(
string memory _errors,
ISystemConfig _sysCfg
)
external
view
returns (string memory)
{
IDisputeGameFactory dgf = IDisputeGameFactory(_sysCfg.disputeGameFactory());
_errors = internalRequire(address(dgf.gameImpls(GameTypes.CANNON)) == address(0), "PLDG-NOSHAPE", _errors);
_errors = internalRequire(address(dgf.gameImpls(GameTypes.SUPER_CANNON)) == address(0), "SCDG-NOSHAPE", _errors);
_errors = internalRequire(
address(dgf.gameImpls(GameTypes.SUPER_PERMISSIONED)) == address(0), "SPDG-NOSHAPE", _errors
);
_errors = internalRequire(
address(dgf.gameImpls(GameTypes.SUPER_CANNON_KONA)) == address(0), "SCKDG-NOSHAPE", _errors
);
_errors =
internalRequire(address(dgf.gameImpls(GameTypes.ZK_DISPUTE_GAME)) == address(0), "ZKDG-NOSHAPE", _errors);
_errors = internalRequire(
address(dgf.gameImpls(GameTypes.PERMISSIONED_CANNON)) != address(0), "PDDG-NOSHAPE", _errors
);
_errors = internalRequire(address(dgf.gameImpls(GameTypes.CANNON_KONA)) != address(0), "CKDG-NOSHAPE", _errors);
return _errors;
}
/// @notice Asserts that the MipsVm contract is valid.
function assertValidMipsVm(
string memory _errors,
IMIPS64 _mips,
address _mipsImpl,
string memory _errorPrefix
)
public
view
returns (string memory)
{
_errorPrefix = string.concat(_errorPrefix, "-VM");
_errors = internalRequire(address(_mips) == _mipsImpl, string.concat(_errorPrefix, "-10"), _errors);
_errors = internalRequire(
LibString.eq(ISemver(address(_mips)).version(), ISemver(_mipsImpl).version()),
string.concat(_errorPrefix, "-20"),
_errors
);
_errors = internalRequire(_mips.stateVersion() == 8, string.concat(_errorPrefix, "-30"), _errors);
return _errors;
}
/// @notice Asserts that the OptimismMintableERC20Factory contract is valid.
function assertValidOptimismMintableERC20Factory(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl
)
external
view
returns (string memory)
{
IOptimismMintableERC20Factory _factory = IOptimismMintableERC20Factory(_sysCfg.optimismMintableERC20Factory());
_errors = internalRequire(
LibString.eq(ISemver(address(_factory)).version(), ISemver(_impl).version()), "MERC20F-10", _errors
);
_errors = internalRequire(_admin.getProxyImplementation(address(_factory)) == _impl, "MERC20F-20", _errors);
IL1StandardBridge _bridge = IL1StandardBridge(payable(_sysCfg.l1StandardBridge()));
_errors = internalRequire(_factory.BRIDGE() == address(_bridge), "MERC20F-30", _errors);
_errors = internalRequire(_factory.bridge() == address(_bridge), "MERC20F-40", _errors);
return _errors;
}
/// @notice Asserts that the DisputeGameFactory contract is valid.
function assertValidDisputeGameFactory(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl,
address _l1PAOMultisig
)
external
view
returns (string memory)
{
IDisputeGameFactory _factory = IDisputeGameFactory(_sysCfg.disputeGameFactory());
_errors = internalRequire(
LibString.eq(ISemver(address(_factory)).version(), ISemver(_impl).version()), "DF-10", _errors
);
_errors = internalRequire(_admin.getProxyImplementation(address(_factory)) == _impl, "DF-20", _errors);
_errors = internalRequire(_factory.owner() == _l1PAOMultisig, "DF-30", _errors);
_errors = internalRequire(IProxyAdminOwnedBase(address(_factory)).proxyAdmin() == _admin, "DF-40", _errors);
// At least one permissioned game must be registered — either the legacy
// PERMISSIONED_CANNON or the super-root SUPER_PERMISSIONED.
_errors = internalRequire(
address(_factory.gameImpls(GameTypes.PERMISSIONED_CANNON)) != address(0)
|| address(_factory.gameImpls(GameTypes.SUPER_PERMISSIONED)) != address(0),
"DF-50",
_errors
);
return _errors;
}
/// @notice Asserts that the OptimismPortal contract is valid.
function assertValidOptimismPortal(
string memory _errors,
ISystemConfig _sysCfg,
IProxyAdmin _admin,
address _impl
)
external
view
returns (string memory)
{
IOptimismPortal2 _portal = IOptimismPortal2(payable(_sysCfg.optimismPortal()));
_errors = internalRequire(
LibString.eq(ISemver(address(_portal)).version(), ISemver(_impl).version()), "PORTAL-10", _errors
);
_errors = internalRequire(_admin.getProxyImplementation(address(_portal)) == _impl, "PORTAL-20", _errors);
_errors = internalRequire(address(_portal.systemConfig()) == address(_sysCfg), "PORTAL-40", _errors);
_errors = internalRequire(_portal.l2Sender() == Constants.DEFAULT_L2_SENDER, "PORTAL-80", _errors);
_errors = internalRequire(IProxyAdminOwnedBase(address(_portal)).proxyAdmin() == _admin, "PORTAL-90", _errors);
// The proof maturity delay is per chain and "standard" means within the configured bounds.
uint256 proofMaturityDelay = _portal.proofMaturityDelaySeconds();
_errors = internalRequire(
proofMaturityDelay >= EXPECTED_MIN_PROOF_MATURITY_DELAY_SECONDS
&& proofMaturityDelay <= EXPECTED_MAX_PROOF_MATURITY_DELAY_SECONDS,
"PORTAL-100",
_errors
);
// TODO(optimism-private#744): assert the portal's bridge hook once OPCM configures hooks.
return _errors;
}
/// @notice Asserts that the PreimageOracle contract is valid.
function assertValidPreimageOracle(
string memory _errors,
IPreimageOracle _oracle,
string memory _errorPrefix
)
public
view
returns (string memory)
{
_errorPrefix = string.concat(_errorPrefix, "-PIMGO");
_errors = internalRequire(
LibString.eq(ISemver(address(_oracle)).version(), EXPECTED_PREIMAGE_ORACLE_VERSION),
string.concat(_errorPrefix, "-10"),
_errors
);
_errors = internalRequire(
_oracle.challengePeriod() == EXPECTED_CHALLENGE_PERIOD, string.concat(_errorPrefix, "-20"), _errors
);
_errors = internalRequire(
_oracle.minProposalSize() == EXPECTED_MIN_PROPOSAL_SIZE, string.concat(_errorPrefix, "-30"), _errors
);
return _errors;
}
/// @notice Asserts that the DelayedWETH contract is valid.
function assertValidDelayedWETH(
string memory _errors,
ISystemConfig _sysCfg,
IDelayedWETH _weth,
IProxyAdmin _admin,
address _l1PAOMultisig,
address _delayedWETHImpl,
string memory _errorPrefix
)
public
view
returns (string memory)
{
_errorPrefix = string.concat(_errorPrefix, "-DWETH");
_errors = internalRequire(
LibString.eq(ISemver(address(_weth)).version(), ISemver(_delayedWETHImpl).version()),
string.concat(_errorPrefix, "-10"),
_errors
);
_errors = internalRequire(
_admin.getProxyImplementation(address(_weth)) == _delayedWETHImpl,
string.concat(_errorPrefix, "-20"),
_errors
);
_errors =
internalRequire(_weth.proxyAdminOwner() == _l1PAOMultisig, string.concat(_errorPrefix, "-30"), _errors);
// The withdrawal delay is per chain; "standard" means within the sanctioned range.
uint256 withdrawalDelay = _weth.delay();
_errors = internalRequire(
withdrawalDelay >= EXPECTED_MIN_WITHDRAWAL_DELAY_SECONDS
&& withdrawalDelay <= EXPECTED_MAX_WITHDRAWAL_DELAY_SECONDS,
string.concat(_errorPrefix, "-40"),
_errors
);
_errors = internalRequire(
address(_weth.ethLockbox()) == expectedETHLockbox(_sysCfg), string.concat(_errorPrefix, "-50"), _errors
);
_errors = internalRequire(
IProxyAdminOwnedBase(address(_weth)).proxyAdmin() == _admin, string.concat(_errorPrefix, "-60"), _errors
);
_errors = internalRequire(address(_weth) == _sysCfg.delayedWETH(), string.concat(_errorPrefix, "-70"), _errors);
return _errors;
}
/// @notice Asserts that the AnchorStateRegistry contract is valid.
function assertValidAnchorStateRegistry(
string memory _errors,
ISystemConfig _sysCfg,
IDisputeGameFactory _dgf,
IAnchorStateRegistry _asr,
IProxyAdmin _admin,
address _anchorStateRegistryImpl,
string memory _errorPrefix
)
public
view
returns (string memory)
{
_errorPrefix = string.concat(_errorPrefix, "-ANCHORP");
_errors = internalRequire(
LibString.eq(ISemver(address(_asr)).version(), ISemver(_anchorStateRegistryImpl).version()),
string.concat(_errorPrefix, "-10"),
_errors
);
_errors = internalRequire(
_admin.getProxyImplementation(address(_asr)) == _anchorStateRegistryImpl,
string.concat(_errorPrefix, "-20"),
_errors
);
_errors = internalRequire(
address(_asr.disputeGameFactory()) == address(_dgf), string.concat(_errorPrefix, "-30"), _errors
);
_errors = internalRequire(
address(_asr.ethLockbox()) == expectedETHLockbox(_sysCfg), string.concat(_errorPrefix, "-40"), _errors
);
_errors = internalRequire(
IProxyAdminOwnedBase(address(_asr)).proxyAdmin() == _admin, string.concat(_errorPrefix, "-50"), _errors
);
_errors = internalRequire(_asr.retirementTimestamp() > 0, string.concat(_errorPrefix, "-60"), _errors);
// The registry a game anchors against must be the one the portal consults when finalizing
// withdrawals. Without this, a game could snapshot the respected game type of a second,
// locally valid registry that the portal never reads.
_errors = internalRequire(
IOptimismPortal2(payable(_sysCfg.optimismPortal())).anchorStateRegistry() == _asr,
string.concat(_errorPrefix, "-70"),
_errors
);
// The finality delay is per chain and "standard" means within the configured bounds.
uint256 finalityDelay = _asr.disputeGameFinalityDelaySeconds();
_errors = internalRequire(
finalityDelay >= EXPECTED_MIN_DISPUTE_GAME_FINALITY_DELAY_SECONDS
&& finalityDelay <= EXPECTED_MAX_DISPUTE_GAME_FINALITY_DELAY_SECONDS,
string.concat(_errorPrefix, "-80"),
_errors
);
return _errors;
}
/// @notice Asserts that a DisputeGame contract is valid. Drills into WETH, ASR, MIPS, and
/// PreimageOracle validation. Caller resolves storage-dependent values via the
/// `DisputeGameImpls` and `DisputeGameConfig` structs.
function assertValidDisputeGame(
DisputeGameValidationArgs memory _args,
DisputeGameImpls memory _impls,
DisputeGameConfig memory _cfg
)
public
view
returns (string memory errors_)
{
errors_ = _args.errors;
string memory errorPrefix = _args.errorPrefix;
DisputeGameImplementation memory game = _args.game;
(Hash anchorRoot,) = game.asr.getAnchorRoot();
IDisputeGameFactory dgf = IDisputeGameFactory(_args.sysCfg.disputeGameFactory());
errors_ = internalRequire(
LibString.eq(ISemver(game.gameAddress).version(), ISemver(_impls.expectedGameImpl).version()),
string.concat(errorPrefix, "-20"),
errors_
);
errors_ =
internalRequire(game.gameAddress == _impls.expectedGameImpl, string.concat(errorPrefix, "-150"), errors_);
errors_ = internalRequire(
GameType.unwrap(game.gameType) == GameType.unwrap(_args.gameType),
string.concat(errorPrefix, "-30"),
errors_
);
errors_ = internalRequire(
Claim.unwrap(game.absolutePrestate) == _args.absolutePrestate, string.concat(errorPrefix, "-40"), errors_
);
// Super game types store l2ChainId=0 in game args because the chain ID is embedded
// in the super root proof extraData, not in the game args.
uint256 expectedL2ChainId = GameTypes.isSuperGame(_args.gameType) ? 0 : _args.l2ChainID;
errors_ = internalRequire(game.l2ChainId == expectedL2ChainId, string.concat(errorPrefix, "-60"), errors_);
errors_ = internalRequire(game.l2SequenceNumber == 0, string.concat(errorPrefix, "-70"), errors_);
errors_ = internalRequire(
Duration.unwrap(game.clockExtension) == EXPECTED_CLOCK_EXTENSION, string.concat(errorPrefix, "-80"), errors_
);
errors_ = internalRequire(game.splitDepth == EXPECTED_SPLIT_DEPTH, string.concat(errorPrefix, "-90"), errors_);
errors_ =
internalRequire(game.maxGameDepth == EXPECTED_MAX_GAME_DEPTH, string.concat(errorPrefix, "-100"), errors_);
errors_ = internalRequire(
Duration.unwrap(game.maxClockDuration) == EXPECTED_MAX_CLOCK_DURATION,
string.concat(errorPrefix, "-110"),
errors_
);
errors_ = internalRequire(Hash.unwrap(anchorRoot) != bytes32(0), string.concat(errorPrefix, "-120"), errors_);
errors_ = assertValidDelayedWETH(
errors_, _args.sysCfg, game.weth, _args.admin, _cfg.l1PAOMultisig, _impls.delayedWETHImpl, errorPrefix
);
errors_ = assertValidAnchorStateRegistry(
errors_, _args.sysCfg, dgf, game.asr, _args.admin, _impls.anchorStateRegistryImpl, errorPrefix
);
errors_ = assertValidMipsVm(errors_, IMIPS64(address(game.vm)), _impls.mipsImpl, errorPrefix);
// Only assert valid preimage oracle if the game VM is valid, since otherwise
// the contract is likely to revert.
if (address(game.vm) == _impls.mipsImpl) {
errors_ = assertValidPreimageOracle(errors_, game.vm.oracle(), errorPrefix);
}
return errors_;
}
/// @notice Asserts that a simplified SuperPermissionedDisputeGame contract is valid.
function assertValidSuperPermissionedDisputeGame(
SuperPermissionedDisputeGameValidationArgs memory _args,
SuperPermissionedDisputeGameImpls memory _impls
)
public
view
returns (string memory errors_)
{
errors_ = _args.errors;
string memory errorPrefix = _args.errorPrefix;
SuperPermissionedDisputeGameImplementation memory game = _args.game;
(Hash anchorRoot,) = game.asr.getAnchorRoot();
IDisputeGameFactory dgf = IDisputeGameFactory(_args.sysCfg.disputeGameFactory());
errors_ = internalRequire(
LibString.eq(ISemver(game.gameAddress).version(), ISemver(_impls.expectedGameImpl).version()),
string.concat(errorPrefix, "-20"),
errors_
);
errors_ =
internalRequire(game.gameAddress == _impls.expectedGameImpl, string.concat(errorPrefix, "-150"), errors_);
errors_ = internalRequire(Hash.unwrap(anchorRoot) != bytes32(0), string.concat(errorPrefix, "-120"), errors_);
errors_ = assertValidAnchorStateRegistry(
errors_, _args.sysCfg, dgf, game.asr, _args.admin, _impls.anchorStateRegistryImpl, errorPrefix
);
errors_ = internalRequire(game.proposer == _args.expectedProposer, string.concat(errorPrefix, "-140"), errors_);
return errors_;
}
}
src/cannon/libraries/CannonTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
using LPPMetadataLib for LPPMetaData global;
/// @notice Packed LPP metadata.
/// ┌─────────────┬────────────────────────────────────────────┐
/// │ Bit Offsets │ Description │
/// ├─────────────┼────────────────────────────────────────────┤
/// │ [0, 64) │ Timestamp (Finalized - All data available) │
/// │ [64, 96) │ Part Offset │
/// │ [96, 128) │ Claimed Size │
/// │ [128, 160) │ Blocks Processed (Inclusive of Padding) │
/// │ [160, 192) │ Bytes Processed (Non-inclusive of Padding) │
/// │ [192, 256) │ Countered │
/// └─────────────┴────────────────────────────────────────────┘
type LPPMetaData is bytes32;
/// @notice LPP metadata UDT extension functions.
library LPPMetadataLib {
uint256 private constant U64_MASK = 0xFFFFFFFFFFFFFFFF;
uint256 private constant U32_MASK = 0xFFFFFFFF;
function setTimestamp(LPPMetaData _self, uint64 _timestamp) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(shl(192, _timestamp), and(_self, not(shl(192, U64_MASK))))
}
}
function setPartOffset(LPPMetaData _self, uint32 _partOffset) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(shl(160, _partOffset), and(_self, not(shl(160, U32_MASK))))
}
}
function setClaimedSize(LPPMetaData _self, uint32 _claimedSize) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(shl(128, _claimedSize), and(_self, not(shl(128, U32_MASK))))
}
}
function setBlocksProcessed(LPPMetaData _self, uint32 _blocksProcessed) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(shl(96, _blocksProcessed), and(_self, not(shl(96, U32_MASK))))
}
}
function setBytesProcessed(LPPMetaData _self, uint32 _bytesProcessed) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(shl(64, _bytesProcessed), and(_self, not(shl(64, U32_MASK))))
}
}
function setCountered(LPPMetaData _self, bool _countered) internal pure returns (LPPMetaData self_) {
assembly {
self_ := or(_countered, and(_self, not(U64_MASK)))
}
}
function timestamp(LPPMetaData _self) internal pure returns (uint64 timestamp_) {
assembly {
timestamp_ := shr(192, _self)
}
}
function partOffset(LPPMetaData _self) internal pure returns (uint64 partOffset_) {
assembly {
partOffset_ := and(shr(160, _self), U32_MASK)
}
}
function claimedSize(LPPMetaData _self) internal pure returns (uint32 claimedSize_) {
assembly {
claimedSize_ := and(shr(128, _self), U32_MASK)
}
}
function blocksProcessed(LPPMetaData _self) internal pure returns (uint32 blocksProcessed_) {
assembly {
blocksProcessed_ := and(shr(96, _self), U32_MASK)
}
}
function bytesProcessed(LPPMetaData _self) internal pure returns (uint32 bytesProcessed_) {
assembly {
bytesProcessed_ := and(shr(64, _self), U32_MASK)
}
}
function countered(LPPMetaData _self) internal pure returns (bool countered_) {
assembly {
countered_ := and(_self, U64_MASK)
}
}
}
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/Blueprint.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Bytes } from "src/libraries/Bytes.sol";
/// @notice Methods for working with ERC-5202 blueprint contracts.
/// https://eips.ethereum.org/EIPS/eip-5202
library Blueprint {
/// @notice The structure of a blueprint contract per ERC-5202.
struct Preamble {
uint8 ercVersion;
bytes preambleData;
bytes initcode;
}
/// @notice Thrown when converting a bytes array to a uint256 and the bytes array is too long.
error BytesArrayTooLong();
/// @notice Throw when contract deployment fails.
error DeploymentFailed();
/// @notice Thrown when parsing a blueprint preamble and the resulting initcode is empty.
error EmptyInitcode();
/// @notice Thrown when call to the identity precompile fails.
error IdentityPrecompileCallFailed();
/// @notice Thrown when parsing a blueprint preamble and the bytecode does not contain the expected prefix bytes.
error NotABlueprint();
/// @notice Thrown when parsing a blueprint preamble and the reserved bits are set.
error ReservedBitsSet();
/// @notice Thrown when parsing a blueprint preamble and the preamble data is not empty.
/// We do not use the preamble data, so it's expected to be empty.
error UnexpectedPreambleData(bytes data);
/// @notice Thrown during deployment if the ERC version is not supported.
error UnsupportedERCVersion(uint8 version);
/// @notice Takes the desired initcode for a blueprint as a parameter, and returns EVM code
/// which will deploy a corresponding blueprint contract (with no data section). Based on the
/// reference implementation in https://eips.ethereum.org/EIPS/eip-5202.
function blueprintDeployerBytecode(bytes memory _initcode) internal pure returns (bytes memory) {
// Check that the initcode is not empty.
if (_initcode.length == 0) revert EmptyInitcode();
bytes memory blueprintPreamble = hex"FE7100"; // ERC-5202 preamble.
bytes memory blueprintBytecode = bytes.concat(blueprintPreamble, _initcode);
// The length of the deployed code in bytes.
bytes2 lenBytes = bytes2(uint16(blueprintBytecode.length));
// Copy <blueprintBytecode> to memory and `RETURN` it per EVM creation semantics.
// PUSH2 <len> RETURNDATASIZE DUP2 PUSH1 10 RETURNDATASIZE CODECOPY RETURN
bytes memory deployBytecode = bytes.concat(hex"61", lenBytes, hex"3d81600a3d39f3");
return bytes.concat(deployBytecode, blueprintBytecode);
}
/// @notice Given bytecode as a sequence of bytes, parse the blueprint preamble and deconstruct
/// the bytecode into the ERC version, preamble data and initcode. Reverts if the bytecode is
/// not a valid blueprint contract according to ERC-5202.
function parseBlueprintPreamble(bytes memory _bytecode) internal view returns (Preamble memory) {
if (_bytecode.length < 2 || _bytecode[0] != 0xFE || _bytecode[1] != 0x71) {
revert NotABlueprint();
}
uint8 ercVersion = uint8(_bytecode[2] & 0xFC) >> 2;
uint8 nLengthBytes = uint8(_bytecode[2] & 0x03);
if (nLengthBytes == 0x03) revert ReservedBitsSet();
uint256 dataLength = 0;
if (nLengthBytes > 0) {
bytes memory lengthBytes = new bytes(nLengthBytes);
for (uint256 i = 0; i < nLengthBytes; i++) {
lengthBytes[i] = _bytecode[3 + i];
}
dataLength = bytesToUint(lengthBytes);
}
bytes memory preambleData = new bytes(dataLength);
if (nLengthBytes != 0) {
uint256 dataStart = 3 + nLengthBytes;
// This loop is very small, so not worth using the identity precompile like we do with initcode below.
for (uint256 i = 0; i < dataLength; i++) {
preambleData[i] = _bytecode[dataStart + i];
}
}
// Parsing the initcode byte-by-byte is too costly for long initcode, so we perform a staticcall
// to the identity precompile at address(0x04) to copy the initcode.
uint256 initcodeStart = 3 + nLengthBytes + dataLength;
uint256 initcodeLength = _bytecode.length - initcodeStart;
if (initcodeLength == 0) revert EmptyInitcode();
bytes memory initcode = new bytes(initcodeLength);
bool success;
assembly ("memory-safe") {
// Calculate the memory address of the input data (initcode) within _bytecode.
// - add(_bytecode, 32): Moves past the length field to the start of _bytecode's data.
// - add(..., initcodeStart): Adds the offset to reach the initcode within _bytecode.
let inputData := add(add(_bytecode, 32), initcodeStart)
// Calculate the memory address for the output data in initcode.
let outputData := add(initcode, 32)
// Perform the staticcall to the identity precompile.
success := staticcall(gas(), 0x04, inputData, initcodeLength, outputData, initcodeLength)
}
if (!success) revert IdentityPrecompileCallFailed();
return Preamble(ercVersion, preambleData, initcode);
}
/// @notice Parses the code at the given `_target` as a blueprint and deploys the resulting initcode.
/// This version of `deployFrom` is used when the initcode requires no constructor arguments.
function deployFrom(address _target, bytes32 _salt) internal returns (address) {
return deployFrom(_target, _salt, new bytes(0));
}
/// @notice Parses the code at the given `_target` as a blueprint and deploys the resulting initcode
/// with the given `_data` appended, i.e. `_data` is the ABI-encoded constructor arguments.
function deployFrom(address _target, bytes32 _salt, bytes memory _data) internal returns (address newContract_) {
Preamble memory preamble = parseBlueprintPreamble(address(_target).code);
if (preamble.ercVersion != 0) revert UnsupportedERCVersion(preamble.ercVersion);
if (preamble.preambleData.length != 0) revert UnexpectedPreambleData(preamble.preambleData);
bytes memory initcode = bytes.concat(preamble.initcode, _data);
assembly ("memory-safe") {
newContract_ := create2(0, add(initcode, 0x20), mload(initcode), _salt)
}
if (newContract_ == address(0)) revert DeploymentFailed();
}
/// @notice Parses the code at two target addresses as individual blueprints, concatenates them and then deploys
/// the resulting initcode with the given `_data` appended, i.e. `_data` is the ABI-encoded constructor arguments.
function deployFrom(
address _target1,
address _target2,
bytes32 _salt,
bytes memory _data
)
internal
returns (address newContract_)
{
Preamble memory preamble1 = parseBlueprintPreamble(address(_target1).code);
if (preamble1.ercVersion != 0) revert UnsupportedERCVersion(preamble1.ercVersion);
if (preamble1.preambleData.length != 0) revert UnexpectedPreambleData(preamble1.preambleData);
Preamble memory preamble2 = parseBlueprintPreamble(address(_target2).code);
if (preamble2.ercVersion != 0) revert UnsupportedERCVersion(preamble2.ercVersion);
if (preamble2.preambleData.length != 0) revert UnexpectedPreambleData(preamble2.preambleData);
bytes memory initcode = bytes.concat(preamble1.initcode, preamble2.initcode, _data);
assembly ("memory-safe") {
newContract_ := create2(0, add(initcode, 0x20), mload(initcode), _salt)
}
if (newContract_ == address(0)) revert DeploymentFailed();
}
/// @notice Deploys a blueprint contract with the given `_rawBytecode` and `_salt`. If the blueprint is too large to
/// fit in a single deployment, it is split across two addresses. It is the responsibility of the caller to handle
/// large contracts by checking if the second return value is not address(0).
function create(
bytes memory _rawBytecode,
bytes32 _salt
)
internal
returns (address newContract1_, address newContract2_)
{
if (_rawBytecode.length <= maxInitCodeSize()) {
newContract1_ = deploySmallBytecode(blueprintDeployerBytecode(_rawBytecode), _salt);
return (newContract1_, address(0));
}
(newContract1_, newContract2_) = deployBigBytecode(_rawBytecode, _salt);
}
/// @notice Deploys a blueprint contract that can fit in a single address.
function deploySmallBytecode(bytes memory _bytecode, bytes32 _salt) internal returns (address newContract_) {
assembly ("memory-safe") {
newContract_ := create2(0, add(_bytecode, 0x20), mload(_bytecode), _salt)
}
require(newContract_ != address(0), "Blueprint: create2 failed");
}
/// @notice Deploys a two blueprint contracts, splitting the bytecode across both of them.
function deployBigBytecode(
bytes memory _bytecode,
bytes32 _salt
)
internal
returns (address newContract1_, address newContract2_)
{
uint32 maxSize = maxInitCodeSize();
bytes memory part1Slice = Bytes.slice(_bytecode, 0, maxSize);
bytes memory part1 = blueprintDeployerBytecode(part1Slice);
bytes memory part2Slice = Bytes.slice(_bytecode, maxSize, _bytecode.length - maxSize);
bytes memory part2 = blueprintDeployerBytecode(part2Slice);
newContract1_ = deploySmallBytecode(part1, _salt);
newContract2_ = deploySmallBytecode(part2, _salt);
}
/// @notice Convert a bytes array to a uint256.
function bytesToUint(bytes memory _b) internal pure returns (uint256) {
if (_b.length > 32) revert BytesArrayTooLong();
uint256 number;
for (uint256 i = 0; i < _b.length; i++) {
number = number + uint256(uint8(_b[i])) * (2 ** (8 * (_b.length - (i + 1))));
}
return number;
}
/// @notice Returns the maximum init code size for each blueprint. The preamble needs 3 bytes.
function maxInitCodeSize() internal pure returns (uint32) {
// Technically this should be 24576 - 3 (max minus preamble size) but we use 23500 here to
// resolve a discrepancy that can occur between development and production builds.
return 23500;
}
}
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/Bytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Bytes
/// @notice Bytes is a library for manipulating byte arrays.
library Bytes {
/// @custom:attribution https://github.com/GNSPS/solidity-bytes-utils
/// @notice Slices a byte array with a given starting index and length. Returns a new byte array
/// as opposed to a pointer to the original array. Will throw if trying to slice more
/// bytes than exist in the array.
/// @param _bytes Byte array to slice.
/// @param _start Starting index of the slice.
/// @param _length Length of the slice.
/// @return Slice of the input byte array.
function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) {
unchecked {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
}
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} { mstore(mc, mload(cc)) }
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/// @notice Slices a byte array with a given starting index up to the end of the original byte
/// array. Returns a new array rather than a pointer to the original.
/// @param _bytes Byte array to slice.
/// @param _start Starting index of the slice.
/// @return Slice of the input byte array.
function slice(bytes memory _bytes, uint256 _start) internal pure returns (bytes memory) {
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
/// @notice Converts a byte array into a nibble array by splitting each byte into two nibbles.
/// Resulting nibble array will be exactly twice as long as the input byte array.
/// @param _bytes Input byte array to convert.
/// @return Resulting nibble array.
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory _nibbles;
assembly {
// Grab a free memory offset for the new array
_nibbles := mload(0x40)
// Load the length of the passed bytes array from memory
let bytesLength := mload(_bytes)
// Calculate the length of the new nibble array
// This is the length of the input array times 2
let nibblesLength := shl(0x01, bytesLength)
// Update the free memory pointer to allocate memory for the new array.
// To do this, we add the length of the new array + 32 bytes for the array length
// rounded up to the nearest 32 byte boundary to the current free memory pointer.
mstore(0x40, add(_nibbles, and(not(0x1F), add(nibblesLength, 0x3F))))
// Store the length of the new array in memory
mstore(_nibbles, nibblesLength)
// Store the memory offset of the _bytes array's contents on the stack
let bytesStart := add(_bytes, 0x20)
// Store the memory offset of the nibbles array's contents on the stack
let nibblesStart := add(_nibbles, 0x20)
// Loop through each byte in the input array
for { let i := 0x00 } lt(i, bytesLength) { i := add(i, 0x01) } {
// Get the starting offset of the next 2 bytes in the nibbles array
let offset := add(nibblesStart, shl(0x01, i))
// Load the byte at the current index within the `_bytes` array
let b := byte(0x00, mload(add(bytesStart, i)))
// Pull out the first nibble and store it in the new array
mstore8(offset, shr(0x04, b))
// Pull out the second nibble and store it in the new array
mstore8(add(offset, 0x01), and(b, 0x0F))
}
}
return _nibbles;
}
/// @notice Compares two byte arrays by comparing their keccak256 hashes.
/// @param _bytes First byte array to compare.
/// @param _other Second byte array to compare.
/// @return True if the two byte arrays are equal, false otherwise.
function equal(bytes memory _bytes, bytes memory _other) internal pure returns (bool) {
return keccak256(_bytes) == keccak256(_other);
}
}
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 ERC-165 interface ID of OptimismMintableERC721 tokens built from source between
/// September 2022 and Bedrock. Those tokens can't be upgraded, so this ID must be
/// accepted forever.
bytes4 internal constant PRE_BEDROCK_OPTIMISM_MINTABLE_ERC721_INTERFACE_ID = 0xe49bc7f8;
/// @notice ERC-165 interface ID of OptimismMintableERC721 tokens built from source between
/// Bedrock and op-contracts v1.8.0. Those tokens can't be upgraded, so this ID must be
/// accepted forever. Newer tokens answer it too, so that older bridges accept them.
bytes4 internal constant BEDROCK_OPTIMISM_MINTABLE_ERC721_INTERFACE_ID = 0x74259ebf;
/// @notice ERC-165 interface ID answered by OptimismMintableERC721 tokens built from
/// op-contracts v1.8.0 source onwards. Written as a literal because
/// type(IOptimismMintableERC721) changes whenever the contract's ABI does.
bytes4 internal constant OPTIMISM_MINTABLE_ERC721_INTERFACE_ID = 0xaecafc23;
/// @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/DevFeatures.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Library of constants representing development features. We use a 32 byte bitmap because
/// it's easier to integrate with op-deployer. Note that users should typically set a
/// single nibble to 1 and the rest to zero, which gives us 64 potential features, like:
/// 0x0000000000000000000000000000000000000000000000000000000000000001
/// 0x0000000000000000000000000000000000000000000000000000000000000010
/// 0x0000000000000000000000000000000000000000000000000000000000000100
/// etc.
/// We'll expand to using all available bits if we need more than 64 concurrent features.
/// @dev ADDING A NEW DEV FEATURE:
/// A dev feature is wired through several files. There is no compile-time link between them.
/// Update every item below.
///
/// 1. Add the new feature bit in this file. Do not reuse a retired value unless the reuse is
/// intentional and reviewed. Retired values: 0x1 (OPTIMISM_PORTAL_INTEROP), 0x10
/// (CANNON_KONA), 0x1000 (CUSTOM_GAS_TOKEN), 0x10000 (OPCM_V2), 0x100000 (L2CM) and
/// 0x1000000 (ZK_DISPUTE_GAME).
/// 2. Add the matching Go flag in `op-core/devfeatures/devfeatures.go`. The Go value MUST
/// match the Solidity value byte-for-byte.
/// 3. Add the env var reader in `packages/contracts-bedrock/scripts/libraries/Config.sol`.
/// 4. Wire the env var into the dev feature bitmap in
/// `packages/contracts-bedrock/test/setup/FeatureFlags.sol`. Add the feature name there too.
/// 5. Add CI coverage in `.circleci/continue/main.yml` under the `&features_matrix` anchor.
/// Add combination rows when this feature interacts with another feature. Document
/// intentionally unsupported combinations near the matrix. Do not register dev features in
/// `setup-features.system_features.default`. List each new matrix job by name in the
/// `requires` of `required-contracts-ci`, or the job runs without gating the merge.
///
/// For the parallel SYSTEM feature checklist, see
/// packages/contracts-bedrock/src/libraries/Features.sol.
library DevFeatures {
/// @notice The feature that enables deployment of V2 dispute game contracts.
/// @custom:legacy
/// This feature is no longer used, but is kept here for legacy reasons.
bytes32 public constant DEPLOY_V2_DISPUTE_GAMES =
bytes32(0x0000000000000000000000000000000000000000000000000000000000000100);
/// @notice The feature that enables the super root games migration path in OPCM upgrade.
bytes32 public constant SUPER_ROOT_GAMES_MIGRATION =
bytes32(0x0000000000000000000000000000000000000000000000000000000010000000);
/// @notice The feature that enables bridge hook configuration on OptimismPortal2.
bytes32 public constant BRIDGE_HOOK = bytes32(0x0000000000000000000000000000000000000000000000000000000100000000);
/// @notice The feature that enables OP Private.
bytes32 public constant OP_PRIVATE = bytes32(0x0000000000000000000000000000000000000000000000000000001000000000);
/// @notice Checks if a feature is enabled in a bitmap. Note that this function does not check
/// that the input feature represents a single feature and the bitwise AND operation
/// allows for multiple features to be enabled at once. Users should generally check
/// for only a single feature at a time.
/// @param _bitmap The bitmap to check.
/// @param _feature The feature to check.
/// @return True if the feature is enabled, false otherwise.
function isDevFeatureEnabled(bytes32 _bitmap, bytes32 _feature) internal pure returns (bool) {
// SuperRootGamesMigration is enabled by default.
// TODO(#21662): remove with the broader SuperRootGamesMigration cleanup.
if (hasFlag(_feature, SUPER_ROOT_GAMES_MIGRATION)) return true;
return _feature != 0 && hasFlag(_bitmap, _feature);
}
/// @notice Checks if all bits of _flag are set in _features.
/// @param _features The bitmap to check against.
/// @param _flag The flag bits to look for.
/// @return True if all bits of _flag are set in _features, false otherwise.
function hasFlag(bytes32 _features, bytes32 _flag) internal pure returns (bool) {
return (_features & _flag) == _flag;
}
}
src/libraries/Features.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Features is a library that stores feature name constants. Can be used alongside the
/// feature flagging functionality in the SystemConfig contract to selectively enable or
/// disable customizable features of the OP Stack.
/// @dev ADDING A NEW SYSTEM FEATURE:
/// System feature values are read from SystemConfig on-chain.
/// Add the new feature name here first.
///
/// If the feature should be toggleable through contract-test env vars and the CI feature
/// matrix, update every applicable item below.
///
/// 1. Add the env var reader in `packages/contracts-bedrock/scripts/libraries/Config.sol`.
/// 2. Consume the reader in deployment and test setup code. Initialize SystemConfig state.
/// Search for existing `Config.sysFeature*` consumers. For `CUSTOM_GAS_TOKEN`, this includes
/// packages/contracts-bedrock/scripts/deploy/Deploy.s.sol and
/// packages/contracts-bedrock/test/setup/CommonTest.sol.
/// 3. Add the feature name in `packages/contracts-bedrock/test/setup/FeatureFlags.sol`.
/// System features are not added to resolveFeaturesFromEnv(). Their value comes from
/// SystemConfig.
/// 4. Register the feature as a system feature in `.circleci/continue/main.yml` under
/// `setup-features.system_features.default`. A missing entry exports DEV_FEATURE__<NAME>
/// instead of SYS_FEATURE__<NAME>.
/// 5. Add CI coverage in `.circleci/continue/main.yml` under the `&features_matrix` anchor.
/// Add combination rows when this feature interacts with another feature. Document
/// intentionally unsupported combinations near the matrix.
///
/// System features have no Go mirror. For the parallel DEV feature checklist, see
/// packages/contracts-bedrock/src/libraries/DevFeatures.sol.
library Features {
/// @notice The ETH_LOCKBOX feature determines whether the system uses an ETHLockbox.
bytes32 internal constant ETH_LOCKBOX = "ETH_LOCKBOX";
/// @notice The CUSTOM_GAS_TOKEN feature determines if the system is configured to use a custom
/// gas token in the OptimismPortal. When the CUSTOM_GAS_TOKEN feature is active, the
/// deposits and withdrawals of native ETH are disabled.
bytes32 internal constant CUSTOM_GAS_TOKEN = "CUSTOM_GAS_TOKEN";
/// @notice The INTEROP feature determines if the system is configured to use interop.
bytes32 internal constant INTEROP = "INTEROP";
}
src/libraries/SemverComp.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Libraries
import { LibString } from "@solady/utils/LibString.sol";
import { JSONParserLib } from "@solady/utils/JSONParserLib.sol";
/// @notice Library for comparing semver strings. Ignores prereleases and build metadata.
library SemverComp {
/// @notice Struct representing a semver string.
/// @custom:field major The major version number.
/// @custom:field minor The minor version number.
/// @custom:field patch The patch version number.
struct Semver {
uint256 major;
uint256 minor;
uint256 patch;
}
/// @notice Error thrown when a semver string has less than 3 parts.
error SemverComp_InvalidSemverParts();
/// @notice Parses a semver string into a Semver struct. Only handles the major, minor, and
/// patch numerical components, ignores prereleases and build metadata.
/// @param _semver The semver string to parse.
/// @return The parsed Semver struct.
function parse(string memory _semver) internal pure returns (Semver memory) {
string[] memory parts = LibString.split(_semver, ".");
// We need at least 3 parts to be a valid semver, but we might have more parts if the
// semver looks like "1.2.3-beta.4+build.5".
if (parts.length < 3) {
revert SemverComp_InvalidSemverParts();
}
// Split the patch component by hyphen, if it exists. We only want the first part of the
// patch. We're ignoring prereleases and build versions in this library. We're handling
// cases like 1.2.3-beta.4+build.5 as well as 1.2.3+build.5.
string[] memory patchParts = LibString.split(parts[2], "-");
string[] memory patchParts2 = LibString.split(patchParts[0], "+");
// Parse the major, minor, and patch components. JSONParserLib will revert if the
// components are not valid decimal numbers.
return Semver({
major: JSONParserLib.parseUint(parts[0]),
minor: JSONParserLib.parseUint(parts[1]),
patch: JSONParserLib.parseUint(patchParts2[0])
});
}
/// @notice Compares two semver strings (=). Ignores prereleases and build metadata.
/// @param _a The first semver string.
/// @param _b The second semver string.
/// @return True if the semver strings are equal, false otherwise.
function eq(string memory _a, string memory _b) internal pure returns (bool) {
Semver memory a = parse(_a);
Semver memory b = parse(_b);
return a.major == b.major && a.minor == b.minor && a.patch == b.patch;
}
/// @notice Compares two semver strings (<). Ignores prereleases and build metadata.
/// @param _a The first semver string.
/// @param _b The second semver string.
/// @return True if the first semver string is less than the second, false otherwise.
function lt(string memory _a, string memory _b) internal pure returns (bool) {
Semver memory a = parse(_a);
Semver memory b = parse(_b);
return a.major < b.major || (a.major == b.major && a.minor < b.minor)
|| (a.major == b.major && a.minor == b.minor && a.patch < b.patch);
}
/// @notice Compares two semver strings (<=). Ignores prereleases and build metadata.
/// @param _a The first semver string.
/// @param _b The second semver string.
/// @return True if the first semver string is less than or equal to the second, false otherwise.
function lte(string memory _a, string memory _b) internal pure returns (bool) {
return eq(_a, _b) || lt(_a, _b);
}
/// @notice Compares two semver strings (>). Ignores prereleases and build metadata.
/// @param _a The first semver string.
/// @param _b The second semver string.
/// @return True if the first semver string is greater than the second, false otherwise.
function gt(string memory _a, string memory _b) internal pure returns (bool) {
return !eq(_a, _b) && !lt(_a, _b);
}
/// @notice Compares two semver strings (>=). Ignores prereleases and build metadata.
/// @param _a The first semver string.
/// @param _b The second semver string.
/// @return True if the first semver string is greater than or equal to the second, false otherwise.
function gte(string memory _a, string memory _b) internal pure returns (bool) {
return eq(_a, _b) || gt(_a, _b);
}
/// @notice Checks if a semver string has extra tags (prerelease "-" or build metadata "+").
/// @param _semver The semver string to check.
/// @return True if the semver has extra tags, false otherwise.
function hasExtraTag(string memory _semver) internal pure returns (bool) {
return LibString.contains(_semver, "-") || LibString.contains(_semver, "+");
}
}
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
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"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.