Verified contractExactAGPL-3.0
PolygonRollupManager
Address0x9ab2cb2107d3e737f7977b2e5042c58de98326ab
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 500 runs
- EVM version
- cancun
- License
- AGPL-3.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,718,131
- Creation transaction
- 0x89bf47d838…6d7c33c3ec
42 files
- contracts/v2/PolygonRollupManager.solmain67.91 KB
- @openzeppelin/contracts-upgradeable4/access/IAccessControlUpgradeable.sol2.93 KB
- @openzeppelin/contracts-upgradeable4/proxy/utils/Initializable.sol6.63 KB
- @openzeppelin/contracts-upgradeable4/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @openzeppelin/contracts-upgradeable4/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol2.26 KB
- @openzeppelin/contracts-upgradeable4/token/ERC20/utils/SafeERC20Upgradeable.sol4.59 KB
- @openzeppelin/contracts-upgradeable4/utils/AddressUpgradeable.sol8.28 KB
- @openzeppelin/contracts-upgradeable4/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts-upgradeable4/utils/StringsUpgradeable.sol2.3 KB
- @openzeppelin/contracts-upgradeable4/utils/introspection/ERC165Upgradeable.sol1.52 KB
- @openzeppelin/contracts-upgradeable4/utils/introspection/IERC165Upgradeable.sol864 B
- @openzeppelin/contracts-upgradeable4/utils/math/MathUpgradeable.sol12.52 KB
- @openzeppelin/contracts5/access/Ownable.sol3.1 KB
- @openzeppelin/contracts5/interfaces/IERC1967.sol636 B
- @openzeppelin/contracts5/proxy/ERC1967/ERC1967Proxy.sol1.72 KB
- @openzeppelin/contracts5/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- @openzeppelin/contracts5/proxy/Proxy.sol2.67 KB
- @openzeppelin/contracts5/proxy/beacon/IBeacon.sol472 B
- @openzeppelin/contracts5/proxy/transparent/ProxyAdmin.sol1.95 KB
- @openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol6.37 KB
- @openzeppelin/contracts5/utils/Address.sol6.26 KB
- @openzeppelin/contracts5/utils/Context.sol860 B
- @openzeppelin/contracts5/utils/StorageSlot.sol3.93 KB
- @openzeppelin/contracts52/utils/ReentrancyGuardTransient.sol2.06 KB
- @openzeppelin/contracts52/utils/TransientSlot.sol5.07 KB
- contracts/interfaces/IBasePolygonZkEVMGlobalExitRoot.sol1.37 KB
- contracts/interfaces/IPolygonZkEVMBridge.sol2.88 KB
- contracts/interfaces/IVerifierRollup.sol273 B
- contracts/lib/EmergencyManager.sol1.92 KB
- contracts/v2/interfaces/IAggLayerGateway.sol6.66 KB
- contracts/v2/interfaces/IAggchainBase.sol5.61 KB
- contracts/v2/interfaces/IPolygonConsensusBase.sol377 B
- contracts/v2/interfaces/IPolygonPessimisticConsensus.sol172 B
- contracts/v2/interfaces/IPolygonRollupBase.sol412 B
- contracts/v2/interfaces/IPolygonRollupManager.sol12.19 KB
- contracts/v2/interfaces/IPolygonZkEVMGlobalExitRootV2.sol415 B
- contracts/v2/interfaces/ISP1Verifier.sol1.06 KB
- contracts/v2/lib/Hashes.sol1.07 KB
- contracts/v2/lib/LegacyZKEVMStateVariables.sol6.33 KB
- contracts/v2/lib/PolygonAccessControlUpgradeable.sol7.55 KB
- contracts/v2/lib/PolygonConstantsBase.sol675 B
- contracts/v2/lib/PolygonTransparentProxy.sol3.04 KB
contracts/v2/PolygonRollupManager.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.28;
import "./interfaces/IPolygonZkEVMGlobalExitRootV2.sol";
import "../interfaces/IPolygonZkEVMBridge.sol";
import "./interfaces/IPolygonRollupBase.sol";
import "../interfaces/IVerifierRollup.sol";
import "../lib/EmergencyManager.sol";
import "@openzeppelin/contracts-upgradeable4/token/ERC20/utils/SafeERC20Upgradeable.sol";
// @dev For ReentrancyGuardTransient there is no difference between upgradable and not upgradable contracts
import "@openzeppelin/contracts52/utils/ReentrancyGuardTransient.sol";
import "./lib/PolygonTransparentProxy.sol";
import "./lib/PolygonAccessControlUpgradeable.sol";
import "./lib/LegacyZKEVMStateVariables.sol";
import "./lib/PolygonConstantsBase.sol";
import "./interfaces/IPolygonPessimisticConsensus.sol";
import "./interfaces/ISP1Verifier.sol";
import "./interfaces/IPolygonRollupManager.sol";
import "./interfaces/IAggchainBase.sol";
import "./interfaces/IAggLayerGateway.sol";
import "./lib/Hashes.sol";
/**
* Contract responsible for managing rollups and the verification of their batches.
* This contract will create and update rollups and store all the hashed sequenced data from them.
* The logic for sequence batches is moved to the `consensus` contracts, while the verification of all of
* them will be done in this one. In this way, the proof aggregation of the rollups will be easier on a close future.
*/
contract PolygonRollupManager is
PolygonAccessControlUpgradeable,
EmergencyManager,
LegacyZKEVMStateVariables,
PolygonConstantsBase,
IPolygonRollupManager,
ReentrancyGuardTransient
{
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* @notice Struct which to store the rollup type data
* @param consensusImplementation Consensus implementation ( contains the consensus logic for the transparent proxy)
* @param address verifier
* @param forkID fork ID
* @param rollupVerifierType Rollup compatibility ID, to check upgradability between rollup types
* @param obsolete Indicates if the rollup type is obsolete
* @param genesis Genesis block of the rollup, note that will only be used on creating new rollups, not upgrade them
* @param programVKey Hashed program that will be executed in case of using a "general purpose ZK verifier" e.g SP1
*/
struct RollupType {
address consensusImplementation;
address verifier;
uint64 forkID;
/// @custom:oz-renamed-from rollupCompatibilityID
/// @custom:oz-retyped-from uint8
VerifierType rollupVerifierType;
bool obsolete;
bytes32 genesis;
bytes32 programVKey;
}
/**
* @notice Struct which to store the rollup data of each chain
* @param rollupContract Rollup consensus contract, which manages everything
* related to sequencing transactions
* @param chainID Chain ID of the rollup
* @param verifier Verifier contract
* @param forkID ForkID of the rollup
* @param batchNumToStateRoot State root mapping
* @param sequencedBatches Queue of batches that defines the virtual state
* @param _legacyPendingStateTransitions Pending state mapping (deprecated)
* @param lastLocalExitRoot Last exit root verified, used for compute the rollupExitRoot
* @param lastBatchSequenced Last batch sent by the consensus contract
* @param lastVerifiedBatch Last batch verified
* @param _legacyLastPendingState Last pending state (deprecated)
* @param _legacyLastPendingStateConsolidated Last pending state consolidated (deprecated)
* @param lastVerifiedBatchBeforeUpgrade Last batch verified before the last upgrade
* @param rollupTypeID Rollup type ID, can be 0 if it was added as an existing rollup
* @param rollupVerifierType Rollup ID used for compatibility checks when upgrading
* @param lastPessimisticRoot Pessimistic info, currently contains the local balance tree and the local nullifier tree hashed
* @param programVKey Hashed program that will be executed in case of using a "general purpose ZK verifier" e.g SP1
*/
struct RollupData {
address rollupContract;
uint64 chainID;
address verifier;
uint64 forkID;
mapping(uint64 batchNum => bytes32) batchNumToStateRoot;
mapping(uint64 batchNum => SequencedBatchData) sequencedBatches;
/// @custom:oz-renamed-from pendingStateTransitions
mapping(uint256 pendingStateNum => PendingState) _legacyPendingStateTransitions;
bytes32 lastLocalExitRoot;
uint64 lastBatchSequenced;
uint64 lastVerifiedBatch;
/// @custom:oz-renamed-from lastPendingState
uint64 _legacyLastPendingState;
/// @custom:oz-renamed-from lastPendingStateConsolidated
uint64 _legacyLastPendingStateConsolidated;
uint64 lastVerifiedBatchBeforeUpgrade;
uint64 rollupTypeID;
/// @custom:oz-renamed-from rollupCompatibilityID
/// @custom:oz-retyped-from uint8
VerifierType rollupVerifierType;
bytes32 lastPessimisticRoot;
bytes32 programVKey;
}
/**
* @notice Struct to return all the necessary rollup info: VerifierType StateTransition
* @param rollupContract Rollup consensus contract, which manages everything
* related to sequencing transactions
* @param chainID Chain ID of the rollup
* @param verifier Verifier contract
* @param forkID ForkID of the rollup
* @param lastLocalExitRoot Last exit root verified, used for compute the rollupExitRoot
* @param lastBatchSequenced Last batch sent by the consensus contract
* @param lastVerifiedBatch Last batch verified
* @param _legacyLastPendingState Last pending state (deprecated)
* @param _legacyLastPendingStateConsolidated Last pending state consolidated (deprecated)
* @param lastVerifiedBatchBeforeUpgrade Last batch verified before the last upgrade
* @param rollupTypeID Rollup type ID, can be 0 if it was added as an existing rollup
* @param rollupVerifierType Rollup ID used for compatibility checks when upgrading
*/
struct RollupDataReturn {
address rollupContract;
uint64 chainID;
address verifier;
uint64 forkID;
bytes32 lastLocalExitRoot;
uint64 lastBatchSequenced;
uint64 lastVerifiedBatch;
uint64 _legacyLastPendingState;
uint64 _legacyLastPendingStateConsolidated;
uint64 lastVerifiedBatchBeforeUpgrade;
uint64 rollupTypeID;
VerifierType rollupVerifierType;
}
/**
* @notice Struct which to store the rollup data of each chain
* @param rollupContract Rollup consensus contract, which manages everything
* related to sequencing transactions
* @param chainID Chain ID of the rollup
* @param verifier Verifier contract
* @param forkID ForkID of the rollup
* @param lastLocalExitRoot Last exit root verified, used for compute the rollupExitRoot
* @param lastBatchSequenced Last batch sent by the consensus contract
* @param lastVerifiedBatch Last batch verified
* @param lastVerifiedBatchBeforeUpgrade Last batch verified before the last upgrade
* @param rollupTypeID Rollup type ID, can be 0 if it was added as an existing rollup
* @param rollupVerifierType Rollup ID used for compatibility checks when upgrading
* @param lastPessimisticRoot Pessimistic info, currently contains the local balance tree and the local nullifier tree hashed
* @param programVKey Hashed program that will be executed in case of using a "general purpose ZK verifier" e.g SP1
*/
struct RollupDataReturnV2 {
address rollupContract;
uint64 chainID;
address verifier;
uint64 forkID;
bytes32 lastLocalExitRoot;
uint64 lastBatchSequenced;
uint64 lastVerifiedBatch;
uint64 lastVerifiedBatchBeforeUpgrade;
uint64 rollupTypeID;
VerifierType rollupVerifierType;
bytes32 lastPessimisticRoot;
bytes32 programVKey;
}
// Modulus zkSNARK
uint256 internal constant _RFIELD =
21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Max batch fee value
uint256 internal constant _MAX_BATCH_FEE = 1000 ether;
// Min value batch fee
uint256 internal constant _MIN_BATCH_FEE = 1 gwei;
// Goldilocks prime field
uint256 internal constant _GOLDILOCKS_PRIME_FIELD = 0xFFFFFFFF00000001; // 2 ** 64 - 2 ** 32 + 1
// Max uint64
uint256 internal constant _MAX_UINT_64 = type(uint64).max; // 0xFFFFFFFFFFFFFFFF
// Exit merkle tree levels
uint256 internal constant _EXIT_TREE_DEPTH = 32;
// Roles
// Be able to add a new rollup type
bytes32 internal constant _ADD_ROLLUP_TYPE_ROLE =
keccak256("ADD_ROLLUP_TYPE_ROLE");
// Be able to obsolete a rollup type, which means that new rollups cannot use this type
bytes32 internal constant _OBSOLETE_ROLLUP_TYPE_ROLE =
keccak256("OBSOLETE_ROLLUP_TYPE_ROLE");
// Be able to create a new rollup using a rollup type
bytes32 internal constant _CREATE_ROLLUP_ROLE =
keccak256("CREATE_ROLLUP_ROLE");
// Be able to create a new rollup which does not have to follow any rollup type.
// Also sets the genesis block for that network
bytes32 internal constant _ADD_EXISTING_ROLLUP_ROLE =
keccak256("ADD_EXISTING_ROLLUP_ROLE");
// Be able to update a rollup to a new rollup type that it's compatible
bytes32 internal constant _UPDATE_ROLLUP_ROLE =
keccak256("UPDATE_ROLLUP_ROLE");
// Be able to that has priority to verify batches and consolidates the state instantly
bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE =
keccak256("TRUSTED_AGGREGATOR_ROLE");
// Be able to set the trusted aggregator address
bytes32 internal constant _TRUSTED_AGGREGATOR_ROLE_ADMIN =
keccak256("TRUSTED_AGGREGATOR_ROLE_ADMIN");
// Be able to tweak parameters
bytes32 internal constant _TWEAK_PARAMETERS_ROLE =
keccak256("TWEAK_PARAMETERS_ROLE");
// Be able to set the current batch fee
bytes32 internal constant _SET_FEE_ROLE = keccak256("SET_FEE_ROLE");
// Be able to stop the emergency state
bytes32 internal constant _STOP_EMERGENCY_ROLE =
keccak256("STOP_EMERGENCY_ROLE");
// Be able to activate the emergency state without any further condition
bytes32 internal constant _EMERGENCY_COUNCIL_ROLE =
keccak256("EMERGENCY_COUNCIL_ROLE");
// Be able to set the emergency council address
bytes32 internal constant _EMERGENCY_COUNCIL_ADMIN =
keccak256("EMERGENCY_COUNCIL_ADMIN");
// Current rollup manager version
string public constant ROLLUP_MANAGER_VERSION = "al-v0.3.0";
// Hardcoded address used to indicate that this address triggered in an event should not be considered as valid.
address private constant _NO_ADDRESS =
0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
// Global Exit Root address
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IPolygonZkEVMGlobalExitRootV2 public immutable globalExitRootManager;
// PolygonZkEVM Bridge Address
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IPolygonZkEVMBridge public immutable bridgeAddress;
// POL token address
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IERC20Upgradeable public immutable pol;
// Polygon Verifier Gateway address
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IAggLayerGateway public immutable aggLayerGateway;
// Number of rollup types added, every new type will be assigned sequentially a new ID
uint32 public rollupTypeCount;
// Rollup type mapping
/// @custom:oz-retyped-from PolygonRollupManagerPrevious.RollupType
mapping(uint32 rollupTypeID => RollupType) public rollupTypeMap;
// Number of rollups added, every new rollup will be assigned sequentially a new ID
uint32 public rollupCount;
// Rollups ID mapping
/// @custom:oz-retyped-from PolygonRollupManagerPrevious.RollupData
mapping(uint32 rollupID => RollupData) internal _rollupIDToRollupData;
// Rollups address mapping
mapping(address rollupAddress => uint32 rollupID) public rollupAddressToID;
// Chain ID mapping for nullifying
// note we will take care to avoid that current known chainIDs are not reused in our networks (example: 1)
mapping(uint64 chainID => uint32 rollupID) public chainIDToRollupID;
// Total sequenced batches across all rollups
uint64 public totalSequencedBatches;
// Total verified batches across all rollups
uint64 public totalVerifiedBatches;
// Last timestamp when an aggregation happen
uint64 public lastAggregationTimestamp;
// Trusted aggregator timeout, if a sequence is not verified in this time frame,
// everyone can verify that sequence
/// @custom:oz-renamed-from trustedAggregatorTimeout
uint64 internal __legacyTrustedAggregatorTimeout;
// Once a pending state exceeds this timeout it can be consolidated (deprecated)
/// @custom:oz-renamed-from pendingStateTimeout
uint64 internal __legacyPendingStateTimeout;
// Time target of the verification of a batch
// Adaptively the batchFee will be updated to achieve this target
/// @custom:oz-renamed-from verifyBatchTimeTarget
uint64 internal __legacyVerifyBatchTimeTarget;
// Batch fee multiplier with 3 decimals that goes from 1000 - 1023
/// @custom:oz-renamed-from multiplierBatchFee
uint16 internal __legacyMultiplierBatchFee;
// Current POL fee per batch sequenced
// note This variable is internal, since the view function getBatchFee is likely to be upgraded
uint256 internal _batchFee;
// Timestamp when the last emergency state was deactivated
uint64 public lastDeactivatedEmergencyStateTimestamp;
/**
* @dev Emitted when a new rollup type is added
*/
event AddNewRollupType(
uint32 indexed rollupTypeID,
address consensusImplementation,
address verifier,
uint64 forkID,
VerifierType rollupVerifierType,
bytes32 genesis,
string description,
bytes32 programVKey
);
/**
* @dev Emitted when a a rollup type is obsoleted
*/
event ObsoleteRollupType(uint32 indexed rollupTypeID);
/**
* @dev Emitted when a new rollup is created based on a rollupType
*/
event CreateNewRollup(
uint32 indexed rollupID,
uint32 rollupTypeID,
address rollupAddress,
uint64 chainID,
address gasTokenAddress
);
/**
* @dev Emitted when an existing rollup is added
*/
event AddExistingRollup(
uint32 indexed rollupID,
uint64 forkID,
address rollupAddress,
uint64 chainID,
VerifierType rollupVerifierType,
uint64 lastVerifiedBatchBeforeUpgrade,
bytes32 programVKey,
bytes32 initPessimisticRoot
);
/**
* @dev Emitted when a rollup is updated
*/
event UpdateRollup(
uint32 indexed rollupID,
uint32 newRollupTypeID,
uint64 lastVerifiedBatchBeforeUpgrade
);
/**
* @dev Emitted when a new verifier is added
*/
event OnSequenceBatches(uint32 indexed rollupID, uint64 lastBatchSequenced);
/**
* @dev Emitted when the trusted aggregator verifies batches
*/
event VerifyBatchesTrustedAggregator(
uint32 indexed rollupID,
uint64 numBatch,
bytes32 stateRoot,
bytes32 exitRoot,
address indexed aggregator
);
/**
* @dev Emitted when rollback batches
*/
event RollbackBatches(
uint32 indexed rollupID,
uint64 indexed targetBatch,
bytes32 accInputHashToRollback
);
/**
* @dev Emitted when is updated the trusted aggregator address
*/
event SetTrustedAggregator(address newTrustedAggregator);
/**
* @dev Emitted when is updated the batch fee
*/
event SetBatchFee(uint256 newBatchFee);
/**
* @dev Emitted when rollup manager is upgraded
*/
event UpdateRollupManagerVersion(string rollupManagerVersion);
/**
* @notice Emitted when a ALGateway or Pessimistic chain verifies a pessimistic proof
* @param rollupID Rollup ID
* @param prevPessimisticRoot Previous pessimistic root
* @param newPessimisticRoot New pessimistic root
* @param prevLocalExitRoot Previous local exit root
* @param newLocalExitRoot New local exit root
* @param l1InfoRoot L1 info root
* @param trustedAggregator Trusted aggregator address
*/
event VerifyPessimisticStateTransition(
uint32 indexed rollupID,
bytes32 prevPessimisticRoot,
bytes32 newPessimisticRoot,
bytes32 prevLocalExitRoot,
bytes32 newLocalExitRoot,
bytes32 l1InfoRoot,
address indexed trustedAggregator
);
/**
* @dev Emitted when a new rollup is created based on a rollupType
*/
event CreateNewAggchain(
uint32 indexed rollupID,
uint32 rollupTypeID,
address rollupAddress,
uint64 chainID,
uint8 rollupVerifierType,
bytes initializeBytesAggchain
);
/**
* @param _globalExitRootManager Global exit root manager address
* @param _pol POL token address
* @param _bridgeAddress Bridge address
* @param _aggLayerGateway Polygon Verifier Gateway address
*/
constructor(
IPolygonZkEVMGlobalExitRootV2 _globalExitRootManager,
IERC20Upgradeable _pol,
IPolygonZkEVMBridge _bridgeAddress,
IAggLayerGateway _aggLayerGateway
) {
// Check non zero inputs
if (
address(_globalExitRootManager) == address(0) ||
address(_pol) == address(0) ||
address(_bridgeAddress) == address(0) ||
address(_aggLayerGateway) == address(0)
) {
revert InvalidConstructorInputs();
}
globalExitRootManager = _globalExitRootManager;
pol = _pol;
bridgeAddress = _bridgeAddress;
aggLayerGateway = _aggLayerGateway;
// Disable initializers on the implementation following the best practices
_disableInitializers();
}
/**
* Initializer function to set new rollup manager version
*/
function initialize() external virtual reinitializer(4) {
emit UpdateRollupManagerVersion(ROLLUP_MANAGER_VERSION);
}
///////////////////////////////////////
// Rollups management functions
///////////////////////////////////////
////////////////
// Rollups Types
////////////////
/**
* @notice Add a new rollup type
* @param consensusImplementation Consensus implementation
* @param verifier Verifier address
* @param forkID ForkID of the verifier
* @param rollupVerifierType rollup verifier type
* @param genesis Genesis block of the rollup
* @param description Description of the rollup type
* @param programVKey Hashed program that will be executed in case of using a "general purpose ZK verifier" e.g SP1
*/
function addNewRollupType(
address consensusImplementation,
address verifier,
uint64 forkID,
VerifierType rollupVerifierType,
bytes32 genesis,
string memory description,
bytes32 programVKey
) external onlyRole(_ADD_ROLLUP_TYPE_ROLE) {
// Check proposed address is not this contract to avoid self-referential loops causing infinite delegate calls
if (consensusImplementation == address(this)) {
revert InvalidImplementationAddress();
}
uint32 rollupTypeID = ++rollupTypeCount;
if (rollupVerifierType == VerifierType.Pessimistic) {
// No genesis on pessimistic rollups
if (genesis != bytes32(0)) revert InvalidRollupType();
} else if (rollupVerifierType == VerifierType.ALGateway) {
// Those params should be zero for ALGateway rollup types
if (
verifier != address(0) ||
forkID != 0 ||
genesis != bytes32(0) ||
programVKey != bytes32(0)
) revert InvalidRollupType();
} else if (rollupVerifierType == VerifierType.StateTransition) {
// No programVKey on state transition rollups
if (programVKey != bytes32(0)) revert InvalidRollupType();
} else {
// unreachable code since solidity enforces the enum input rollupVerifierType to be one of the enum values
revert InvalidRollupType();
}
rollupTypeMap[rollupTypeID] = RollupType({
consensusImplementation: consensusImplementation,
verifier: verifier,
forkID: forkID,
rollupVerifierType: rollupVerifierType,
obsolete: false,
genesis: genesis,
programVKey: programVKey
});
emit AddNewRollupType(
rollupTypeID,
consensusImplementation,
verifier,
forkID,
rollupVerifierType,
genesis,
description,
programVKey
);
}
/**
* @notice Obsolete Rollup type
* @param rollupTypeID Rollup type to obsolete
*/
function obsoleteRollupType(
uint32 rollupTypeID
) external onlyRole(_OBSOLETE_ROLLUP_TYPE_ROLE) {
// Check that rollup type exists
if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check rollup type is not obsolete
RollupType storage currentRollupType = rollupTypeMap[rollupTypeID];
if (currentRollupType.obsolete) {
revert RollupTypeObsolete();
}
currentRollupType.obsolete = true;
emit ObsoleteRollupType(rollupTypeID);
}
/**
* @notice Create a new rollup
* @param rollupTypeID Rollup type to deploy
* @param chainID ChainID of the rollup, must be a new one, can not have more than 32 bits
* @param initializeBytesAggchain Encoded params to initialize the chain. Each aggchain has its encoded params.
* @dev in case of rollupType state transition or pessimistic, the encoded params
* are the following: (address admin, address sequencer, address gasTokenAddress, string sequencerURL, string networkName)
*/
function attachAggchainToAL(
uint32 rollupTypeID,
uint64 chainID,
bytes memory initializeBytesAggchain
) external onlyRole(_CREATE_ROLLUP_ROLE) {
// Check that rollup type exists
if (rollupTypeID == 0 || rollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check rollup type is not obsolete
RollupType storage rollupType = rollupTypeMap[rollupTypeID];
if (rollupType.obsolete) {
revert RollupTypeObsolete();
}
// check chainID max value
// Currently we have this limitation by the circuit, might be removed in a future
if (chainID > type(uint32).max) {
revert ChainIDOutOfRange();
}
// Check chainID nullifier
if (chainIDToRollupID[chainID] != 0) {
revert ChainIDAlreadyExist();
}
// Create a new Rollup, using a transparent proxy pattern
// Consensus will be the implementation, and this contract the admin
uint32 rollupID = ++rollupCount;
address rollupAddress = address(
new PolygonTransparentProxy(
rollupType.consensusImplementation,
address(this),
new bytes(0)
)
);
// Set chainID to rollup id mapping
chainIDToRollupID[chainID] = rollupID;
// Set rollup address to rollup id mapping
rollupAddressToID[rollupAddress] = rollupID;
// Set rollup data
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollup.rollupContract = rollupAddress;
rollup.chainID = chainID;
rollup.rollupTypeID = rollupTypeID;
rollup.rollupVerifierType = rollupType.rollupVerifierType;
if (rollupType.rollupVerifierType == VerifierType.ALGateway) {
// Emit create new aggchain event
emit CreateNewAggchain(
rollupID,
rollupTypeID,
rollupAddress,
chainID,
uint8(rollupType.rollupVerifierType),
initializeBytesAggchain
);
// This event is emitted for backwards compatibility
/// @dev the address is hardcoded as it doesn't apply for aggchains and zero address is used for ether
emit CreateNewRollup(
rollupID,
rollupTypeID,
rollupAddress,
chainID,
_NO_ADDRESS
);
address aggchainManager = abi.decode(
initializeBytesAggchain,
(address)
);
// Set the aggchain manager, aggchain contract will be initialized later
// through the aggchain manager
IAggchainBase(rollupAddress).initAggchainManager(aggchainManager);
} else {
// assign non ALGateway values to rollup data
rollup.forkID = rollupType.forkID;
rollup.verifier = rollupType.verifier;
rollup.batchNumToStateRoot[0] = rollupType.genesis;
rollup.programVKey = rollupType.programVKey;
// custom parsing of the initializeBytesAggchain for a sate transition or pessimistic rollup
(
address admin,
address sequencer,
address gasTokenAddress,
string memory sequencerURL,
string memory networkName
) = abi.decode(
initializeBytesAggchain,
(address, address, address, string, string)
);
// Emit create new rollup event
emit CreateNewRollup(
rollupID,
rollupTypeID,
rollupAddress,
chainID,
gasTokenAddress
);
// Initialize new rollup
IPolygonRollupBase(rollupAddress).initialize(
admin,
sequencer,
rollupID,
gasTokenAddress,
sequencerURL,
networkName
);
}
}
/**
* @notice Add an already deployed rollup
* note that this rollup does not follow any rollupType
* @param rollupAddress Rollup address
* @param verifier Verifier address, must be added before
* @param forkID Fork id of the added rollup
* @param chainID Chain id of the added rollup
* @param initRoot Genesis block for StateTransitionChains & localExitRoot for pessimistic chain
* @param rollupVerifierType Compatibility ID for the added rollup
* @param programVKey Hashed program that will be executed in case of using a "general purpose ZK verifier" e.g SP1
* @param initPessimisticRoot Pessimistic root to init the chain.
*/
function addExistingRollup(
address rollupAddress,
address verifier,
uint64 forkID,
uint64 chainID,
bytes32 initRoot,
VerifierType rollupVerifierType,
bytes32 programVKey,
bytes32 initPessimisticRoot
) external onlyRole(_ADD_EXISTING_ROLLUP_ROLE) {
// Check chainID nullifier
if (chainIDToRollupID[chainID] != 0) {
revert ChainIDAlreadyExist();
}
// check chainID max value
// Currently we have this limitation by the circuit, might be removed in a future
if (chainID > type(uint32).max) {
revert ChainIDOutOfRange();
}
// Check if rollup address was already added
if (rollupAddressToID[address(rollupAddress)] != 0) {
revert RollupAddressAlreadyExist();
}
// Check proposed address is not this contract to avoid self-referential loops causing infinite delegate calls
if (rollupAddress == address(this) || rollupAddress.code.length == 0) {
revert InvalidImplementationAddress();
}
// Increment rollup count
uint32 rollupID = ++rollupCount;
// Set chainID nullifier
chainIDToRollupID[chainID] = rollupID;
// Store rollup data
rollupAddressToID[address(rollupAddress)] = rollupID;
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollup.rollupContract = rollupAddress;
rollup.forkID = forkID;
rollup.verifier = verifier;
rollup.chainID = chainID;
rollup.rollupVerifierType = rollupVerifierType;
// Check verifier type
if (rollupVerifierType == VerifierType.Pessimistic) {
rollup.programVKey = programVKey;
rollup.lastPessimisticRoot = initPessimisticRoot;
rollup.lastLocalExitRoot = initRoot;
if (verifier.code.length == 0) {
revert InvalidVerifierAddress();
}
} else if (rollupVerifierType == VerifierType.ALGateway) {
if (
verifier != address(0) ||
forkID != 0 ||
programVKey != bytes32(0)
) {
revert InvalidInputsForRollupType();
}
rollup.lastPessimisticRoot = initPessimisticRoot;
rollup.lastLocalExitRoot = initRoot;
} else {
if (
programVKey != bytes32(0) || initPessimisticRoot != bytes32(0)
) {
revert InvalidInputsForRollupType();
}
rollup.batchNumToStateRoot[0] = initRoot;
if (verifier.code.length == 0) {
revert InvalidVerifierAddress();
}
}
emit AddExistingRollup(
rollupID,
forkID,
address(rollupAddress),
chainID,
rollupVerifierType,
0,
programVKey,
initPessimisticRoot
);
}
/**
* @notice Upgrade an existing rollup from the rollup admin address
* This address is able to update the rollup with more restrictions that the _UPDATE_ROLLUP_ROLE
* @param rollupContract Rollup consensus proxy address
* @param newRollupTypeID New rollupTypeID to upgrade to
*/
function updateRollupByRollupAdmin(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID
) external {
// Check admin of the network is msg.sender
if (IPolygonRollupBase(address(rollupContract)).admin() != msg.sender) {
revert OnlyRollupAdmin();
}
// Check all sequences are verified before upgrading
RollupData storage rollup = _rollupIDToRollupData[
rollupAddressToID[address(rollupContract)]
];
// Check all sequenced batches are verified
if (rollup.lastBatchSequenced != rollup.lastVerifiedBatch) {
revert AllSequencedMustBeVerified();
}
// Not allowed to update to an older rollup type id, only supported from updateRollup function
// Rollups added via 'addExistingRollup' has rollupTypeID = 0
if (rollup.rollupTypeID >= newRollupTypeID) {
revert UpdateToOldRollupTypeID();
}
// note that for rollups via 'addExistingRollup', the rollupTypeID is set to 0
// Admin can't update to a different rollup type
if (
rollup.rollupVerifierType !=
rollupTypeMap[newRollupTypeID].rollupVerifierType
) {
revert UpdateNotCompatible();
}
_updateRollup(rollupContract, newRollupTypeID, new bytes(0));
}
/**
* @notice Upgrade an existing rollup
* @param rollupContract Rollup consensus proxy address
* @param newRollupTypeID New rollupTypeID to upgrade to
* @param upgradeData Upgrade data
*/
function updateRollup(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID,
bytes memory upgradeData
) external onlyRole(_UPDATE_ROLLUP_ROLE) {
_updateRollup(rollupContract, newRollupTypeID, upgradeData);
}
/**
* @notice Upgrade an existing rollup
* @param rollupContract Rollup consensus proxy address
* @param newRollupTypeID New rollupTypeID to upgrade to
* @param upgradeData Upgrade data
*/
function _updateRollup(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID,
bytes memory upgradeData
) internal {
// Check that rollup type exists
if (newRollupTypeID == 0 || newRollupTypeID > rollupTypeCount) {
revert RollupTypeDoesNotExist();
}
// Check the rollup exists
uint32 rollupID = rollupAddressToID[address(rollupContract)];
if (rollupID == 0) {
revert RollupMustExist();
}
RollupData storage rollup = _rollupIDToRollupData[rollupID];
// The update must be to a new rollup type
if (rollup.rollupTypeID == newRollupTypeID) {
revert UpdateToSameRollupTypeID();
}
RollupType storage newRollupType = rollupTypeMap[newRollupTypeID];
// Check rollup type is not obsolete
if (newRollupType.obsolete) {
revert RollupTypeObsolete();
}
// Only allow update rollupVerifierType when updating to ALGateway
if (
newRollupType.rollupVerifierType != VerifierType.ALGateway &&
rollup.rollupVerifierType != newRollupType.rollupVerifierType
) {
revert UpdateNotCompatible();
}
// Update rollup parameters
rollup.verifier = newRollupType.verifier;
rollup.forkID = newRollupType.forkID;
rollup.programVKey = newRollupType.programVKey;
rollup.rollupTypeID = newRollupTypeID;
rollup.rollupVerifierType = newRollupType.rollupVerifierType;
uint64 lastVerifiedBatch = getLastVerifiedBatch(rollupID);
rollup.lastVerifiedBatchBeforeUpgrade = lastVerifiedBatch;
// Upgrade rollup
rollupContract.upgradeToAndCall(
newRollupType.consensusImplementation,
upgradeData
);
emit UpdateRollup(rollupID, newRollupTypeID, lastVerifiedBatch);
}
/**
* @notice Rollback batches of the target rollup
* Only applies to state transition rollups
* @param rollupContract Rollup consensus proxy address
* @param targetBatch Batch to rollback up to but not including this batch
*/
function rollbackBatches(
IPolygonRollupBase rollupContract,
uint64 targetBatch
) external nonReentrant {
// Check msg.sender has _UPDATE_ROLLUP_ROLE rol or is the admin of the network
if (
!hasRole(_UPDATE_ROLLUP_ROLE, msg.sender) &&
IPolygonRollupBase(address(rollupContract)).admin() != msg.sender
) {
revert NotAllowedAddress();
}
// Check the rollup exists
uint32 rollupID = rollupAddressToID[address(rollupContract)];
if (rollupID == 0) {
revert RollupMustExist();
}
// Load rollup
RollupData storage rollup = _rollupIDToRollupData[rollupID];
if (rollup.rollupVerifierType != VerifierType.StateTransition) {
revert OnlyStateTransitionChains();
}
uint64 lastBatchSequenced = rollup.lastBatchSequenced;
// Batch to rollback should be already sequenced
if (
targetBatch >= lastBatchSequenced ||
targetBatch < rollup.lastVerifiedBatch
) {
revert RollbackBatchIsNotValid();
}
uint64 currentBatch = lastBatchSequenced;
// delete sequence batches structs until the targetBatch
while (currentBatch != targetBatch) {
// Load previous end of sequence batch
uint64 previousBatch = rollup
.sequencedBatches[currentBatch]
.previousLastBatchSequenced;
// Batch to rollback must be end of a sequence
if (previousBatch < targetBatch) {
revert RollbackBatchIsNotEndOfSequence();
}
// delete sequence information
delete rollup.sequencedBatches[currentBatch];
// Update current batch for next iteration
currentBatch = previousBatch;
}
// Update last batch sequenced on rollup data
rollup.lastBatchSequenced = targetBatch;
// Update totalSequencedBatches
totalSequencedBatches -= lastBatchSequenced - targetBatch;
// Clean pending state if any
rollupContract.rollbackBatches(
targetBatch,
rollup.sequencedBatches[targetBatch].accInputHash
);
emit RollbackBatches(
rollupID,
targetBatch,
rollup.sequencedBatches[targetBatch].accInputHash
);
}
/////////////////////////////////////
// Sequence/Verify batches functions
////////////////////////////////////
/**
* @notice Sequence batches, callback called by one of the consensus managed by this contract
* @param newSequencedBatches Number of batches sequenced
* @param newAccInputHash New accumulate input hash
*/
function onSequenceBatches(
uint64 newSequencedBatches,
bytes32 newAccInputHash
) external ifNotEmergencyState returns (uint64) {
// Check that the msg.sender is an added rollup
uint32 rollupID = rollupAddressToID[msg.sender];
if (rollupID == 0) {
revert SenderMustBeRollup();
}
// This prevents overwriting sequencedBatches
if (newSequencedBatches == 0) {
revert MustSequenceSomeBatch();
}
RollupData storage rollup = _rollupIDToRollupData[rollupID];
if (rollup.rollupVerifierType != VerifierType.StateTransition) {
revert OnlyStateTransitionChains();
}
// Update total sequence parameters
totalSequencedBatches += newSequencedBatches;
// Update sequenced batches of the current rollup
uint64 previousLastBatchSequenced = rollup.lastBatchSequenced;
uint64 newLastBatchSequenced = previousLastBatchSequenced +
newSequencedBatches;
rollup.lastBatchSequenced = newLastBatchSequenced;
rollup.sequencedBatches[newLastBatchSequenced] = SequencedBatchData({
accInputHash: newAccInputHash,
sequencedTimestamp: uint64(block.timestamp),
previousLastBatchSequenced: previousLastBatchSequenced
});
emit OnSequenceBatches(rollupID, newLastBatchSequenced);
return newLastBatchSequenced;
}
/**
* @notice Allows a trusted aggregator to verify multiple batches
* @param rollupID Rollup identifier
* @param pendingStateNum Init pending state, 0 if consolidated state is used (deprecated)
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param newStateRoot New State root once the batch is processed
* @param beneficiary Address that will receive the verification reward
* @param proof Fflonk proof
*/
function verifyBatchesTrustedAggregator(
uint32 rollupID,
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) external onlyRole(_TRUSTED_AGGREGATOR_ROLE) {
// Pending state became deprecated,
// It's still there just to have backwards compatibility interface
if (pendingStateNum != 0) {
revert PendingStateNumExist();
}
RollupData storage rollup = _rollupIDToRollupData[rollupID];
if (rollup.rollupVerifierType != VerifierType.StateTransition) {
revert OnlyStateTransitionChains();
}
_verifyAndRewardBatches(
rollup,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
newStateRoot,
beneficiary,
proof
);
// Consolidate state
rollup.lastVerifiedBatch = finalNewBatch;
rollup.batchNumToStateRoot[finalNewBatch] = newStateRoot;
rollup.lastLocalExitRoot = newLocalExitRoot;
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(getRollupExitRoot());
emit VerifyBatchesTrustedAggregator(
rollupID,
finalNewBatch,
newStateRoot,
newLocalExitRoot,
msg.sender
);
}
/**
* @notice Verify and reward batches internal function
* @param rollup Rollup Data storage pointer that will be used to the verification
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param newStateRoot New State root once the batch is processed
* @param beneficiary Address that will receive the verification reward
* @param proof Fflonk proof
*/
function _verifyAndRewardBatches(
RollupData storage rollup,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) internal virtual {
bytes32 oldStateRoot;
uint64 currentLastVerifiedBatch = _getLastVerifiedBatch(rollup);
if (initNumBatch < rollup.lastVerifiedBatchBeforeUpgrade) {
revert InitBatchMustMatchCurrentForkID();
}
// Use consolidated state
oldStateRoot = rollup.batchNumToStateRoot[initNumBatch];
if (oldStateRoot == bytes32(0)) {
revert OldStateRootDoesNotExist();
}
// Check initNumBatch is inside the range, sanity check
if (initNumBatch > currentLastVerifiedBatch) {
revert InitNumBatchAboveLastVerifiedBatch();
}
// Check final batch
if (finalNewBatch <= currentLastVerifiedBatch) {
revert FinalNumBatchBelowLastVerifiedBatch();
}
// Get snark bytes
bytes memory snarkHashBytes = _getInputSnarkBytes(
rollup,
initNumBatch,
finalNewBatch,
newLocalExitRoot,
oldStateRoot,
newStateRoot
);
// Calculate the snark input
uint256 inputSnark = uint256(sha256(snarkHashBytes)) % _RFIELD;
// Verify proof
if (
!IVerifierRollup(rollup.verifier).verifyProof(proof, [inputSnark])
) {
revert InvalidProof();
}
// Pay POL rewards
uint64 newVerifiedBatches = finalNewBatch - currentLastVerifiedBatch;
pol.safeTransfer(
beneficiary,
calculateRewardPerBatch() * newVerifiedBatches
);
// Update aggregation parameters
totalVerifiedBatches += newVerifiedBatches;
lastAggregationTimestamp = uint64(block.timestamp);
// Callback to the rollup address
IPolygonRollupBase(rollup.rollupContract).onVerifyBatches(
finalNewBatch,
newStateRoot,
msg.sender
);
}
/**
* @notice Allows a trusted aggregator to verify pessimistic proof
* @param rollupID Rollup identifier
* @param l1InfoTreeLeafCount Count of the L1InfoTree leaf that will be used to verify imported bridge exits
* @param newLocalExitRoot New local exit root
* @param newPessimisticRoot New pessimistic information, Hash(localBalanceTreeRoot, nullifierTreeRoot)
* @param proof SP1 proof (Plonk)
* @param aggchainData Specific custom data to verify Aggregation layer chains
* @dev A reentrancy measure has been applied because this function calls `onVerifyPessimistic`, is an open function implemented by the aggchains
* @dev the function can not be a view because the nonReentrant uses a transient storage variable
*/
function verifyPessimisticTrustedAggregator(
uint32 rollupID,
uint32 l1InfoTreeLeafCount,
bytes32 newLocalExitRoot,
bytes32 newPessimisticRoot,
bytes calldata proof,
bytes calldata aggchainData
) external onlyRole(_TRUSTED_AGGREGATOR_ROLE) nonReentrant {
RollupData storage rollup = _rollupIDToRollupData[rollupID];
// Not for state transition chains
if (rollup.rollupVerifierType == VerifierType.StateTransition) {
revert StateTransitionChainsNotAllowed();
}
// Not aggchainData for VerifierType.Pessimistic
if (
rollup.rollupVerifierType == VerifierType.Pessimistic &&
aggchainData.length != 0
) {
revert AggchainDataMustBeZeroForPessimisticVerifierType();
}
// Check l1InfoTreeLeafCount has a valid l1InfoTreeRoot
bytes32 l1InfoRoot = globalExitRootManager.l1InfoRootMap(
l1InfoTreeLeafCount
);
if (l1InfoRoot == bytes32(0)) {
revert L1InfoTreeLeafCountInvalid();
}
bytes memory inputPessimisticBytes = _getInputPessimisticBytes(
rollupID,
rollup,
l1InfoRoot,
newLocalExitRoot,
newPessimisticRoot,
aggchainData
);
if (rollup.rollupVerifierType == VerifierType.ALGateway) {
// Verify proof. The pessimistic proof selector is attached at the first 4 bytes of the proof
// proof[0:4]: 4 bytes selector pp
// proof[4:8]: 4 bytes selector SP1 verifier
// proof[8:]: proof
aggLayerGateway.verifyPessimisticProof(
inputPessimisticBytes,
proof
);
} else {
// Verify proof
ISP1Verifier(rollup.verifier).verifyProof(
rollup.programVKey,
inputPessimisticBytes,
proof
);
}
// Update aggregation parameters
lastAggregationTimestamp = uint64(block.timestamp);
// Consolidate state
bytes32 prevLocalExitRoot = rollup.lastLocalExitRoot;
rollup.lastLocalExitRoot = newLocalExitRoot;
bytes32 prevPessimisticRoot = rollup.lastPessimisticRoot;
rollup.lastPessimisticRoot = newPessimisticRoot;
// Interact with globalExitRootManager
globalExitRootManager.updateExitRoot(getRollupExitRoot());
// Same event as verifyBatches to support current bridge service to synchronize everything
/// @dev moved newLocalExitRoot to aux variable to avoid stack too deep errors at compilation
bytes32 newLocalExitRootAux = newLocalExitRoot;
emit VerifyBatchesTrustedAggregator(
rollupID,
0, // final batch: does not apply in pessimistic
bytes32(0), // new state root: does not apply in pessimistic
newLocalExitRootAux,
msg.sender
);
/// @dev emit a second event with more data, not updated/removed the other one for backwards compatibility reasons
emit VerifyPessimisticStateTransition(
rollupID,
prevPessimisticRoot,
newPessimisticRoot,
prevLocalExitRoot,
newLocalExitRootAux,
l1InfoRoot,
msg.sender
);
if (rollup.rollupVerifierType == VerifierType.ALGateway) {
// Allow chains to manage customData
// Callback to the rollup address
IAggchainBase(rollup.rollupContract).onVerifyPessimistic(
aggchainData
);
}
}
////////////////////////
// Emergency state functions
////////////////////////
/**
* @notice Function to activate emergency state, which also enables the emergency mode on both PolygonRollupManager and PolygonZkEVMBridge contracts
* If not called by the owner must not have been aggregated in a _HALT_AGGREGATION_TIMEOUT period and an emergency state was not happened in the same period
*/
function activateEmergencyState() external {
if (!hasRole(_EMERGENCY_COUNCIL_ROLE, msg.sender)) {
if (
lastAggregationTimestamp == 0 ||
lastAggregationTimestamp + _HALT_AGGREGATION_TIMEOUT >
block.timestamp ||
lastDeactivatedEmergencyStateTimestamp +
_HALT_AGGREGATION_TIMEOUT >
block.timestamp
) {
revert HaltTimeoutNotExpired();
}
}
_activateEmergencyState();
}
/**
* @notice Function to deactivate emergency state on both PolygonRollupManager and PolygonZkEVMBridge contracts
*/
function deactivateEmergencyState()
external
onlyRole(_STOP_EMERGENCY_ROLE)
{
// Set last deactivated emergency state
lastDeactivatedEmergencyStateTimestamp = uint64(block.timestamp);
// Deactivate emergency state on PolygonZkEVMBridge
bridgeAddress.deactivateEmergencyState();
// Deactivate emergency state on this contract
super._deactivateEmergencyState();
}
/**
* @notice Internal function to activate emergency state on both PolygonRollupManager and PolygonZkEVMBridge contracts
*/
function _activateEmergencyState() internal override {
// Activate emergency state on PolygonZkEVM Bridge
bridgeAddress.activateEmergencyState();
// Activate emergency state on this contract
super._activateEmergencyState();
}
//////////////////
// Setter functions
//////////////////
/**
* @notice Set the current batch fee
* @param newBatchFee new batch fee
*/
function setBatchFee(uint256 newBatchFee) external onlyRole(_SET_FEE_ROLE) {
// check fees min and max
if (newBatchFee > _MAX_BATCH_FEE || newBatchFee < _MIN_BATCH_FEE) {
revert BatchFeeOutOfRange();
}
_batchFee = newBatchFee;
emit SetBatchFee(newBatchFee);
}
////////////////////////
// view/pure functions
///////////////////////
/**
* @notice Get the current rollup exit root
* Compute using all the local exit roots of all rollups the rollup exit root
* Since it's expected to have no more than 10 rollups in this first version, even if this approach
* has a gas consumption that scales linearly with the rollups added, it's ok
* In a future versions this computation will be done inside the circuit
*/
function getRollupExitRoot() public view returns (bytes32) {
uint256 currentNodes = rollupCount;
// If there are no nodes return 0
if (currentNodes == 0) {
return bytes32(0);
}
// This array will contain the nodes of the current iteration
bytes32[] memory tmpTree = new bytes32[](currentNodes);
// In the first iteration the nodes will be the leafs which are the local exit roots of each network
for (uint256 i = 0; i < currentNodes; i++) {
// The first rollup ID starts on 1
tmpTree[i] = _rollupIDToRollupData[uint32(i + 1)].lastLocalExitRoot;
}
// This variable will keep track of the zero hashes
bytes32 currentZeroHashHeight = 0;
// This variable will keep track of the remaining levels to compute
uint256 remainingLevels = _EXIT_TREE_DEPTH;
// Calculate the root of the sub-tree that contains all the localExitRoots
while (currentNodes != 1) {
uint256 nextIterationNodes = currentNodes / 2 + (currentNodes % 2);
bytes32[] memory nextTmpTree = new bytes32[](nextIterationNodes);
for (uint256 i = 0; i < nextIterationNodes; i++) {
// if we are on the last iteration of the current level and the nodes are odd
if (i == nextIterationNodes - 1 && (currentNodes % 2) == 1) {
nextTmpTree[i] = Hashes.efficientKeccak256(
tmpTree[i * 2],
currentZeroHashHeight
);
} else {
nextTmpTree[i] = Hashes.efficientKeccak256(
tmpTree[i * 2],
tmpTree[(i * 2) + 1]
);
}
}
// Update tree variables
tmpTree = nextTmpTree;
currentNodes = nextIterationNodes;
currentZeroHashHeight = Hashes.efficientKeccak256(
currentZeroHashHeight,
currentZeroHashHeight
);
remainingLevels--;
}
bytes32 currentRoot = tmpTree[0];
// Calculate remaining levels, since it's a sequential merkle tree, the rest of the tree are zeroes
for (uint256 i = 0; i < remainingLevels; i++) {
currentRoot = Hashes.efficientKeccak256(
currentRoot,
currentZeroHashHeight
);
currentZeroHashHeight = Hashes.efficientKeccak256(
currentZeroHashHeight,
currentZeroHashHeight
);
}
return currentRoot;
}
/**
* @notice Get the last verified batch
*/
function getLastVerifiedBatch(
uint32 rollupID
) public view returns (uint64) {
return _getLastVerifiedBatch(_rollupIDToRollupData[rollupID]);
}
/**
* @notice Get the last verified batch
*/
function _getLastVerifiedBatch(
RollupData storage rollup
) internal view returns (uint64) {
return rollup.lastVerifiedBatch;
}
/**
* @notice Function to calculate the reward to verify a single batch
*/
function calculateRewardPerBatch() public view returns (uint256) {
uint256 currentBalance = pol.balanceOf(address(this));
// Total Batches to be verified = total Sequenced Batches - total verified Batches
uint256 totalBatchesToVerify = totalSequencedBatches -
totalVerifiedBatches;
if (totalBatchesToVerify == 0) return 0;
return currentBalance / totalBatchesToVerify;
}
/**
* @notice Get batch fee
* This function is used instead of the automatic public view one,
* because in a future might change the behavior and we will be able to maintain the interface
*/
function getBatchFee() public view returns (uint256) {
return _batchFee;
}
/**
* @notice Get forced batch fee
*/
function getForcedBatchFee() public view returns (uint256) {
return _batchFee * 100;
}
/**
* @notice Function to calculate the pessimistic input bytes
* @param rollupID Rollup id used to calculate the input snark bytes
* @param l1InfoTreeRoot L1 Info tree root to proof imported bridges
* @param newLocalExitRoot New local exit root
* @param newPessimisticRoot New pessimistic information, Hash(localBalanceTreeRoot, nullifierTreeRoot)
* @param aggchainData Specific custom data to verify Aggregation layer chains
*/
function getInputPessimisticBytes(
uint32 rollupID,
bytes32 l1InfoTreeRoot,
bytes32 newLocalExitRoot,
bytes32 newPessimisticRoot,
bytes calldata aggchainData
) external view returns (bytes memory) {
return
_getInputPessimisticBytes(
rollupID,
_rollupIDToRollupData[rollupID],
l1InfoTreeRoot,
newLocalExitRoot,
newPessimisticRoot,
aggchainData
);
}
/**
* @notice Function to calculate the input snark bytes
* @param rollupID Rollup identifier
* @param rollup Rollup data storage pointer
* @param l1InfoTreeRoot L1 Info tree root to proof imported bridges
* @param newLocalExitRoot New local exit root
* @param newPessimisticRoot New pessimistic information, Hash(localBalanceTreeRoot, nullifierTreeRoot)
*/
function _getInputPessimisticBytes(
uint32 rollupID,
RollupData storage rollup,
bytes32 l1InfoTreeRoot,
bytes32 newLocalExitRoot,
bytes32 newPessimisticRoot,
bytes calldata aggchainData
) internal view returns (bytes memory inputPessimisticBytes) {
// Different consensusHash and encoding if the rollup is ALGateway or pessimistic
if (rollup.rollupVerifierType == VerifierType.ALGateway) {
bytes32 aggchainHash = IAggchainBase(rollup.rollupContract)
.getAggchainHash(aggchainData);
inputPessimisticBytes = abi.encodePacked(
rollup.lastLocalExitRoot,
rollup.lastPessimisticRoot,
l1InfoTreeRoot,
rollupID,
aggchainHash,
newLocalExitRoot,
newPessimisticRoot
);
} else {
bytes32 consensusHash = IPolygonPessimisticConsensus(
address(rollup.rollupContract)
).getConsensusHash();
inputPessimisticBytes = abi.encodePacked(
rollup.lastLocalExitRoot,
rollup.lastPessimisticRoot,
l1InfoTreeRoot,
rollupID,
consensusHash,
newLocalExitRoot,
newPessimisticRoot
);
}
}
/**
* @notice Function to calculate the input snark bytes
* @param rollupID Rollup id used to calculate the input snark bytes
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param oldStateRoot State root before batch is processed
* @param newStateRoot New State root once the batch is processed
*/
function getInputSnarkBytes(
uint32 rollupID,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 oldStateRoot,
bytes32 newStateRoot
) public view returns (bytes memory) {
return
_getInputSnarkBytes(
_rollupIDToRollupData[rollupID],
initNumBatch,
finalNewBatch,
newLocalExitRoot,
oldStateRoot,
newStateRoot
);
}
/**
* @notice Function to calculate the input snark bytes
* @param rollup Rollup data storage pointer
* @param initNumBatch Batch which the aggregator starts the verification
* @param finalNewBatch Last batch aggregator intends to verify
* @param newLocalExitRoot New local exit root once the batch is processed
* @param oldStateRoot State root before batch is processed
* @param newStateRoot New State root once the batch is processed
*/
function _getInputSnarkBytes(
RollupData storage rollup,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 oldStateRoot,
bytes32 newStateRoot
) internal view returns (bytes memory) {
// Sanity check
bytes32 oldAccInputHash = rollup
.sequencedBatches[initNumBatch]
.accInputHash;
bytes32 newAccInputHash = rollup
.sequencedBatches[finalNewBatch]
.accInputHash;
// Sanity check
if (initNumBatch != 0 && oldAccInputHash == bytes32(0)) {
revert OldAccInputHashDoesNotExist();
}
if (newAccInputHash == bytes32(0)) {
revert NewAccInputHashDoesNotExist();
}
// Check that new state root is inside goldilocks field
if (!_checkStateRootInsidePrime(uint256(newStateRoot))) {
revert NewStateRootNotInsidePrime();
}
return
abi.encodePacked(
msg.sender,
oldStateRoot,
oldAccInputHash,
initNumBatch,
rollup.chainID,
rollup.forkID,
newStateRoot,
newAccInputHash,
newLocalExitRoot,
finalNewBatch
);
}
/**
* @notice Function to check if the state root is inside of the prime field
* @param newStateRoot New State root once the batch is processed
*/
function _checkStateRootInsidePrime(
uint256 newStateRoot
) internal pure returns (bool) {
if (
((newStateRoot & _MAX_UINT_64) < _GOLDILOCKS_PRIME_FIELD) &&
(((newStateRoot >> 64) & _MAX_UINT_64) < _GOLDILOCKS_PRIME_FIELD) &&
(((newStateRoot >> 128) & _MAX_UINT_64) <
_GOLDILOCKS_PRIME_FIELD) &&
((newStateRoot >> 192) < _GOLDILOCKS_PRIME_FIELD)
) {
return true;
} else {
return false;
}
}
/**
* @notice Get rollup state root given a batch number
* @param rollupID Rollup identifier
* @param batchNum Batch number
*/
function getRollupBatchNumToStateRoot(
uint32 rollupID,
uint64 batchNum
) public view returns (bytes32) {
return _rollupIDToRollupData[rollupID].batchNumToStateRoot[batchNum];
}
/**
* @notice Get rollup sequence batches struct given a batch number
* @param rollupID Rollup identifier
* @param batchNum Batch number
*/
function getRollupSequencedBatches(
uint32 rollupID,
uint64 batchNum
) public view returns (SequencedBatchData memory) {
return _rollupIDToRollupData[rollupID].sequencedBatches[batchNum];
}
/**
* @notice Get rollup data: VerifierType StateTransition
* @param rollupID Rollup identifier
*/
function rollupIDToRollupData(
uint32 rollupID
) public view returns (RollupDataReturn memory rollupData) {
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollupData.rollupContract = rollup.rollupContract;
rollupData.chainID = rollup.chainID;
rollupData.verifier = rollup.verifier;
rollupData.forkID = rollup.forkID;
rollupData.lastLocalExitRoot = rollup.lastLocalExitRoot;
rollupData.lastBatchSequenced = rollup.lastBatchSequenced;
rollupData.lastVerifiedBatch = rollup.lastVerifiedBatch;
rollupData._legacyLastPendingState = rollup._legacyLastPendingState;
rollupData._legacyLastPendingStateConsolidated = rollup
._legacyLastPendingStateConsolidated;
rollupData.lastVerifiedBatchBeforeUpgrade = rollup
.lastVerifiedBatchBeforeUpgrade;
rollupData.rollupTypeID = rollup.rollupTypeID;
rollupData.rollupVerifierType = rollup.rollupVerifierType;
}
/**
* @notice Get rollup data: VerifierType State transition
* @param rollupID Rollup identifier
*/
function rollupIDToRollupDataDeserialized(
uint32 rollupID
)
public
view
returns (
address rollupContract,
uint64 chainID,
address verifier,
uint64 forkID,
bytes32 lastLocalExitRoot,
uint64 lastBatchSequenced,
uint64 lastVerifiedBatch,
uint64 _legacyLastPendingState,
uint64 _legacyLastPendingStateConsolidated,
uint64 lastVerifiedBatchBeforeUpgrade,
uint64 rollupTypeID,
VerifierType rollupVerifierType
)
{
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollupContract = rollup.rollupContract;
chainID = rollup.chainID;
verifier = rollup.verifier;
forkID = rollup.forkID;
lastLocalExitRoot = rollup.lastLocalExitRoot;
lastBatchSequenced = rollup.lastBatchSequenced;
lastVerifiedBatch = rollup.lastVerifiedBatch;
_legacyLastPendingState = rollup._legacyLastPendingState;
_legacyLastPendingStateConsolidated = rollup
._legacyLastPendingStateConsolidated;
lastVerifiedBatchBeforeUpgrade = rollup.lastVerifiedBatchBeforeUpgrade;
rollupTypeID = rollup.rollupTypeID;
rollupVerifierType = rollup.rollupVerifierType;
}
/**
* @notice Get rollup data: VerifierType Pessimistic
* @param rollupID Rollup identifier
*/
function rollupIDToRollupDataV2(
uint32 rollupID
) public view returns (RollupDataReturnV2 memory rollupData) {
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollupData.rollupContract = rollup.rollupContract;
rollupData.chainID = rollup.chainID;
rollupData.verifier = rollup.verifier;
rollupData.forkID = rollup.forkID;
rollupData.lastLocalExitRoot = rollup.lastLocalExitRoot;
rollupData.lastBatchSequenced = rollup.lastBatchSequenced;
rollupData.lastVerifiedBatch = rollup.lastVerifiedBatch;
rollupData.lastVerifiedBatchBeforeUpgrade = rollup
.lastVerifiedBatchBeforeUpgrade;
rollupData.rollupTypeID = rollup.rollupTypeID;
rollupData.rollupVerifierType = rollup.rollupVerifierType;
rollupData.lastPessimisticRoot = rollup.lastPessimisticRoot;
rollupData.programVKey = rollup.programVKey;
}
/**
* @notice Get rollup data deserialized
* @dev A deserialized version of the rollup data done for a better parsing from etherscan
* @param rollupID Rollup identifier
*/
function rollupIDToRollupDataV2Deserialized(
uint32 rollupID
)
public
view
returns (
address rollupContract,
uint64 chainID,
address verifier,
uint64 forkID,
bytes32 lastLocalExitRoot,
uint64 lastBatchSequenced,
uint64 lastVerifiedBatch,
uint64 lastVerifiedBatchBeforeUpgrade,
uint64 rollupTypeID,
VerifierType rollupVerifierType,
bytes32 lastPessimisticRoot,
bytes32 programVKey
)
{
RollupData storage rollup = _rollupIDToRollupData[rollupID];
rollupContract = rollup.rollupContract;
chainID = rollup.chainID;
verifier = rollup.verifier;
forkID = rollup.forkID;
lastLocalExitRoot = rollup.lastLocalExitRoot;
lastBatchSequenced = rollup.lastBatchSequenced;
lastVerifiedBatch = rollup.lastVerifiedBatch;
lastVerifiedBatchBeforeUpgrade = rollup.lastVerifiedBatchBeforeUpgrade;
rollupTypeID = rollup.rollupTypeID;
rollupVerifierType = rollup.rollupVerifierType;
lastPessimisticRoot = rollup.lastPessimisticRoot;
programVKey = rollup.programVKey;
}
}
@openzeppelin/contracts-upgradeable4/access/IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@openzeppelin/contracts-upgradeable4/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable4/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts-upgradeable4/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable4/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts-upgradeable4/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable4/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable4/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
@openzeppelin/contracts-upgradeable4/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable4/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@openzeppelin/contracts-upgradeable4/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts5/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @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);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts5/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts5/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
@openzeppelin/contracts5/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
@openzeppelin/contracts5/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
@openzeppelin/contracts5/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts5/proxy/transparent/ProxyAdmin.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol)
pragma solidity ^0.8.20;
import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol";
import {Ownable} from "../../access/Ownable.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)`
* and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev Sets the initial owner who can perform upgrades.
*/
constructor(address initialOwner) Ownable(initialOwner) {}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
* See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
* - If `data` is empty, `msg.value` must be zero.
*/
function upgradeAndCall(
ITransparentUpgradeableProxy proxy,
address implementation,
bytes memory data
) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}
@openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.20;
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {ProxyAdmin} from "./ProxyAdmin.sol";
/**
* @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
* does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
* mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
* include them in the ABI so this interface must be used to interact with it.
*/
interface ITransparentUpgradeableProxy is IERC1967 {
function upgradeToAndCall(address, bytes calldata) external payable;
}
/**
* @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
* 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to
* the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
* the proxy admin cannot fallback to the target implementation.
*
* These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
* dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
* call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
* allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
* interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
*
* NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
* inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
* mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
* fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
* implementation.
*
* NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
* meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
*
* IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
* immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
* overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
* undesirable state where the admin slot is different from the actual admin.
*
* WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
* compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
* function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
* could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
// An immutable address for the admin to avoid unnecessary SLOADs before each call
// at the expense of removing the ability to change the admin once it's set.
// This is acceptable if the admin is always a ProxyAdmin instance or similar contract
// with its own ability to transfer the permissions to another account.
address private immutable _admin;
/**
* @dev The proxy caller is the current admin, and can't fallback to the proxy target.
*/
error ProxyDeniedAdminAccess();
/**
* @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
* backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
* {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_admin = address(new ProxyAdmin(initialOwner));
// Set the storage value and emit an event for ERC-1967 compatibility
ERC1967Utils.changeAdmin(_proxyAdmin());
}
/**
* @dev Returns the admin of this proxy.
*/
function _proxyAdmin() internal virtual returns (address) {
return _admin;
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
*/
function _fallback() internal virtual override {
if (msg.sender == _proxyAdmin()) {
if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
revert ProxyDeniedAdminAccess();
} else {
_dispatchUpgradeToAndCall();
}
} else {
super._fallback();
}
}
/**
* @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
}
@openzeppelin/contracts5/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@openzeppelin/contracts5/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts5/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts52/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
@openzeppelin/contracts52/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
contracts/interfaces/IBasePolygonZkEVMGlobalExitRoot.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
interface IBasePolygonZkEVMGlobalExitRoot {
/**
* @dev Thrown when the caller is not the allowed contracts
*/
error OnlyAllowedContracts();
/**
* @dev Thrown when the caller is not the coinbase neither the globalExitRootUpdater
*/
error OnlyGlobalExitRootUpdater();
/**
* @dev Thrown when trying to call a function that only the pending GlobalExitRootUpdater can call.
*/
error OnlyPendingGlobalExitRootUpdater();
/**
* @dev Thrown when the caller is not the globalExitRootRemover
*/
error OnlyGlobalExitRootRemover();
/**
* @dev Thrown when trying to call a function that only the pending GlobalExitRootRemover can call.
*/
error OnlyPendingGlobalExitRootRemover();
/**
* @dev Thrown when trying to insert a global exit root that is already set
*/
error GlobalExitRootAlreadySet();
/**
* @dev Thrown when trying to remove a ger that doesn't exist
*/
error GlobalExitRootNotFound();
/**
* @dev Thrown when trying to call a function with an input zero address
*/
error InvalidZeroAddress();
function updateExitRoot(bytes32 newRollupExitRoot) external;
function globalExitRootMap(
bytes32 globalExitRootNum
) external returns (uint256);
}
contracts/interfaces/IPolygonZkEVMBridge.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
interface IPolygonZkEVMBridge {
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error OnlyPolygonZkEVM();
/**
* @dev Thrown when the destination network is invalid
*/
error DestinationNetworkInvalid();
/**
* @dev Thrown when the amount does not match msg.value
*/
error AmountDoesNotMatchMsgValue();
/**
* @dev Thrown when user is bridging tokens and is also sending a value
*/
error MsgValueNotZero();
/**
* @dev Thrown when the Ether transfer on claimAsset fails
*/
error EtherTransferFailed();
/**
* @dev Thrown when the message transaction on claimMessage fails
*/
error MessageFailed();
/**
* @dev Thrown when the global exit root does not exist
*/
error GlobalExitRootInvalid();
/**
* @dev Thrown when the smt proof does not match
*/
error InvalidSmtProof();
/**
* @dev Thrown when an index is already claimed
*/
error AlreadyClaimed();
/**
* @dev Thrown when the owner of permit does not match the sender
*/
error NotValidOwner();
/**
* @dev Thrown when the spender of the permit does not match this contract address
*/
error NotValidSpender();
/**
* @dev Thrown when the amount of the permit does not match
*/
error NotValidAmount();
/**
* @dev Thrown when the permit data contains an invalid signature
*/
error NotValidSignature();
function bridgeAsset(
uint32 destinationNetwork,
address destinationAddress,
uint256 amount,
address token,
bool forceUpdateGlobalExitRoot,
bytes calldata permitData
) external payable;
function bridgeMessage(
uint32 destinationNetwork,
address destinationAddress,
bool forceUpdateGlobalExitRoot,
bytes calldata metadata
) external payable;
function claimAsset(
bytes32[32] calldata smtProof,
uint32 index,
bytes32 mainnetExitRoot,
bytes32 rollupExitRoot,
uint32 originNetwork,
address originTokenAddress,
uint32 destinationNetwork,
address destinationAddress,
uint256 amount,
bytes calldata metadata
) external;
function claimMessage(
bytes32[32] calldata smtProof,
uint32 index,
bytes32 mainnetExitRoot,
bytes32 rollupExitRoot,
uint32 originNetwork,
address originAddress,
uint32 destinationNetwork,
address destinationAddress,
uint256 amount,
bytes calldata metadata
) external;
function updateGlobalExitRoot() external;
function activateEmergencyState() external;
function deactivateEmergencyState() external;
}
contracts/interfaces/IVerifierRollup.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
/**
* @dev Define interface verifier
*/
interface IVerifierRollup {
function verifyProof(
bytes32[24] calldata proof,
uint256[1] calldata pubSignals
) external view returns (bool);
}
contracts/lib/EmergencyManager.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
/**
* @dev Contract helper responsible to manage the emergency state
*/
contract EmergencyManager {
/**
* @dev Thrown when emergency state is active, and the function requires otherwise
*/
error OnlyNotEmergencyState();
/**
* @dev Thrown when emergency state is not active, and the function requires otherwise
*/
error OnlyEmergencyState();
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
*/
/// @custom:oz-renamed-from _gap
uint256[10] private __gap;
// Indicates whether the emergency state is active or not
bool public isEmergencyState;
/**
* @dev Emitted when emergency state is activated
*/
event EmergencyStateActivated();
/**
* @dev Emitted when emergency state is deactivated
*/
event EmergencyStateDeactivated();
/**
* @notice Only allows a function to be callable if emergency state is unactive
*/
modifier ifNotEmergencyState() {
if (isEmergencyState) {
revert OnlyNotEmergencyState();
}
_;
}
/**
* @notice Only allows a function to be callable if emergency state is active
*/
modifier ifEmergencyState() {
if (!isEmergencyState) {
revert OnlyEmergencyState();
}
_;
}
/**
* @notice Activate emergency state
*/
function _activateEmergencyState() internal virtual ifNotEmergencyState {
isEmergencyState = true;
emit EmergencyStateActivated();
}
/**
* @notice Deactivate emergency state
*/
function _deactivateEmergencyState() internal virtual ifEmergencyState {
isEmergencyState = false;
emit EmergencyStateDeactivated();
}
}
contracts/v2/interfaces/IAggLayerGateway.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
// based on: https://github.com/succinctlabs/sp1-contracts/blob/main/contracts/src/ISP1VerifierGateway.sol
interface IAggLayerGatewayEvents {
/// @notice Emitted when a verifier route is added.
/// @param selector The verifier selector that was added.
/// @param verifier The address of the verifier contract.
/// @param pessimisticVKey The verification key
event RouteAdded(
bytes4 selector,
address verifier,
bytes32 pessimisticVKey
);
/// @notice Emitted when a verifier route is frozen.
/// @param selector The verifier selector that was frozen.
/// @param verifier The address of the verifier contract.
event RouteFrozen(
bytes4 selector,
address verifier,
bytes32 pessimisticVKey
);
/**
* Emitted when a new default aggchain verification key is added
* @param selector The 4 bytes selector of the added default aggchain verification key.
* @param newVKey New aggchain verification key to be added
*/
event AddDefaultAggchainVKey(bytes4 selector, bytes32 newVKey);
/**
* Emitted when a default aggchain verification key is update
* @param selector The 4 bytes selector of the updated default aggchain verification key.
* @param previousVKey Aggchain verification key previous value
* @param newVKey Aggchain verification key updated value
*/
event UpdateDefaultAggchainVKey(
bytes4 selector,
bytes32 previousVKey,
bytes32 newVKey
);
/**
* Emitted when a default aggchain verification key is set to zero
* @param selector The 4 bytes selector of the updated default aggchain verification key.
*/
event UnsetDefaultAggchainVKey(bytes4 selector);
}
/// @dev Extended error events from https://github.com/succinctlabs/sp1-contracts/blob/main/contracts/src/ISP1VerifierGateway.sol
interface IAggLayerGatewayErrors {
/// @notice Thrown when the verifier route is not found.
/// @param selector The verifier selector that was specified.
error RouteNotFound(bytes4 selector);
/// @notice Thrown when the verifier route is found, but is frozen.
/// @param selector The verifier selector that was specified.
error RouteIsFrozen(bytes4 selector);
/// @notice Thrown when trying to freeze a route that is already frozen.
/// @param selector The pessimistic verification key selector that was specified.
error RouteIsAlreadyFrozen(bytes4 selector);
/// @notice Thrown when adding a verifier route and the selector already contains a route.
/// @param selector The pessimistic verification key selector that was specified.
/// @param verifier The address of the verifier contract in the existing route.
error RouteAlreadyExists(bytes4 selector, address verifier);
/// @notice Thrown when adding a verifier route and the selector returned by the verifier is
/// zero.
error PPSelectorCannotBeZero();
/// @notice Thrown when adding a verifier key with value zero
error VKeyCannotBeZero();
/// @notice Thrown when the caller is not the AggLayerAdmin
error OnlyAggLayerAdmin();
//// @notice Thrown when the caller is not the pending AggLayerAdmin
error OnlyPendingAggLayerAdmin();
/// @notice Thrown when trying to add an aggchain verification key that already exists
error AggchainVKeyAlreadyExists();
/// @notice Thrown when trying to retrieve an aggchain verification key from the mapping that doesn't exists
error AggchainVKeyNotFound();
/// @notice Thrown when trying to call a function with an input zero address
error InvalidZeroAddress();
/// @notice Thrown when the input proof bytes are invalid.
error InvalidProofBytesLength();
}
/// @title IAggLayerGateway
/// @notice This contract is the interface for the AggLayerGateway.
/// @notice Based on https://github.com/succinctlabs/sp1-contracts/blob/main/contracts/src/ISP1VerifierGateway.sol
interface IAggLayerGateway is IAggLayerGatewayEvents, IAggLayerGatewayErrors {
/**
* Struct that defines a verifier route
* @param verifier The address of the verifier contract.
* @param pessimisticVKey The verification key to be used for verifying pessimistic proofs.
* @param frozen Whether the route is frozen.
*/
struct AggLayerVerifierRoute {
address verifier; // SP1 Verifier. It contains sanity check SP1 version with the 4 first bytes of the proof. proof[4:]
bytes32 pessimisticVKey;
bool frozen;
}
/**
* @notice returns the current aggchain verification key, used to verify chain's FEP.
* @dev This function is necessary to query the map from an external function. In solidity maps are not
* directly accessible from external functions like other state variables.
*/
function getDefaultAggchainVKey(
bytes4 defaultAggchainSelector
) external view returns (bytes32);
/// @notice Verifies a pessimistic proof with given public values and proof.
/// @dev It is expected that the first 4 bytes of proofBytes must match the first 4 bytes of
/// target verifier's VERIFIER_HASH.
/// @param publicValues The public values encoded as bytes.
/// @param proofBytes The proof of the program execution the SP1 zkVM encoded as bytes.
function verifyPessimisticProof(
bytes calldata publicValues,
bytes calldata proofBytes
) external view;
/// @notice Adds a verifier route. This enable proofs to be routed to this verifier.
/// @dev Only callable by the owner. The owner is responsible for ensuring that the specified
/// verifier is correct with a valid VERIFIER_HASH. Once a route to a verifier is added, it
/// cannot be removed.
/// @param pessimisticVKeySelector The verifier selector to add.
/// @param verifier The address of the verifier contract. This verifier MUST implement the
/// ISP1VerifierWithHash interface.
/// @param pessimisticVKey The verification key to be used for verifying pessimistic proofs.
function addPessimisticVKeyRoute(
bytes4 pessimisticVKeySelector,
address verifier,
bytes32 pessimisticVKey
) external;
/// @notice Freezes a verifier route. This prevents proofs from being routed to this verifier.
/// @dev Only callable by the owner. Once a route to a verifier is frozen, it cannot be
/// unfrozen.
/// @param pessimisticVKeySelector The verifier selector to freeze.
function freezePessimisticVKeyRoute(
bytes4 pessimisticVKeySelector
) external;
}
contracts/v2/interfaces/IAggchainBase.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.28;
interface IAggchainBaseEvents {
/**
* @notice Emitted when the admin adds an aggchain verification key.
* @param selector The selector of the verification key to add.
* @param newAggchainVKey The new aggchain verification key.
*/
event AddAggchainVKey(bytes4 selector, bytes32 newAggchainVKey);
/**
* @notice Emitted when the admin updates the aggchain verification key.
* @param selector The selector of the verification key to update.
* @param previousAggchainVKey The previous aggchain verification key.
* @param newAggchainVKey The new new aggchain verification key.
*/
event UpdateAggchainVKey(
bytes4 selector,
bytes32 previousAggchainVKey,
bytes32 newAggchainVKey
);
/**
* @notice Emitted when the admin set the flag useDefaultGateway to true.
*/
event EnableUseDefaultGatewayFlag();
/**
* @notice Emitted when the admin set the flag useDefaultGateway to false.
*/
event DisableUseDefaultGatewayFlag();
/**
* @notice Emitted when the vKeyManager starts the two-step transfer role setting a new pending vKeyManager.
* @param currentVKeyManager The current vKeyManager.
* @param newPendingVKeyManager The new pending vKeyManager.
*/
event TransferVKeyManagerRole(
address currentVKeyManager,
address newPendingVKeyManager
);
/**
* @notice Emitted when the pending vKeyManager accepts the vKeyManager role.
* @param oldVKeyManager The previous vKeyManager.
* @param newVKeyManager The new vKeyManager.
*/
event AcceptVKeyManagerRole(address oldVKeyManager, address newVKeyManager);
/// @dev Emitted when the aggchainManager starts the two-step transfer role setting a new pending newAggchainManager
/// @param currentAggchainManager The current pending aggchainManager
/// @param newPendingAggchainManager The new pending aggchainManager
event TransferAggchainManagerRole(
address currentAggchainManager,
address newPendingAggchainManager
);
/// @notice Emitted when the pending aggchainManager accepts the aggchainManager role
/// @param oldAggchainManager The old aggchainManager
/// @param newAggchainManager The new aggchainManager
event AcceptAggchainManagerRole(
address oldAggchainManager,
address newAggchainManager
);
}
interface IAggchainBaseErrors {
/// @notice Thrown when trying to add zero value verification key.
error ZeroValueAggchainVKey();
/// @notice Thrown when trying to add an aggchain verification key that already exists.
error OwnedAggchainVKeyAlreadyAdded();
/// @notice Thrown when trying to retrieve an aggchain verification key that does not exist.
error OwnedAggchainVKeyNotFound();
/// @notice Thrown when trying to initialize the incorrect initialize function.
error InvalidInitializeFunction();
/// @notice Thrown when trying to enable the default gateway when it is already enabled.
error UseDefaultGatewayAlreadyEnabled();
/// @notice Thrown when trying to disable the default gateway when it is already disabled.
error UseDefaultGatewayAlreadyDisabled();
/// @notice Thrown when trying to call a function that only the VKeyManager can call.
error OnlyVKeyManager();
/// @notice Thrown when trying to call a function that only the pending VKeyManager can call.
error OnlyPendingVKeyManager();
/// @notice Thrown when trying to retrieve an aggchain verification key from the mapping that doesn't exists.
error AggchainVKeyNotFound();
/// @notice Thrown when trying to deploy the aggchain with a zero address as the AggLayerGateway
error InvalidAggLayerGatewayAddress();
/// @notice Thrown when trying to set the aggchain manager to zero address.
error AggchainManagerCannotBeZero();
/// @notice Thrown when the caller is not the aggchain manager
error OnlyAggchainManager();
/// @notice Thrown when the caller is not the pending aggchain manager
error OnlyPendingAggchainManager();
/// @notice Thrown when trying to call a function with an input zero address
error InvalidZeroAddress();
/// @notice Thrown when the aggchainData has an invalid format
error InvalidAggchainDataLength();
/// @notice Thrown when the aggchainvKeySelectir contains an invalid aggchain type.
error InvalidAggchainType();
}
/**
* @title IAggchainBase
* @notice Shared interface for native aggchain implementations.
*/
interface IAggchainBase is IAggchainBaseErrors, IAggchainBaseEvents {
/**
* @notice Gets aggchain hash.
* @dev Each chain should properly manage its own aggchain hash.
* @param aggchainData Custom chain data to build the consensus hash.
*/
function getAggchainHash(
bytes calldata aggchainData
) external view returns (bytes32);
/**
* @notice Callback from the PolygonRollupManager to update the chain's state.
* @dev Each chain should properly manage its own state.
* @param aggchainData Custom chain data to update chain's state
*/
function onVerifyPessimistic(bytes calldata aggchainData) external;
/**
* @notice Sets the aggchain manager.
* @param newAggchainManager The address of the new aggchain manager.
*/
function initAggchainManager(address newAggchainManager) external;
/// @notice Returns the unique aggchain type identifier.
function AGGCHAIN_TYPE() external view returns (bytes2);
}
contracts/v2/interfaces/IPolygonConsensusBase.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
interface IPolygonConsensusBase {
function initialize(
address _admin,
address sequencer,
uint32 networkID,
address gasTokenAddress,
string memory sequencerURL,
string memory _networkName
) external;
function admin() external view returns (address);
}
contracts/v2/interfaces/IPolygonPessimisticConsensus.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
interface IPolygonPessimisticConsensus {
function getConsensusHash() external view returns (bytes32);
}
contracts/v2/interfaces/IPolygonRollupBase.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
import "./IPolygonConsensusBase.sol";
interface IPolygonRollupBase is IPolygonConsensusBase {
function onVerifyBatches(
uint64 lastVerifiedBatch,
bytes32 newStateRoot,
address aggregator
) external;
function rollbackBatches(
uint64 targetBatch,
bytes32 accInputHashToRollback
) external;
}
contracts/v2/interfaces/IPolygonRollupManager.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
import "../../interfaces/IVerifierRollup.sol";
import "./IPolygonRollupBase.sol";
import {ITransparentUpgradeableProxy} from "@openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol";
interface IPolygonRollupManager {
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error UpdateToSameRollupTypeID();
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error RollupMustExist();
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error SenderMustBeRollup();
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error TrustedAggregatorTimeoutNotExpired();
/**
* @dev Thrown when sender is not the PolygonZkEVM address
*/
error ExceedMaxVerifyBatches();
/**
* @dev Thrown when attempting to access a pending state that does not exist
*/
error PendingStateDoesNotExist();
/**
* @dev Thrown when the init num batch does not match with the one in the pending state
*/
error InitNumBatchDoesNotMatchPendingState();
/**
* @dev Thrown when the old state root of a certain batch does not exist
*/
error OldStateRootDoesNotExist();
/**
* @dev Thrown when the init verification batch is above the last verification batch
*/
error InitNumBatchAboveLastVerifiedBatch();
/**
* @dev Thrown when the final verification batch is below or equal the last verification batch
*/
error FinalNumBatchBelowLastVerifiedBatch();
/**
* @dev Thrown when the zkproof is not valid
*/
error InvalidProof();
/**
* @dev Thrown when attempting to consolidate a pending state not yet consolidable
*/
error PendingStateNotConsolidable();
/**
* @dev Thrown when attempting to consolidate a pending state that is already consolidated or does not exist
*/
error PendingStateInvalid();
/**
* @dev Thrown when the new accumulate input hash does not exist
*/
error NewAccInputHashDoesNotExist();
/**
* @dev Thrown when the new state root is not inside prime
*/
error NewStateRootNotInsidePrime();
/**
* @dev Thrown when the final pending state num is not in a valid range
*/
error FinalPendingStateNumInvalid();
/**
* @dev Thrown when the final num batch does not match with the one in the pending state
*/
error FinalNumBatchDoesNotMatchPendingState();
/**
* @dev Thrown when the stored root matches the new root proving a different state
*/
error StoredRootMustBeDifferentThanNewRoot();
/**
* @dev Thrown when the halt timeout is not expired when attempting to activate the emergency state
*/
error HaltTimeoutNotExpired();
/**
* @dev Thrown when the old accumulate input hash does not exist
*/
error OldAccInputHashDoesNotExist();
/**
* @dev Thrown when attempting to set a new trusted aggregator timeout equal or bigger than current one
*/
error NewTrustedAggregatorTimeoutMustBeLower();
/**
* @dev Thrown when attempting to set a new pending state timeout equal or bigger than current one
*/
error NewPendingStateTimeoutMustBeLower();
/**
* @dev Thrown when attempting to set a new multiplier batch fee in a invalid range of values
*/
error InvalidRangeMultiplierBatchFee();
/**
* @dev Thrown when attempting to set a batch time target in an invalid range of values
*/
error InvalidRangeBatchTimeTarget();
/**
* @dev Thrown when the caller is not the pending admin
*/
error ChainIDAlreadyExist();
/**
* @dev Thrown when the caller is not the pending admin
*/
error MustSequenceSomeBatch();
/**
* @dev When a rollup type does not exist
*/
error RollupTypeDoesNotExist();
/**
* @dev When a rollup type does not exist
*/
error RollupTypeObsolete();
/**
* @dev When a rollup type does not exist
*/
error InitBatchMustMatchCurrentForkID();
/**
* @dev When a rollup type does not exist
*/
error UpdateNotCompatible();
/**
* @dev When a rollup type does not exist
*/
error BatchFeeOutOfRange();
/**
* @dev When a rollup type does not exist
*/
error AllzkEVMSequencedBatchesMustBeVerified();
/**
* @dev When adding an existing rollup where the rollup address already was added
*/
error RollupAddressAlreadyExist();
/**
* @dev When verifying proof for multiple roolups and they are not ordered by ID
*/
error RollupIDNotAscendingOrder();
/**
* @dev When try to create a new rollup and set a chainID bigger than 32 bits
*/
error ChainIDOutOfRange();
/**
* @dev When try to upgrade a rollup a sender that's not the admin of the rollup
*/
error OnlyRollupAdmin();
/**
* @dev When try to update a rollup with sequences pending to verify
*/
error AllSequencedMustBeVerified();
/**
* @dev Thrown when do not sequence any blob
*/
error MustSequenceSomeBlob();
/**
* @dev Thrown when the final verification sequence is below or equal the last verification sequence
*/
error FinalNumSequenceBelowLastVerifiedSequence();
/**
* @dev When the init sequence was verified in another forkID
*/
error InitSequenceMustMatchCurrentForkID();
/**
* @dev Thrown when the init num sequence does not match with the one in the pending state
*/
error InitSequenceNumDoesNotMatchPendingState();
/**
* @dev Thrown when the final num sequence does not match with the one in the pending state
*/
error FinalNumSequenceDoesNotMatchPendingState();
/**
* @dev Thrown when attempting to set a new multiplier zkgas in a invalid range of values
*/
error InvalidRangeMultiplierZkGasPrice();
/**
* @dev Thrown when attempting to set a seuqnece time target in an invalid range of values
*/
error InvalidRangeSequenceTimeTarget();
/**
* @dev When a set a zkgasprice out of range
*/
error zkGasPriceOfRange();
/**
* @dev Cannot update from network admin with unconsolidated pending state
*/
error CannotUpdateWithUnconsolidatedPendingState();
/**
* @dev Try to verify batches without any sequence data
*/
error EmptyVerifySequencesData();
/**
* @dev Update to old rollup ID
*/
error UpdateToOldRollupTypeID();
/**
* @dev All batches must be verified before the upgrade
*/
error AllBatchesMustBeVerified();
/**
* @dev Rollback batch is not sequenced
*/
error RollbackBatchIsNotValid();
/**
* @dev Rollback batch is not the end of any sequence
*/
error RollbackBatchIsNotEndOfSequence();
/**
* @dev rollbackBatches is called from a non authorized address
*/
error NotAllowedAddress();
/**
* @dev Invalid Rollup type parameters
*/
error InvalidRollupType();
/**
* @dev Invalid Rollup parameters
*/
error InvalidRollup();
/**
* @dev Not valid L1 info tree leaf count
*/
error L1InfoTreeLeafCountInvalid();
/**
* @dev Only State Transition Chains
*/
error OnlyStateTransitionChains();
/**
* @dev Pending state num exist
*/
error PendingStateNumExist();
/**
* @dev Thrown when a function is executed for a State transition chains when it is not allowed
* @dev This function was previously called `OnlyChainsWithPessimisticProofs`but with the new ALGateway verifier Type
* state transitions must be excluded
*/
error StateTransitionChainsNotAllowed();
/**
* @dev Custom chain data must be zero for pessimistic verifier type
*/
error AggchainDataMustBeZeroForPessimisticVerifierType();
/**
* @dev Invalid Pessimistic proof
*/
error InvalidPessimisticProof();
/**
* @dev Invalid Verifier Type when getting rollup data
*/
error InvalidVerifierType();
/**
* @dev Thrown when trying to deploy rollup Manager with some zero address as the input
*/
error InvalidConstructorInputs();
/**
* @dev Thrown when trying to create a rollup but the input parameters are not according with the chosen rollupType
*/
error InvalidInputsForRollupType();
/**
* @dev Thrown when trying to add an existing rollup or create a new rollup type with an invalid consensus implementation address
*/
error InvalidImplementationAddress();
/**
* @dev Thrown when trying to create rollup or rollup type with an invalid verifier address
*/
error InvalidVerifierAddress();
enum VerifierType {
StateTransition,
Pessimistic,
ALGateway
}
function addNewRollupType(
address consensusImplementation,
address verifier,
uint64 forkID,
VerifierType rollupVerifierType,
bytes32 initRoot,
string memory description,
bytes32 programVKey
) external;
function obsoleteRollupType(uint32 rollupTypeID) external;
function attachAggchainToAL(
uint32 rollupTypeID,
uint64 chainID,
bytes memory initializeBytesAggchain
) external;
function addExistingRollup(
address rollupAddress,
address verifier,
uint64 forkID,
uint64 chainID,
bytes32 initRoot,
VerifierType rollupVerifierType,
bytes32 programVKey,
bytes32 initPessimisticRoot
) external;
function updateRollupByRollupAdmin(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID
) external;
function updateRollup(
ITransparentUpgradeableProxy rollupContract,
uint32 newRollupTypeID,
bytes memory upgradeData
) external;
function rollbackBatches(
IPolygonRollupBase rollupContract,
uint64 targetBatch
) external;
function onSequenceBatches(
uint64 newSequencedBatches,
bytes32 newAccInputHash
) external returns (uint64);
function verifyBatchesTrustedAggregator(
uint32 rollupID,
uint64 pendingStateNum,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 newStateRoot,
address beneficiary,
bytes32[24] calldata proof
) external;
function verifyPessimisticTrustedAggregator(
uint32 rollupID,
uint32 l1InfoTreeLeafCount,
bytes32 newLocalExitRoot,
bytes32 newPessimisticRoot,
bytes calldata proof,
bytes memory aggchainData
) external;
function activateEmergencyState() external;
function deactivateEmergencyState() external;
function setBatchFee(uint256 newBatchFee) external;
function getRollupExitRoot() external view returns (bytes32);
function getLastVerifiedBatch(
uint32 rollupID
) external view returns (uint64);
function calculateRewardPerBatch() external view returns (uint256);
function getBatchFee() external view returns (uint256);
function getForcedBatchFee() external view returns (uint256);
function getInputPessimisticBytes(
uint32 rollupID,
bytes32 selectedGlobalExitRoot,
bytes32 newLocalExitRoot,
bytes32 newPessimisticRoot,
bytes memory aggchainData
) external view returns (bytes memory);
function getInputSnarkBytes(
uint32 rollupID,
uint64 initNumBatch,
uint64 finalNewBatch,
bytes32 newLocalExitRoot,
bytes32 oldStateRoot,
bytes32 newStateRoot
) external view returns (bytes memory);
function getRollupBatchNumToStateRoot(
uint32 rollupID,
uint64 batchNum
) external view returns (bytes32);
function lastDeactivatedEmergencyStateTimestamp()
external
view
returns (uint64);
}
contracts/v2/interfaces/IPolygonZkEVMGlobalExitRootV2.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
import "../../interfaces/IBasePolygonZkEVMGlobalExitRoot.sol";
interface IPolygonZkEVMGlobalExitRootV2 is IBasePolygonZkEVMGlobalExitRoot {
function getLastGlobalExitRoot() external view returns (bytes32);
function getRoot() external view returns (bytes32);
function l1InfoRootMap(uint32 depositCount) external view returns (bytes32);
}
contracts/v2/interfaces/ISP1Verifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// imported from: https://github.com/succinctlabs/sp1-contracts/blob/main/contracts/src/ISP1Verifier.sol
/// @title SP1 Verifier Interface
/// @author Succinct Labs
/// @notice This contract is the interface for the SP1 Verifier.
interface ISP1Verifier {
/// @notice Verifies a proof with given public values and vkey.
/// @dev It is expected that the first 4 bytes of proofBytes must match the first 4 bytes of
/// target verifier's VERIFIER_HASH.
/// @param programVKey The verification key for the RISC-V program.
/// @param publicValues The public values encoded as bytes.
/// @param proofBytes The proof of the program execution the SP1 zkVM encoded as bytes.
function verifyProof(
bytes32 programVKey,
bytes calldata publicValues,
bytes calldata proofBytes
) external view;
}
interface ISP1VerifierWithHash is ISP1Verifier {
/// @notice Returns the hash of the verifier.
function VERIFIER_HASH() external pure returns (bytes32);
}
contracts/v2/lib/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
* @notice This code is a copy from OpenZeppelin Contracts v5.1.0 (utils/cryptography/Hashes.sol) with a minor change:
* function visibility is modified from 'private' to 'internal' so it can be used in other contracts.
* @notice OpenZeppelin already did this change: https://github.com/OpenZeppelin/openzeppelin-contracts/commit/441dc141ac99622de7e535fa75dfc74af939019c
* to be included in next version of OpenZeppelin Contracts.
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(
bytes32 a,
bytes32 b
) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
contracts/v2/lib/LegacyZKEVMStateVariables.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
/**
* Since the current contract of PolygonZkEVM will be upgraded to a PolygonRollupManager there's defined
* all the legacy public variables in order to not use previous used storage slots
* The variables will be used by the RollupManager only for initialize the zkEVM inside the initializer function
*/
contract LegacyZKEVMStateVariables {
/**
* @notice Struct which will be stored for every batch sequence
* @param accInputHash Hash chain that contains all the information to process a batch:
* Before etrog: keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 globalExitRoot, uint64 timestamp, address seqAddress)
* Etrog: keccak256(bytes32 oldAccInputHash, keccak256(bytes transactions), bytes32 l1InfoRoot/forcedGlobalExitRoot, uint64 currentTimestamp/forcedTimestamp, address l2Coinbase, bytes32 0/forcedBlockHashL1)
* @param sequencedTimestamp Sequenced timestamp
* @param previousLastBatchSequenced Previous last batch sequenced before the current one, this is used to properly calculate the fees
*/
struct SequencedBatchData {
bytes32 accInputHash;
uint64 sequencedTimestamp;
uint64 previousLastBatchSequenced;
}
/**
* @notice Struct to store the pending states
* Pending state will be an intermediary state, that after a timeout can be consolidated, which means that will be added
* to the state root mapping, and the global exit root will be updated
* This is a protection mechanism against soundness attacks, that will be turned off in the future
* @param timestamp Timestamp where the pending state is added to the queue
* @param lastVerifiedBatch Last batch verified batch of this pending state
* @param exitRoot Pending exit root
* @param stateRoot Pending state root
*/
struct PendingState {
uint64 timestamp;
uint64 lastVerifiedBatch;
bytes32 exitRoot;
bytes32 stateRoot;
}
// Time target of the verification of a batch
// Adaptatly the batchFee will be updated to achieve this target
/// @custom:oz-renamed-from verifyBatchTimeTarget
uint64 internal _legacyVerifyBatchTimeTarget;
// Batch fee multiplier with 3 decimals that goes from 1000 - 1023
/// @custom:oz-renamed-from multiplierBatchFee
uint16 internal _legacyMultiplierBatchFee;
// Trusted sequencer address
/// @custom:oz-renamed-from trustedSequencer
address internal _legacyTrustedSequencer;
// Current matic fee per batch sequenced
/// @custom:oz-renamed-from batchFee
uint256 internal _legacyBatchFee;
// Queue of forced batches with their associated data
// ForceBatchNum --> hashedForcedBatchData
// hashedForcedBatchData: hash containing the necessary information to force a batch:
// keccak256(keccak256(bytes transactions), bytes32 globalExitRoot, unint64 minForcedTimestamp)
/// @custom:oz-renamed-from forcedBatches
mapping(uint64 => bytes32) internal _legacyForcedBatches;
// Queue of batches that defines the virtual state
// SequenceBatchNum --> SequencedBatchData
/// @custom:oz-renamed-from sequencedBatches
mapping(uint64 => SequencedBatchData) internal _legacySequencedBatches;
// Last sequenced timestamp
/// @custom:oz-renamed-from lastTimestamp
uint64 internal _legacyLastTimestamp;
// Last batch sent by the sequencers
/// @custom:oz-renamed-from lastBatchSequenced
uint64 internal _legacylastBatchSequenced;
// Last forced batch included in the sequence
/// @custom:oz-renamed-from lastForceBatchSequenced
uint64 internal _legacyLastForceBatchSequenced;
// Last forced batch
/// @custom:oz-renamed-from lastForceBatch
uint64 internal _legacyLastForceBatch;
// Last batch verified by the aggregators
/// @custom:oz-renamed-from lastVerifiedBatch
uint64 internal _legacyLastVerifiedBatch;
// Trusted aggregator address
/// @custom:oz-renamed-from trustedAggregator
address internal _legacyTrustedAggregator;
// State root mapping
// BatchNum --> state root
/// @custom:oz-renamed-from batchNumToStateRoot
mapping(uint64 => bytes32) internal _legacyBatchNumToStateRoot;
// Trusted sequencer URL
/// @custom:oz-renamed-from trustedSequencerURL
string internal _legacyTrustedSequencerURL;
// L2 network name
/// @custom:oz-renamed-from networkName
string internal _legacyNetworkName;
// Pending state mapping
// pendingStateNumber --> PendingState
/// @custom:oz-renamed-from pendingStateTransitions
mapping(uint256 => PendingState) internal _legacyPendingStateTransitions;
// Last pending state
/// @custom:oz-renamed-from lastPendingState
uint64 internal _legacyLastPendingState;
// Last pending state consolidated
/// @custom:oz-renamed-from lastPendingStateConsolidated
uint64 internal _legacyLastPendingStateConsolidated;
// Once a pending state exceeds this timeout it can be consolidated
/// @custom:oz-renamed-from pendingStateTimeout
uint64 internal _legacyPendingStateTimeout;
// Trusted aggregator timeout, if a sequence is not verified in this time frame,
// everyone can verify that sequence
/// @custom:oz-renamed-from trustedAggregatorTimeout
uint64 internal _legacyTrustedAggregatorTimeout;
// Address that will be able to adjust contract parameters or stop the emergency state
/// @custom:oz-renamed-from admin
address internal _legacyAdmin;
// This account will be able to accept the admin role
/// @custom:oz-renamed-from pendingAdmin
address internal _legacyPendingAdmin;
// Force batch timeout
/// @custom:oz-renamed-from forceBatchTimeout
uint64 internal _legacyForceBatchTimeout;
// Indicates if forced batches are disallowed
/// @custom:oz-renamed-from isForcedBatchDisallowed
bool internal _legacyIsForcedBatchDisallowed;
// Indicates the current version
/// @custom:oz-renamed-from version
uint256 internal _legacyVersion;
// Last batch verified before the last upgrade
/// @custom:oz-renamed-from lastVerifiedBatchBeforeUpgrade
uint256 internal _legacyLastVerifiedBatchBeforeUpgrade;
}
contracts/v2/lib/PolygonAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable4/access/IAccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable4/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable4/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable4/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable4/proxy/utils/Initializable.sol";
/**
* @dev Contract AccessControlUpgradeable from Openzeppelin with the following modifications:
* - Delete ERC165Upgradeable dependencies, which is not important to our contract and save us the "gap"
* variables and let us have consistent storage
* - Add the legacy Owner variable, to be consistent with the previous one
* - Add custom errors
* - Replace _msgSender() with msg.sender
*/
abstract contract PolygonAccessControlUpgradeable is
Initializable,
ContextUpgradeable,
IAccessControlUpgradeable
{
function __AccessControl_init() internal onlyInitializing {}
// Legacy variable
/// @custom:oz-renamed-from _owner
address internal _legacyOwner;
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Thrown when the addres does not have the required role
*/
error AddressDoNotHaveRequiredRole();
/**
* @dev Thrown when the renounce address is not the message sender
*/
error AccessControlOnlyCanRenounceRolesForSelf();
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(
bytes32 role,
address account
) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `msg.sender` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, msg.sender);
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AddressDoNotHaveRequiredRole();
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(
bytes32 role
) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(
bytes32 role,
address account
) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(
bytes32 role,
address account
) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(
bytes32 role,
address account
) public virtual override {
if (account != msg.sender) {
revert AccessControlOnlyCanRenounceRolesForSelf();
}
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[48] private __gap;
}
contracts/v2/lib/PolygonConstantsBase.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.20;
/**
* This contract will contain the constants used across different contracts
*/
contract PolygonConstantsBase {
// If the system a does not verify a batch inside this time window, the contract enters in emergency mode
uint64 internal constant _HALT_AGGREGATION_TIMEOUT = 1 weeks;
// Maximum batches that can be verified in one call. It depends on our current metrics
// This should be a protection against someone that tries to generate huge chunk of invalid batches, and we can't prove otherwise before the pending timeout expires
uint64 internal constant _MAX_VERIFY_BATCHES = 1000;
}
contracts/v2/lib/PolygonTransparentProxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.20;
import {ERC1967Utils} from "@openzeppelin/contracts5/proxy/ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts5/proxy/ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "@openzeppelin/contracts5/interfaces/IERC1967.sol";
import {ProxyAdmin} from "@openzeppelin/contracts5/proxy/transparent/ProxyAdmin.sol";
import {ITransparentUpgradeableProxy} from "@openzeppelin/contracts5/proxy/transparent/TransparentUpgradeableProxy.sol";
/**
* @dev Contract TransparentUpgradeableProxy from Openzeppelin v5 with the following modifications:
* - Admin is a parameter in the constructor ( like previous versions) instead of being deployed
* - Let the admin get access to the proxy
* - Replace _msgSender() with msg.sender
*/
contract PolygonTransparentProxy is ERC1967Proxy {
// An immutable address for the admin to avoid unnecessary SLOADs before each call
// at the expense of removing the ability to change the admin once it's set.
// This is acceptable if the admin is always a ProxyAdmin instance or similar contract
// with its own ability to transfer the permissions to another account.
address private immutable _admin;
/**
* @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
* backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
* {ERC1967Proxy-constructor}.
*/
constructor(
address _logic,
address admin,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
_admin = admin;
// Set the storage value and emit an event for ERC-1967 compatibility
ERC1967Utils.changeAdmin(_proxyAdmin());
}
/**
* @dev Returns the admin of this proxy.
*/
function _proxyAdmin() internal virtual returns (address) {
return _admin;
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
*/
function _fallback() internal virtual override {
if (msg.sender == _proxyAdmin()) {
if (
msg.sig !=
ITransparentUpgradeableProxy.upgradeToAndCall.selector
) {
super._fallback();
} else {
_dispatchUpgradeToAndCall();
}
} else {
super._fallback();
}
}
/**
* @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(
msg.data[4:],
(address, bytes)
);
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
}
Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 500,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.