Verified contractPartialMIT
OPContractsManagerMigrator
Address0x3f01185f5825f0f40d2e11014ef0d6458b50cd12
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.15
- Same code
2 more contracts
Details
- Compiler
- solc 0.8.15+commit.e14f2714
- Language
- solidity
- Optimization
- Yes, 5,000 runs
- EVM version
- london
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,352,304
- Creation transaction
- 0x68dd9b4174…a6cee994c9
30 files
- src/L1/opcm/OPContractsManagerMigrator.solmain28.98 KB
- interfaces/L1/IETHLockbox.sol1.99 KB
- interfaces/L1/IOptimismPortal2.sol5.91 KB
- interfaces/L1/IResourceMetering.sol680 B
- interfaces/L1/ISuperchainConfig.sol1.57 KB
- interfaces/L1/ISystemConfig.sol5.56 KB
- interfaces/L1/opcm/IOPContractsManagerContainer.sol1.55 KB
- interfaces/L1/opcm/IOPContractsManagerUtils.sol5.39 KB
- interfaces/dispute/IAnchorStateRegistry.sol3.12 KB
- interfaces/dispute/IDelayedWETH.sol2.34 KB
- interfaces/dispute/IDisputeGame.sol1.26 KB
- interfaces/dispute/IDisputeGameFactory.sol2.98 KB
- interfaces/dispute/IInitializable.sol130 B
- interfaces/legacy/IAddressManager.sol521 B
- interfaces/universal/IOwnable.sol686 B
- interfaces/universal/IProxyAdmin.sol1.62 KB
- interfaces/universal/IProxyAdminOwnedBase.sol620 B
- interfaces/universal/IReinitializableBase.sol323 B
- interfaces/universal/ISemver.sol519 B
- lib/solady/src/utils/JSONParserLib.sol36.08 KB
- lib/solady/src/utils/LibString.sol51.93 KB
- src/L1/opcm/OPContractsManagerUtilsCaller.sol13.7 KB
- src/dispute/lib/LibPosition.sol9.48 KB
- src/dispute/lib/LibUDT.sol9.01 KB
- src/dispute/lib/Types.sol5.95 KB
- src/libraries/Constants.sol4.37 KB
- src/libraries/DevFeatures.sol4.25 KB
- src/libraries/Features.sol2.59 KB
- src/libraries/SemverComp.sol4.85 KB
- src/libraries/Types.sol4.23 KB
src/L1/opcm/OPContractsManagerMigrator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
// Contracts
import { OPContractsManagerUtilsCaller } from "src/L1/opcm/OPContractsManagerUtilsCaller.sol";
// Libraries
import { DevFeatures } from "src/libraries/DevFeatures.sol";
import { GameTypes } from "src/dispute/lib/Types.sol";
import { Constants } from "src/libraries/Constants.sol";
import { Features } from "src/libraries/Features.sol";
import { SemverComp } from "src/libraries/SemverComp.sol";
// Interfaces
import { IDelayedWETH } from "interfaces/dispute/IDelayedWETH.sol";
import { IAnchorStateRegistry } from "interfaces/dispute/IAnchorStateRegistry.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 { IOptimismPortal2 as IOptimismPortal } from "interfaces/L1/IOptimismPortal2.sol";
import { IETHLockbox } from "interfaces/L1/IETHLockbox.sol";
import { IOPContractsManagerContainer } from "interfaces/L1/opcm/IOPContractsManagerContainer.sol";
import { IOPContractsManagerUtils } from "interfaces/L1/opcm/IOPContractsManagerUtils.sol";
import { GameType, Proposal } from "src/dispute/lib/Types.sol";
/// @title OPContractsManagerMigrator
/// @notice OPContractsManagerMigrator is a contract that provides the migration functionality for
/// migrating one or more OP Stack chains to use the Super Root dispute games and shared
/// dispute game contracts.
contract OPContractsManagerMigrator is OPContractsManagerUtilsCaller {
/// @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 the chainSystemConfigs array is empty.
error OPContractsManagerMigrator_NoChains();
/// @notice Thrown when a chain is paused before migration mutates its portal.
error OPContractsManagerMigrator_SystemPaused();
/// @notice Thrown when a chain is already in an interop set.
error OPContractsManagerMigrator_ChainAlreadyMigrated();
/// @notice Thrown when the SuperchainConfig is older than this release's implementation.
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 the ZK_DISPUTE_GAME dev feature is not enabled.
error OPContractsManagerMigrator_ZKDisputeGameNotEnabled();
/// @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();
/// @notice Thrown when the starting anchor root is zero or leaves no room for a uint64
/// successor.
error OPContractsManagerMigrator_InvalidStartingAnchorRoot();
/// @param _utils The utility functions for the OPContractsManager.
constructor(IOPContractsManagerUtils _utils) OPContractsManagerUtilsCaller(_utils) { }
/// @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.
/// @dev NOTE: This function is designed exclusively for the case of N independent pre-interop
/// chains merging into a single interop set. It does NOT support partial migration (i.e.,
/// migrating a subset of chains that share a lockbox) or any other migration scenario.
/// Re-migration is rejected: any chain that already has Features.INTEROP enabled is
/// refused, because re-migrating it would corrupt the shared DisputeGameFactory and
/// ETHLockbox used by every chain in its set. SystemConfig does not allow INTEROP to be
/// disabled.
/// @dev NOTE: OPContractsManagerV2.upgrade() only performs standard chain upgrades. This
/// function performs the one-off interop activation by enabling required features,
/// connecting each portal to the shared ETHLockbox, migrating liquidity, and moving each
/// portal to the shared dispute game contracts.
/// @param _input The input parameters for the migration.
function migrate(MigrateInput calldata _input) public {
// Check that at least one chain is being migrated.
if (_input.chainSystemConfigs.length == 0) {
revert OPContractsManagerMigrator_NoChains();
}
// Check that the starting respected game type is a valid super game type.
// SUPER_CANNON is retired in favor of SUPER_CANNON_KONA.
if (
_input.startingRespectedGameType.raw() != GameTypes.SUPER_CANNON_KONA.raw()
&& _input.startingRespectedGameType.raw() != GameTypes.SUPER_PERMISSIONED.raw()
) {
revert OPContractsManagerMigrator_InvalidStartingRespectedGameType();
}
// Check that the starting anchor root is non-zero and leaves room for a successor.
if (
_input.startingAnchorRoot.root.raw() == bytes32(0)
|| _input.startingAnchorRoot.l2SequenceNumber >= type(uint64).max
) {
revert OPContractsManagerMigrator_InvalidStartingAnchorRoot();
}
// Check that all of the chains have the same core contracts, that no chain reports a
// zero l2ChainId, that no two chains share the same l2ChainId, and that l2ChainIds are
// provided in ascending order.
_validateChainSystemConfigs(_input.chainSystemConfigs);
if (SemverComp.lt(
_input.chainSystemConfigs[0].superchainConfig().version(),
ISuperchainConfig(contractsContainer().implementations().superchainConfigImpl).version()
)) {
revert OPContractsManagerMigrator_SuperchainConfigNeedsUpgrade();
}
// Check that every supplied dispute game config is valid and that the starting respected
// game type is one of them.
_validateDisputeGameConfigs(_input.disputeGameConfigs, _input.startingRespectedGameType);
// NOTE: Interop doesn't have a real chain ID, and the chain ID provided here is ONLY used
// as a salt mixer, so we just use the block.timestamp instead. It really doesn't matter
// what we use here.
IOPContractsManagerUtils.ProxyDeployArgs memory proxyDeployArgs = IOPContractsManagerUtils.ProxyDeployArgs({
proxyAdmin: _input.chainSystemConfigs[0].proxyAdmin(),
addressManager: _input.chainSystemConfigs[0].proxyAdmin().addressManager(),
l2ChainId: block.timestamp,
saltMixer: "interop salt mixer"
});
// Permit deployment of exactly the three proxies this function creates.
IOPContractsManagerUtils.ExtraInstruction[] memory extraInstructions =
new IOPContractsManagerUtils.ExtraInstruction[](3);
extraInstructions[0] = IOPContractsManagerUtils.ExtraInstruction({
key: Constants.PERMITTED_PROXY_DEPLOYMENT_KEY, data: bytes("ETHLockbox")
});
extraInstructions[1] = IOPContractsManagerUtils.ExtraInstruction({
key: Constants.PERMITTED_PROXY_DEPLOYMENT_KEY, data: bytes("DisputeGameFactory")
});
extraInstructions[2] = IOPContractsManagerUtils.ExtraInstruction({
key: Constants.PERMITTED_PROXY_DEPLOYMENT_KEY, data: bytes("AnchorStateRegistry")
});
// Deploy the new ETHLockbox.
IETHLockbox ethLockbox = IETHLockbox(
_loadOrDeployProxy(
address(0), // Source from address(0) so we always deploy a new proxy.
bytes4(0),
proxyDeployArgs,
"ETHLockbox",
extraInstructions
)
);
// Deploy the new DisputeGameFactory.
IDisputeGameFactory disputeGameFactory = IDisputeGameFactory(
_loadOrDeployProxy(
address(0), // Source from address(0) so we always deploy a new proxy.
bytes4(0),
proxyDeployArgs,
"DisputeGameFactory",
extraInstructions
)
);
// Deploy the new AnchorStateRegistry.
IAnchorStateRegistry anchorStateRegistry = IAnchorStateRegistry(
_loadOrDeployProxy(
address(0), // Source from address(0) so we always deploy a new proxy.
bytes4(0),
proxyDeployArgs,
"AnchorStateRegistry",
extraInstructions
)
);
// Reuse the existing DelayedWETH from chainSystemConfigs[0] rather than deploying a
// new one. The migrated chains share a SystemConfig, and by extension share its
// DelayedWETH. Deploying a new one would create a divergence — SystemConfig would
// still point to the old one, and future upgrades (which load DelayedWETH from
// SystemConfig) would reference a different DelayedWETH than the shared DGF games.
IDelayedWETH delayedWETH = IDelayedWETH(payable(_input.chainSystemConfigs[0].delayedWETH()));
// Separate context to avoid stack too deep (isolate the implementations variable).
{
// Grab the implementations.
IOPContractsManagerContainer.Implementations memory impls = contractsContainer().implementations();
// Initialize the shared ETHLockbox.
_upgrade(
proxyDeployArgs.proxyAdmin,
address(ethLockbox),
impls.ethLockboxImpl,
abi.encodeCall(
IETHLockbox.initialize, (_input.chainSystemConfigs[0].superchainConfig(), new IOptimismPortal[](0))
)
);
// Initialize the new DisputeGameFactory.
_upgrade(
proxyDeployArgs.proxyAdmin,
address(disputeGameFactory),
impls.disputeGameFactoryImpl,
abi.encodeCall(IDisputeGameFactory.initialize, (proxyDeployArgs.proxyAdmin.owner()))
);
// Initialize the new AnchorStateRegistry.
_upgrade(
proxyDeployArgs.proxyAdmin,
address(anchorStateRegistry),
impls.anchorStateRegistryImpl,
abi.encodeCall(
IAnchorStateRegistry.initialize,
(ethLockbox, disputeGameFactory, _input.startingAnchorRoot, _input.startingRespectedGameType)
)
);
// Migrate each portal to the new ETHLockbox and AnchorStateRegistry.
for (uint256 i = 0; i < _input.chainSystemConfigs.length; i++) {
_updateDelayedWETHLockbox(_input.chainSystemConfigs[i], ethLockbox, impls.delayedWETHImpl);
// Preserve the legacy pause resolver until the portal points at the shared lockbox.
// Upgrading SystemConfig first would query a missing lockbox or recurse through a legacy one.
_migratePortal(_input.chainSystemConfigs[i], ethLockbox, anchorStateRegistry, impls);
_updateSystemConfigDelayedWETH(_input.chainSystemConfigs[i], delayedWETH, impls.systemConfigImpl);
}
}
// Set up the dispute games in the new DisputeGameFactory. Configs are validated by
// _validateDisputeGameConfigs above.
for (uint256 i = 0; i < _input.disputeGameConfigs.length; i++) {
disputeGameFactory.setImplementation(
_input.disputeGameConfigs[i].gameType,
_getGameImpl(_input.disputeGameConfigs[i].gameType),
_makeGameArgs(0, anchorStateRegistry, delayedWETH, _input.disputeGameConfigs[i])
);
disputeGameFactory.setInitBond(_input.disputeGameConfigs[i].gameType, _input.disputeGameConfigs[i].initBond);
}
}
/// @notice Validates the per-chain SystemConfig array supplied to migrate(). All chains must
/// share a ProxyAdmin owner and SuperchainConfig, and their l2ChainIds must be
/// non-zero, distinct, and provided in ascending order.
/// @param _chainSystemConfigs The chain system configs to validate.
function _validateChainSystemConfigs(ISystemConfig[] calldata _chainSystemConfigs) internal view {
uint256 prevL2ChainId;
for (uint256 i = 0; i < _chainSystemConfigs.length; i++) {
// Different chains might actually have different ProxyAdmin contracts, but it's fine
// as long as the owner of all of those contracts is the same.
if (_chainSystemConfigs[i].proxyAdmin().owner() != _chainSystemConfigs[0].proxyAdmin().owner()) {
revert OPContractsManagerMigrator_ProxyAdminOwnerMismatch();
}
// Each chain must have the same SuperchainConfig.
if (_chainSystemConfigs[i].superchainConfig() != _chainSystemConfigs[0].superchainConfig()) {
revert OPContractsManagerMigrator_SuperchainConfigMismatch();
}
// migrate() is the only thing that sets INTEROP on L1 and SystemConfig does not allow
// clearing it, so the flag means this chain is already in an interop set. Re-migrating
// it would drain that set's ETHLockbox into a fresh one and clear every game
// implementation from its shared DisputeGameFactory, for every chain sharing them.
if (_chainSystemConfigs[i].isFeatureEnabled(Features.INTEROP)) {
revert OPContractsManagerMigrator_ChainAlreadyMigrated();
}
// The shared super-root dispute game system keys output roots by l2ChainId, so a
// zero or duplicate l2ChainId across migrated portals would let the same withdrawal
// be finalized through multiple portals.
uint256 l2ChainId = _chainSystemConfigs[i].l2ChainId();
if (i == 0) {
if (l2ChainId == 0) {
revert OPContractsManagerMigrator_ZeroL2ChainId();
}
} else if (l2ChainId == prevL2ChainId) {
revert OPContractsManagerMigrator_DuplicateL2ChainId();
} else if (l2ChainId < prevL2ChainId) {
revert OPContractsManagerMigrator_ChainIdsNotAscending();
}
prevL2ChainId = l2ChainId;
}
}
/// @notice Validates the dispute game configs supplied to migrate(). Migration is a
/// privileged, one-off admin action, so it does not repeat the structural checks that
/// OPContractsManagerV2 applies on the deploy/upgrade path: it takes a variable-length
/// list of super game types rather than one config per valid game type. It does apply
/// the per-config checks from that path, and rejects configs that migration cannot
/// act on: every config is registered as supplied, so a disabled config or a game type
/// that does not use super roots is a caller mistake rather than a no-op.
/// @param _gameConfigs The dispute game configs to validate.
/// @param _startingRespectedGameType The game type the AnchorStateRegistry will respect.
function _validateDisputeGameConfigs(
IOPContractsManagerUtils.DisputeGameConfig[] calldata _gameConfigs,
GameType _startingRespectedGameType
)
internal
view
{
bool startingGameTypeFound;
for (uint256 i = 0; i < _gameConfigs.length; i++) {
_assertValidDisputeGameConfig(_gameConfigs[i]);
if (_gameConfigs[i].gameType.raw() == _startingRespectedGameType.raw()) {
startingGameTypeFound = true;
}
}
// The respected game type must have an implementation registered by this migration.
if (!startingGameTypeFound) {
revert OPContractsManagerMigrator_InvalidStartingRespectedGameType();
}
}
/// @notice Validates a single dispute game config supplied to migrate(). See
/// _validateDisputeGameConfigs for which checks apply and why.
/// @param _gameConfig The dispute game config to validate.
function _assertValidDisputeGameConfig(IOPContractsManagerUtils.DisputeGameConfig calldata _gameConfig)
internal
view
{
uint32 rawGameType = _gameConfig.gameType.raw();
// Non-super game types would have l2ChainId=0, causing the game to revert on chain ID
// mismatch, and legacy fault game types are not validated by this path at all.
if (!GameTypes.isSuperGame(_gameConfig.gameType)) {
revert OPContractsManagerMigrator_InvalidGameType();
}
// Every supplied config is registered, so a disabled config is a caller mistake.
if (!_gameConfig.enabled) {
revert OPContractsManagerMigrator_DisputeGameNotEnabled();
}
// SUPER_PERMISSIONED does not use bonds. Every other game type does.
if (rawGameType == GameTypes.SUPER_PERMISSIONED.raw()) {
if (_gameConfig.initBond != 0) {
revert OPContractsManagerMigrator_InvalidInitBond();
}
} else if (_gameConfig.initBond == 0) {
revert OPContractsManagerMigrator_InvalidInitBond();
}
// ZK_DISPUTE_GAME can only be registered when the dev feature is on.
if (
rawGameType == GameTypes.ZK_DISPUTE_GAME.raw()
&& !contractsContainer().isDevFeatureEnabled(DevFeatures.ZK_DISPUTE_GAME)
) {
revert OPContractsManagerMigrator_ZKDisputeGameNotEnabled();
}
// A permissionless game is unplayable without an absolute prestate.
if (rawGameType == GameTypes.SUPER_CANNON_KONA.raw()) {
IOPContractsManagerUtils.FaultDisputeGameConfig memory faultGameConfig =
abi.decode(_gameConfig.gameArgs, (IOPContractsManagerUtils.FaultDisputeGameConfig));
if (faultGameConfig.absolutePrestate.raw() == bytes32(0)) {
revert OPContractsManagerMigrator_InvalidAbsolutePrestate();
}
} else if (rawGameType == GameTypes.ZK_DISPUTE_GAME.raw()) {
// The ZK game also needs bounded, non-zero durations and a non-zero challenger bond.
if (!_isValidZKDisputeGameConfig(_gameConfig.gameArgs)) {
revert OPContractsManagerMigrator_InvalidZKDisputeGameConfig();
}
}
}
/// @notice Updates a chain's existing DelayedWETH to point at the shared ETHLockbox. Games
/// created before the migration still read their pause state from it.
/// @param _systemConfig The system config for the chain being migrated.
/// @param _ethLockbox The shared ETHLockbox to store in the DelayedWETH.
/// @param _delayedWETHImpl The DelayedWETH implementation to reinitialize with.
function _updateDelayedWETHLockbox(
ISystemConfig _systemConfig,
IETHLockbox _ethLockbox,
address _delayedWETHImpl
)
internal
{
_upgrade(
_systemConfig.proxyAdmin(),
_systemConfig.delayedWETH(),
_delayedWETHImpl,
abi.encodeCall(IDelayedWETH.initialize, (_ethLockbox))
);
}
/// @notice Updates a chain's SystemConfig to point at the shared DelayedWETH while preserving
/// all other per-chain configuration values.
/// @param _systemConfig The system config for the chain being migrated.
/// @param _delayedWETH The shared DelayedWETH to store in the SystemConfig.
/// @param _systemConfigImpl The SystemConfig implementation to reinitialize with.
function _updateSystemConfigDelayedWETH(
ISystemConfig _systemConfig,
IDelayedWETH _delayedWETH,
address _systemConfigImpl
)
internal
{
ISystemConfig.Addresses memory addrs = _systemConfig.getAddresses();
addrs.delayedWETH = address(_delayedWETH);
addrs.opcm = _systemConfig.lastUsedOPCM();
_upgrade(
_systemConfig.proxyAdmin(),
address(_systemConfig),
_systemConfigImpl,
_encodeSystemConfigInit(
SystemConfigInitArgs({
owner: _systemConfig.owner(),
basefeeScalar: _systemConfig.basefeeScalar(),
blobbasefeeScalar: _systemConfig.blobbasefeeScalar(),
batcherHash: _systemConfig.batcherHash(),
gasLimit: _systemConfig.gasLimit(),
unsafeBlockSigner: _systemConfig.unsafeBlockSigner(),
resourceConfig: _systemConfig.resourceConfig(),
addrs: addrs,
l2ChainId: _systemConfig.l2ChainId(),
superchainConfig: _systemConfig.superchainConfig()
})
)
);
}
/// @notice Migrates a single portal to the new ETHLockbox and AnchorStateRegistry and points its
/// old AnchorStateRegistry at the new ETHLockbox.
/// @param _systemConfig The system config for the chain being migrated.
/// @param _newLockbox The new ETHLockbox.
/// @param _newASR The new AnchorStateRegistry.
/// @param _impls The implementations to use for the portal and old AnchorStateRegistry.
function _migratePortal(
ISystemConfig _systemConfig,
IETHLockbox _newLockbox,
IAnchorStateRegistry _newASR,
IOPContractsManagerContainer.Implementations memory _impls
)
internal
{
// CGT chains must not be migrated — prevents incorrect pooling into shared ETHLockbox.
if (_systemConfig.isCustomGasToken()) {
revert OPContractsManagerMigrator_CustomGasTokenNotSupported();
}
// Convert portal to interop portal interface, and grab existing migration state.
IOptimismPortal portal = IOptimismPortal(payable(_systemConfig.optimismPortal()));
IETHLockbox oldLockbox = IETHLockbox(payable(address(portal.ethLockbox())));
IAnchorStateRegistry oldASR = portal.anchorStateRegistry();
IDisputeGameFactory existingDGF = IDisputeGameFactory(payable(address(portal.disputeGameFactory())));
// Check the current pause state before mutating the portal's lockbox. For chains that
// already use a per-chain lockbox, SystemConfig.paused() keys the local pause against the
// portal's current lockbox. Reinitializing the portal first would switch the pause
// identifier to the shared lockbox and could hide an active old-lockbox pause.
if (_systemConfig.paused()) {
revert OPContractsManagerMigrator_SystemPaused();
}
// Authorize the portal on the new ETHLockbox.
_newLockbox.authorizePortal(portal);
// Enable the features required by portal liquidity migration and shared game migration.
// ETH_LOCKBOX must be on so SystemConfig.paused() keys against the portal's lockbox; a
// chain may already have it from deploy/upgrade, and setFeature reverts on a no-op change.
if (!_systemConfig.isFeatureEnabled(Features.ETH_LOCKBOX)) {
_systemConfig.setFeature(Features.ETH_LOCKBOX, true);
}
// INTEROP is guaranteed to be off by _validateChainSystemConfigs.
_systemConfig.setFeature(Features.INTEROP, true);
// Attach the portal directly to the shared ETHLockbox before migrating portal-held ETH.
_upgrade(
_systemConfig.proxyAdmin(),
address(portal),
_impls.optimismPortalImpl,
abi.encodeCall(IOptimismPortal.initialize, (_systemConfig, oldASR, _newLockbox))
);
// Migrate ETH held directly by the portal into the shared ETHLockbox.
portal.migrateLiquidity();
// Sweep any pre-existing per-chain lockbox liquidity into the shared ETHLockbox. Fresh
// chains may have no old lockbox, while already-lockbox-enabled chains can have ETH there
// that would be stranded after the portal starts pointing at the shared lockbox.
if (address(oldLockbox) != address(0) && address(oldLockbox) != address(_newLockbox)) {
// The shared lockbox must authorize the old lockbox before receiveLiquidity() will
// accept ETH from oldLockbox.migrateLiquidity().
_newLockbox.authorizeLockbox(oldLockbox);
oldLockbox.migrateLiquidity(_newLockbox);
}
// Clear out any implementations that might exist in the old DisputeGameFactory proxy.
GameType[] memory clearedGameTypes = GameTypes.clearedGameTypes();
for (uint256 i = 0; i < clearedGameTypes.length; i++) {
existingDGF.setImplementation(clearedGameTypes[i], IDisputeGame(address(0)), hex"");
}
// Migrate the portal to the new ETHLockbox and AnchorStateRegistry.
portal.migrateToSharedDisputeGame(_newLockbox, _newASR);
// Point the old AnchorStateRegistry at the new ETHLockbox. Games created before the
// migration still read their pause state from it.
_upgrade(
_systemConfig.proxyAdmin(),
address(oldASR),
_impls.anchorStateRegistryImpl,
abi.encodeCall(
IAnchorStateRegistry.initialize,
(_newLockbox, oldASR.disputeGameFactory(), oldASR.getStartingAnchorRoot(), oldASR.respectedGameType())
)
);
}
/// @notice Returns the contracts container.
/// @return The contracts container.
function contractsContainer() public view returns (IOPContractsManagerContainer) {
return opcmUtils.contractsContainer();
}
}
interfaces/L1/IETHLockbox.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ISemver } from "interfaces/universal/ISemver.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
import { IOptimismPortal2 } from "interfaces/L1/IOptimismPortal2.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IReinitializableBase } from "interfaces/universal/IReinitializableBase.sol";
interface IETHLockbox is IProxyAdminOwnedBase, ISemver, IReinitializableBase {
error ETHLockbox_Unauthorized();
error ETHLockbox_Paused();
error ETHLockbox_InsufficientBalance();
error ETHLockbox_NoWithdrawalTransactions();
error ETHLockbox_DifferentSuperchainConfig();
event Initialized(uint8 version);
event ETHLocked(IOptimismPortal2 indexed portal, uint256 amount);
event ETHUnlocked(IOptimismPortal2 indexed portal, uint256 amount);
event PortalAuthorized(IOptimismPortal2 indexed portal);
event LockboxAuthorized(IETHLockbox indexed lockbox);
event LiquidityMigrated(IETHLockbox indexed lockbox, uint256 amount);
event LiquidityReceived(IETHLockbox indexed lockbox, uint256 amount);
function initialize(ISuperchainConfig _superchainConfig, IOptimismPortal2[] calldata _portals) external;
function paused() external view returns (bool);
function guardian() external view returns (address);
function authorizedPortals(IOptimismPortal2) external view returns (bool);
function authorizedLockboxes(IETHLockbox) external view returns (bool);
function receiveLiquidity() external payable;
function lockETH() external payable;
function unlockETH(uint256 _value) external;
function authorizePortal(IOptimismPortal2 _portal) external;
function authorizeLockbox(IETHLockbox _lockbox) external;
function migrateLiquidity(IETHLockbox _lockbox) external;
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__() external;
}
interfaces/L1/IOptimismPortal2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { Types } from "src/libraries/Types.sol";
import { 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";
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_ZeroAddress();
error OptimismPortal_LockboxNotAuthorizedForPortal();
error OptimismPortal_DisputeGameNotInvalidated();
error OutOfGas();
error UnexpectedList();
error UnexpectedString();
event Initialized(uint8 version);
event ETHMigrated(address indexed lockbox, uint256 balance);
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) external;
function initVersion() external view returns (uint8);
function l2Sender() external view returns (address);
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 systemConfig() external view returns (ISystemConfig);
function version() external pure returns (string memory);
function __constructor__(uint256 _proofMaturityDelaySeconds) external;
}
interfaces/L1/IResourceMetering.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IResourceMetering {
struct ResourceParams {
uint128 prevBaseFee;
uint64 prevBoughtGas;
uint64 prevBlockNum;
}
struct ResourceConfig {
uint32 maxResourceLimit;
uint8 elasticityMultiplier;
uint8 baseFeeMaxChangeDenominator;
uint32 minimumBaseFee;
uint32 systemTxMaxGas;
uint128 maximumBaseFee;
}
error OutOfGas();
event Initialized(uint8 version);
function params() external view returns (uint128 prevBaseFee, uint64 prevBoughtGas, uint64 prevBlockNum); // nosemgrep
function __constructor__() external;
}
interfaces/L1/ISuperchainConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface ISuperchainConfig is IProxyAdminOwnedBase {
enum UpdateType {
GUARDIAN
}
event ConfigUpdate(UpdateType indexed updateType, bytes data);
event Initialized(uint8 version);
event Paused(address identifier);
event Unpaused(address identifier);
error SuperchainConfig_OnlyGuardian();
error SuperchainConfig_AlreadyPaused(address identifier);
error SuperchainConfig_NotAlreadyPaused(address identifier);
error ReinitializableBase_ZeroInitVersion();
function guardian() external view returns (address);
function initialize(address _guardian) external;
function pause(address _identifier) external;
function unpause(address _identifier) external;
function pausable(address _identifier) external view returns (bool);
function paused() external view returns (bool);
function paused(address _identifier) external view returns (bool);
function isLocalOrGlobalPaused(address _identifier) external view returns (bool);
function expiration(address _identifier) external view returns (uint256);
function extend(address _identifier) external;
function version() external view returns (string memory);
function pauseTimestamps(address) external view returns (uint256);
function pauseExpiry() external view returns (uint256);
function initVersion() external view returns (uint8);
function __constructor__() external;
}
interfaces/L1/ISystemConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IResourceMetering } from "interfaces/L1/IResourceMetering.sol";
import { ISuperchainConfig } from "interfaces/L1/ISuperchainConfig.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
interface ISystemConfig is IProxyAdminOwnedBase {
enum UpdateType {
BATCHER,
FEE_SCALARS,
GAS_LIMIT,
UNSAFE_BLOCK_SIGNER,
EIP_1559_PARAMS,
OPERATOR_FEE_PARAMS,
MIN_BASE_FEE,
DA_FOOTPRINT_GAS_SCALAR
}
struct Addresses {
address l1CrossDomainMessenger;
address l1ERC721Bridge;
address l1StandardBridge;
address optimismPortal;
address optimismMintableERC20Factory;
address delayedWETH;
address opcm;
}
error ReinitializableBase_ZeroInitVersion();
error SystemConfig_InvalidFeatureState();
event ConfigUpdate(uint256 indexed version, UpdateType indexed updateType, bytes data);
event FeatureSet(bytes32 indexed feature, bool indexed enabled);
event Initialized(uint8 version);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function L1_CROSS_DOMAIN_MESSENGER_SLOT() external view returns (bytes32);
function L1_ERC_721_BRIDGE_SLOT() external view returns (bytes32);
function L1_STANDARD_BRIDGE_SLOT() external view returns (bytes32);
function OPTIMISM_MINTABLE_ERC20_FACTORY_SLOT() external view returns (bytes32);
function OPTIMISM_PORTAL_SLOT() external view returns (bytes32);
function DELAYED_WETH_SLOT() external view returns (bytes32);
function START_BLOCK_SLOT() external view returns (bytes32);
function UNSAFE_BLOCK_SIGNER_SLOT() external view returns (bytes32);
function OPCM_SLOT() external view returns (bytes32);
function VERSION() external view returns (uint256);
function basefeeScalar() external view returns (uint32);
function batcherHash() external view returns (bytes32);
function blobbasefeeScalar() external view returns (uint32);
function disputeGameFactory() external view returns (address addr_);
function gasLimit() external view returns (uint64);
function eip1559Denominator() external view returns (uint32);
function eip1559Elasticity() external view returns (uint32);
function getAddresses() external view returns (Addresses memory);
function initialize(
address _owner,
uint32 _basefeeScalar,
uint32 _blobbasefeeScalar,
bytes32 _batcherHash,
uint64 _gasLimit,
address _unsafeBlockSigner,
IResourceMetering.ResourceConfig memory _config,
Addresses memory _addresses,
uint256 _l2ChainId,
ISuperchainConfig _superchainConfig
)
external;
function initVersion() external view returns (uint8);
function l1CrossDomainMessenger() external view returns (address addr_);
function l1ERC721Bridge() external view returns (address addr_);
function l1StandardBridge() external view returns (address addr_);
function l2ChainId() external view returns (uint256);
function maximumGasLimit() external pure returns (uint64);
function minimumGasLimit() external view returns (uint64);
function operatorFeeConstant() external view returns (uint64);
function operatorFeeScalar() external view returns (uint32);
function minBaseFee() external view returns (uint64);
function daFootprintGasScalar() external view returns (uint16);
function optimismMintableERC20Factory() external view returns (address addr_);
function optimismPortal() external view returns (address addr_);
function delayedWETH() external view returns (address addr_);
function lastUsedOPCM() external view returns (address addr_);
function lastUsedOPCMVersion() external view returns (string memory version_);
function overhead() external view returns (uint256);
function owner() external view returns (address);
function renounceOwnership() external;
function resourceConfig() external view returns (IResourceMetering.ResourceConfig memory);
function scalar() external view returns (uint256);
function setBatcherHash(address _batcher) external;
function setBatcherHash(bytes32 _batcherHash) external;
function setGasConfigEcotone(uint32 _basefeeScalar, uint32 _blobbasefeeScalar) external;
function setGasLimit(uint64 _gasLimit) external;
function setOperatorFeeScalars(uint32 _operatorFeeScalar, uint64 _operatorFeeConstant) external;
function setUnsafeBlockSigner(address _unsafeBlockSigner) external;
function setEIP1559Params(uint32 _denominator, uint32 _elasticity) external;
function setMinBaseFee(uint64 _minBaseFee) external;
function setDAFootprintGasScalar(uint16 _daFootprintGasScalar) external;
function startBlock() external view returns (uint256 startBlock_);
function transferOwnership(address newOwner) external; // nosemgrep
function unsafeBlockSigner() external view returns (address addr_);
function version() external pure returns (string memory);
function paused() external view returns (bool);
function superchainConfig() external view returns (ISuperchainConfig);
function guardian() external view returns (address);
function setFeature(bytes32 _feature, bool _enabled) external;
function isFeatureEnabled(bytes32) external view returns (bool);
function isCustomGasToken() external view returns (bool);
function __constructor__() external;
}
interfaces/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/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/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_Unauthorized();
error ReinitializableBase_ZeroInitVersion();
event AnchorUpdated(IDisputeGame indexed game);
event DisputeGameBlacklisted(IDisputeGame indexed disputeGame);
event Initialized(uint8 version);
event RespectedGameTypeSet(GameType gameType);
event RetirementTimestampSet(uint256 timestamp);
function initVersion() external view returns (uint8);
function anchorGame() external view returns (IDisputeGame);
function anchors(GameType) external view returns (Hash, uint256);
function blacklistDisputeGame(IDisputeGame _disputeGame) external;
function disputeGameBlacklist(IDisputeGame) external view returns (bool);
function getAnchorRoot() external view returns (Hash, uint256);
function getStartingAnchorRoot() external view returns (Proposal memory);
function disputeGameFinalityDelaySeconds() external view returns (uint256);
function disputeGameFactory() external view returns (IDisputeGameFactory);
function initialize(
IETHLockbox _ethLockbox,
IDisputeGameFactory _disputeGameFactory,
Proposal memory _startingAnchorRoot,
GameType _startingRespectedGameType
)
external;
function isGameBlacklisted(IDisputeGame _game) external view returns (bool);
function isGameProper(IDisputeGame _game) external view returns (bool);
function isGameRegistered(IDisputeGame _game) external view returns (bool);
function isGameResolved(IDisputeGame _game) external view returns (bool);
function isGameRespected(IDisputeGame _game) external view returns (bool);
function isGameRetired(IDisputeGame _game) external view returns (bool);
function isGameFinalized(IDisputeGame _game) external view returns (bool);
function isGameClaimValid(IDisputeGame _game) external view returns (bool);
function paused() external view returns (bool);
function respectedGameType() external view returns (GameType);
function retirementTimestamp() external view returns (uint64);
function setAnchorState(IDisputeGame _game) external;
function setRespectedGameType(GameType _gameType) external;
function ethLockbox() external view returns (IETHLockbox);
function updateRetirementTimestamp() external;
function version() external view returns (string memory);
function superchainConfig() external view returns (ISuperchainConfig);
function __constructor__(
uint256 _disputeGameFinalityDelaySeconds
) external;
}
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 ReinitializableBase_ZeroInitVersion();
struct WithdrawalRequest {
uint256 amount;
uint256 timestamp;
}
event Initialized(uint8 version);
fallback() external payable;
receive() external payable;
function initVersion() external view returns (uint8);
function ethLockbox() external view returns (IETHLockbox);
function delay() external view returns (uint256);
function hold(address _guy) external;
function hold(address _guy, uint256 _wad) external;
function initialize(IETHLockbox _ethLockbox) external;
function recover(uint256 _wad) external;
function unlock(address _guy, uint256 _wad) external;
function withdraw(address _guy, uint256 _wad) external;
function withdrawals(address, address) external view returns (uint256 amount, uint256 timestamp);
function version() external view returns (string memory);
function withdraw(uint256 _wad) external;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address src) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function deposit() external payable;
function totalSupply() external view returns (uint256);
function approve(address guy, uint256 wad) external returns (bool);
function transfer(address dst, uint256 wad) external returns (bool);
function transferFrom(address src, address dst, uint256 wad) external returns (bool);
function config() external view returns (ISuperchainConfig);
function __constructor__(uint256 _delay) external;
}
interfaces/dispute/IDisputeGame.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IInitializable } from "interfaces/dispute/IInitializable.sol";
import { Timestamp, GameStatus, GameType, Claim, Hash } from "src/dispute/lib/Types.sol";
interface IDisputeGame is IInitializable {
event Resolved(GameStatus indexed status);
function createdAt() external view returns (Timestamp);
function resolvedAt() external view returns (Timestamp);
function status() external view returns (GameStatus);
function gameType() external view returns (GameType gameType_);
function gameCreator() external pure returns (address creator_);
function rootClaim() external pure returns (Claim rootClaim_);
function rootClaimByChainId(uint256 _chainId) external pure returns (Claim rootClaim_);
function l1Head() external pure returns (Hash l1Head_);
function l2SequenceNumber() external pure returns (uint256 l2SequenceNumber_);
function extraData() external pure returns (bytes memory extraData_);
function resolve() external returns (GameStatus status_);
function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_);
function wasRespectedGameTypeWhenCreated() external view returns (bool);
}
interfaces/dispute/IDisputeGameFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IDisputeGame } from "interfaces/dispute/IDisputeGame.sol";
import { GameId, Timestamp, Claim, Hash, GameType } from "src/dispute/lib/Types.sol";
import { IProxyAdminOwnedBase } from "interfaces/universal/IProxyAdminOwnedBase.sol";
import { IReinitializableBase } from "interfaces/universal/IReinitializableBase.sol";
interface IDisputeGameFactory is IProxyAdminOwnedBase, IReinitializableBase {
struct GameSearchResult {
uint256 index;
GameId metadata;
Timestamp timestamp;
Claim rootClaim;
bytes extraData;
}
error GameAlreadyExists(Hash uuid);
error IncorrectBondAmount();
error NoImplementation(GameType gameType);
event DisputeGameCreated(address indexed disputeProxy, GameType indexed gameType, Claim indexed rootClaim);
event ImplementationSet(address indexed impl, GameType indexed gameType);
event ImplementationArgsSet(GameType indexed gameType, bytes args);
event InitBondUpdated(GameType indexed gameType, uint256 indexed newBond);
event Initialized(uint8 version);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function create(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
payable
returns (IDisputeGame proxy_);
function findLatestGames(
GameType _gameType,
uint256 _start,
uint256 _n
)
external
view
returns (GameSearchResult[] memory games_);
function gameAtIndex(uint256 _index)
external
view
returns (GameType gameType_, Timestamp timestamp_, IDisputeGame proxy_);
function gameCount() external view returns (uint256 gameCount_);
function gameArgs(GameType) external view returns (bytes memory);
function gameImpls(GameType) external view returns (IDisputeGame);
function games(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
view
returns (IDisputeGame proxy_, Timestamp timestamp_);
function getGameUUID(
GameType _gameType,
Claim _rootClaim,
bytes memory _extraData
)
external
pure
returns (Hash uuid_);
function initBonds(GameType) external view returns (uint256);
function initialize(address _owner) external;
function owner() external view returns (address);
function renounceOwnership() external;
function setImplementation(GameType _gameType, IDisputeGame _impl) external;
function setImplementation(GameType _gameType, IDisputeGame _impl, bytes calldata _args) external;
function setInitBond(GameType _gameType, uint256 _initBond) external;
function transferOwnership(address newOwner) external; // nosemgrep
function version() external view returns (string memory);
function __constructor__() external;
}
interfaces/dispute/IInitializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IInitializable {
function initialize() external payable;
}
interfaces/legacy/IAddressManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IOwnable } from "interfaces/universal/IOwnable.sol";
/// @title IAddressManager
/// @notice Interface for the AddressManager contract.
interface IAddressManager is IOwnable {
event AddressSet(string indexed name, address newAddress, address oldAddress);
function getAddress(string memory _name) external view returns (address);
function setAddress(string memory _name, address _address) external;
function __constructor__() external;
}
interfaces/universal/IOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOwnable
/// @notice Interface for Ownable.
interface IOwnable {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev The caller account is not authorized to perform an operation.
error OwnableUnauthorizedAccount(address account);
/// @dev The owner is not a valid owner account. (eg. `address(0)`)
error OwnableInvalidOwner(address owner);
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner) external; // nosemgrep
function __constructor__() external;
}
interfaces/universal/IProxyAdmin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IAddressManager } from "interfaces/legacy/IAddressManager.sol";
interface IProxyAdmin {
enum ProxyType {
ERC1967,
CHUGSPLASH,
RESOLVED
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function addressManager() external view returns (IAddressManager);
function changeProxyAdmin(address payable _proxy, address _newAdmin) external;
function getProxyAdmin(address payable _proxy) external view returns (address);
function getProxyImplementation(address _proxy) external view returns (address);
function implementationName(address) external view returns (string memory);
function isUpgrading() external view returns (bool);
function owner() external view returns (address);
function proxyType(address) external view returns (ProxyType);
function renounceOwnership() external;
function setAddress(string memory _name, address _address) external;
function setAddressManager(IAddressManager _address) external;
function setImplementationName(address _address, string memory _name) external;
function setProxyType(address _address, ProxyType _type) external;
function setUpgrading(bool _upgrading) external;
function transferOwnership(address newOwner) external; // nosemgrep
function upgrade(address payable _proxy, address _implementation) external;
function upgradeAndCall(address payable _proxy, address _implementation, bytes memory _data) external payable;
function __constructor__(address _owner) external;
}
interfaces/universal/IProxyAdminOwnedBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IProxyAdmin } from "interfaces/universal/IProxyAdmin.sol";
interface IProxyAdminOwnedBase {
error ProxyAdminOwnedBase_NotSharedProxyAdminOwner();
error ProxyAdminOwnedBase_NotProxyAdminOwner();
error ProxyAdminOwnedBase_NotProxyAdmin();
error ProxyAdminOwnedBase_NotProxyAdminOrProxyAdminOwner();
error ProxyAdminOwnedBase_ProxyAdminNotFound();
error ProxyAdminOwnedBase_NotResolvedDelegateProxy();
function proxyAdmin() external view returns (IProxyAdmin);
function proxyAdminOwner() external view returns (address);
}
interfaces/universal/IReinitializableBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IReinitializableBase {
error ReinitializableBase_ZeroInitVersion();
function initVersion() external view returns (uint8);
// ReinitializerBase is abstract, so it has no constructor in its interface.
function __constructor__() external;
}
interfaces/universal/ISemver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title ISemver
/// @notice ISemver is a simple contract for ensuring that contracts are
/// versioned using semantic versioning.
interface ISemver {
/// @notice Getter for the semantic version of the contract. This is not
/// meant to be used onchain but instead meant to be used by offchain
/// tooling.
/// @return Semver contract version as a string.
function version() external view returns (string memory);
}
lib/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/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/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 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.
/// 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`.
///
/// For the parallel SYSTEM feature checklist, see
/// packages/contracts-bedrock/src/libraries/Features.sol.
library DevFeatures {
/// @notice The feature that enables the interop predeploys on L2, at genesis and in
/// L2ContractsManager upgrades.
bytes32 public constant OPTIMISM_PORTAL_INTEROP =
bytes32(0x0000000000000000000000000000000000000000000000000000000000000001);
/// @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 ZK dispute game system (ZKDisputeGame).
bytes32 public constant ZK_DISPUTE_GAME =
bytes32(0x0000000000000000000000000000000000000000000000000000000001000000);
/// @notice The feature that enables the super root games migration path in OPCM upgrade.
bytes32 public constant SUPER_ROOT_GAMES_MIGRATION =
bytes32(0x0000000000000000000000000000000000000000000000000000000010000000);
/// @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
},
"optimizer": {
"runs": 5000,
"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.