Verified contractPartialBUSL-1.1
KalqiX
Address0xf10744b51bcbf948aaba852f6bf7a86cb09ceaba
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 2,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,225,609
- Creation transaction
- 0xc39fdee959…4feced4cb6
10 files
- project/contracts/KalqiX.solmain16.81 KB
- npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol9.28 KB
- npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol1.19 KB
- npm/@openzeppelin/[email protected]/access/IAccessControl.sol3.34 KB
- project/contracts/interfaces/IKalqiX.sol2.65 KB
- project/contracts/interfaces/IKalqiXBridge.sol6.41 KB
- project/contracts/interfaces/IKalqiXVerifier.sol2.05 KB
- project/contracts/lib/EmergencyManager.sol1.88 KB
- project/contracts/lib/KalqiXAccessControlUpgradeable.sol7.35 KB
- project/contracts/lib/KalqiXStorage.sol748 B
project/contracts/KalqiX.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
import "./interfaces/IKalqiX.sol";
import "./lib/KalqiXAccessControlUpgradeable.sol";
import "./lib/EmergencyManager.sol";
import "./lib/KalqiXStorage.sol";
import "./interfaces/IKalqiXVerifier.sol";
import "./interfaces/IKalqiXBridge.sol";
/**
* Contract responsible for managing the exit roots across multiple Rollups
*/
contract KalqiX is KalqiXAccessControlUpgradeable, EmergencyManager, IKalqiX {
using KalqiXStorage for KalqiXStorage.Layout;
bytes32 public constant _GENESIS_GLOBAL_EXIT_ROOT = bytes32(0x27ae5ba08d7291c96c8cbddcc148bf48a6d68c7974b94356f53754ef6171d757);
bytes32 public constant _GENESIS_PRIORITY_EXIT_ROOT = bytes32(0x27ae5ba08d7291c96c8cbddcc148bf48a6d68c7974b94356f53754ef6171d757);
// Root of a deposits/priority-exit tree with zero leaves (keccak zero-hash
// chain at depth 32; same value as the genesis roots above). Needed because
// the bridge never writes depositVsRoot[0] — a claimed count of 0 maps to
// this constant instead of a bridge lookup.
bytes32 public constant _EMPTY_TREE_ROOT = bytes32(0x27ae5ba08d7291c96c8cbddcc148bf48a6d68c7974b94356f53754ef6171d757);
bytes32 public constant _GENESIS_ACCOUNT_ROOT = bytes32(0x321b01bebc99e1abeb1fd25ac372bfd4add1d36f7821f6639caf53d09b6475f0);
// Role that has priority to verify batches, also consolidates the state instantly
bytes32 public constant _TRUSTED_BATCHER_ROLE =
keccak256("TRUSTED_BATCHER_ROLE");
// Role to Set the Trusted aggregator
bytes32 public constant _TRUSTED_BATCHER_ROLE_ADMIN =
keccak256("TRUSTED_BATCHER_ROLE_ADMIN");
// Trusted aggregator will be able to verify batches without extra delay
bytes32 public constant _EMERGENCY_COUNCIL_ROLE =
keccak256("EMERGENCY_COUNCIL_ROLE");
// Will be able to update the emergency council
bytes32 public constant _EMERGENCY_COUNCIL_ADMIN =
keccak256("EMERGENCY_COUNCIL_ADMIN");
// If a new block verification exceeds this timeout without being verified, the contract enters in emergency mode
uint64 public constant _HALT_VERIFICATION_TIMEOUT = 2 weeks;
//Max amount of time in which priority request should be proceesed. After time expires no new proofs can be submitted
//without first processing the priority exits
uint64 public constant MAX_PRIORITY_EXIT_PROCESSING_TIME = 2 days;
/**
* @param trustedBatcher Trusted batcher address
* @param emergencyCouncil Emergency council address
* @param admin Admin of the rollup
*/
function initialize(
address _bridge,
address _verifier,
address trustedBatcher,
address emergencyCouncil,
address admin
) external initializer {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
if(_bridge == address(0)) {
revert InvalidAddress();
}
if(_verifier == address(0)) {
revert InvalidAddress();
}
if(trustedBatcher == address(0)) {
revert InvalidAddress();
}
if(emergencyCouncil == address(0)) {
revert InvalidAddress();
}
if(admin == address(0)) {
revert InvalidAddress();
}
s.bridge = _bridge;
s.verifier = _verifier;
s.outputRoots[s.totalVerifiedProofs] = KalqiXStorage.OutputRoots(
{
startBlock: 0,
endBlock: 0,
timestamp: uint128(block.timestamp),
globalExitRoot: _GENESIS_GLOBAL_EXIT_ROOT,
accountRoot: _GENESIS_ACCOUNT_ROOT,
// depositVsRoot(0) is an unwritten slot (bytes32(0)); count 0
// consistently maps to the empty tree root everywhere else.
depositRoot: _EMPTY_TREE_ROOT,
priorityExitRoot: _GENESIS_PRIORITY_EXIT_ROOT
});
// Initialize OZ contracts
__AccessControl_init();
// setup roles
// trusted aggregator role
_setupRole(_TRUSTED_BATCHER_ROLE, trustedBatcher);
// admin roles
_setupRole(DEFAULT_ADMIN_ROLE, admin);
// admin should be able to update the timelock address
_setRoleAdmin(_TRUSTED_BATCHER_ROLE, _TRUSTED_BATCHER_ROLE_ADMIN);
_setupRole(_TRUSTED_BATCHER_ROLE_ADMIN, admin);
// Emergency council roles
_setRoleAdmin(_EMERGENCY_COUNCIL_ROLE, _EMERGENCY_COUNCIL_ADMIN);
_setupRole(_EMERGENCY_COUNCIL_ROLE, emergencyCouncil);
_setupRole(_EMERGENCY_COUNCIL_ADMIN, emergencyCouncil);
}
/**
* @notice Function to verify the given block. Every configured chain receives
* every aggregation proof with the same `_networkRoots` array; each chain
* validates only its own network's entry against its local bridge state —
* the other entries are bound by the proof and validated on their home chains.
* Proofs must be applied in order (start block continuity), so a lagging
* chain catches up by replaying the backlog; it can never skip a proof.
* @param _startBlock Start block of the ranges to be proven
* @param _endBlock Last block of the ranges to be proven
* @param _globalExitRoot Merkle root of the global exit tree
* @param _accountRoot Merkle root of the users account Merkle tree
* @param _networkRoots Per-network deposit/priority-exit roots committed by the proof
* @param _depositCount This chain's last deposit number processed in this proof
* @param _processedPriorityExitCount This chain's last priority exit number processed in this proof
* @param proof Proof containing public values
*/
function verifyBlock(
uint256 _startBlock,
uint256 _endBlock,
bytes32 _globalExitRoot,
bytes32 _accountRoot,
IKalqiXVerifier.NetworkRoots[] calldata _networkRoots,
IKalqiXVerifier.AssetActivation[] calldata _assetActivations,
uint32 _depositCount,
uint32 _processedPriorityExitCount,
bytes calldata proof
) external ifNotEmergencyState onlyRole(_TRUSTED_BATCHER_ROLE) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
if (_startBlock != latestBlockNumber() + 1) {
revert InvalidStartBlock();
}
if (_startBlock > _endBlock) {
revert StartBlockGreaterThanEndBlock();
}
if (_depositCount > IKalqiXBridge(s.bridge).depositCount()) {
revert InvalidDepositCount();
}
if (_processedPriorityExitCount > IKalqiXBridge(s.bridge).priorityExitCount()) {
revert InvalidProcessedPriorityExitCount();
}
// Validate this chain's committed entry against the local bridge state.
(bytes32 depositRoot, bytes32 priorityExitRoot) = _validateNetworkRoots(
s,
_networkRoots,
_depositCount,
_processedPriorityExitCount
);
if (IKalqiXBridge(s.bridge).priorityExitCount() > _processedPriorityExitCount) {
(, , , uint256 requestedAt) = IKalqiXBridge(s.bridge).priorityExits(_processedPriorityExitCount + 1);
if (block.timestamp > (uint64(requestedAt) + MAX_PRIORITY_EXIT_PROCESSING_TIME)) {
revert UnprocessedPriorityExitsWithTimeLimitReached();
}
}
// outputRoots[0] is seeded at initialize (or via setGenesisState on a
// chain joining an existing deployment), so the old roots always come
// from storage — no genesis special case.
IKalqiXVerifier(s.verifier).verify(
_startBlock,
_endBlock,
_globalExitRoot,
_accountRoot,
s.outputRoots[s.totalVerifiedProofs].globalExitRoot,
s.outputRoots[s.totalVerifiedProofs].accountRoot,
_networkRoots,
_assetActivations,
proof
);
s.totalVerifiedProofs = s.totalVerifiedProofs + 1;
IKalqiXBridge(s.bridge).updateLastVerifiedDepositNumber(_depositCount);
IKalqiXBridge(s.bridge).updateProcessedPriorityExits(_processedPriorityExitCount);
_activateAssets(s, _assetActivations);
emit BlockVerified(
_startBlock,
_endBlock,
s.totalVerifiedProofs,
block.timestamp
);
// Storage keeps only this chain's own slice; other networks' roots live
// on their home chains.
s.outputRoots[s.totalVerifiedProofs] = KalqiXStorage.OutputRoots(
{
startBlock: _startBlock,
endBlock: _endBlock,
timestamp: uint128(block.timestamp),
globalExitRoot: _globalExitRoot,
accountRoot: _accountRoot,
depositRoot: depositRoot,
priorityExitRoot: priorityExitRoot
});
}
/**
* @notice Activate this chain's entries from the proof's committed asset
* activations. The circuit only commits an activation after checking the
* asset is registered on the claimed chain and on no other chain, so a
* bridge-side mismatch reverts the whole proof (divergence must halt
* loudly). Entries for other networks are consumed on their home chains.
*/
function _activateAssets(
KalqiXStorage.Layout storage s,
IKalqiXVerifier.AssetActivation[] calldata _assetActivations
) internal {
uint32 myNetworkId = IKalqiXBridge(s.bridge).networkID();
for (uint256 i = 0; i < _assetActivations.length; i++) {
if (_assetActivations[i].networkId == myNetworkId) {
IKalqiXBridge(s.bridge).activateAsset(
_assetActivations[i].assetId,
_assetActivations[i].token
);
}
}
}
/**
* @notice Locate this chain's entry in the proof's per-network commitments
* and validate it against the local bridge state. Returns the expected
* (depositRoot, priorityExitRoot) for this chain at the claimed counts.
* A proof may lack this network's entry only before the network's first
* on-circuit activity, i.e. with zero processed counts. The bridge never
* writes depositVsRoot[0], so count 0 maps to the empty tree root.
*/
function _validateNetworkRoots(
KalqiXStorage.Layout storage s,
IKalqiXVerifier.NetworkRoots[] calldata _networkRoots,
uint32 _depositCount,
uint32 _processedPriorityExitCount
) internal view returns (bytes32 depositRoot, bytes32 priorityExitRoot) {
uint32 myNetworkId = IKalqiXBridge(s.bridge).networkID();
bytes32 committedDepositRoot;
bytes32 committedPriorityExitRoot;
bool found = false;
for (uint256 i = 0; i < _networkRoots.length; i++) {
if (_networkRoots[i].networkId == myNetworkId) {
committedDepositRoot = _networkRoots[i].depositRoot;
committedPriorityExitRoot = _networkRoots[i].priorityExitRoot;
found = true;
break;
}
}
if (!found && (_depositCount != 0 || _processedPriorityExitCount != 0)) {
revert NetworkRootsEntryMissing();
}
depositRoot = _depositCount == 0
? _EMPTY_TREE_ROOT
: IKalqiXBridge(s.bridge).depositVsRoot(_depositCount);
if (found && committedDepositRoot != depositRoot) {
revert DepositRootMismatch();
}
priorityExitRoot = _processedPriorityExitCount == 0
? _GENESIS_PRIORITY_EXIT_ROOT
: IKalqiXBridge(s.bridge).priorityExitVsRoot(_processedPriorityExitCount);
if (found && committedPriorityExitRoot != priorityExitRoot) {
revert PriorityExitRootMismatch();
}
}
/**
* @notice Seed the genesis state on a chain that joins an existing
* deployment: its first proof must chain from the deployment's current
* (endBlock, globalExitRoot, accountRoot) rather than from zero. Only
* callable before any proof has been verified.
*/
function setGenesisState(
uint256 _genesisEndBlock,
bytes32 _genesisGlobalExitRoot,
bytes32 _genesisAccountRoot
) external onlyRole(DEFAULT_ADMIN_ROLE) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
if (s.totalVerifiedProofs != 0) {
revert GenesisAlreadySet();
}
s.outputRoots[0] = KalqiXStorage.OutputRoots(
{
startBlock: 0,
endBlock: _genesisEndBlock,
timestamp: uint128(block.timestamp),
globalExitRoot: _genesisGlobalExitRoot,
accountRoot: _genesisAccountRoot,
depositRoot: _EMPTY_TREE_ROOT,
priorityExitRoot: _GENESIS_PRIORITY_EXIT_ROOT
});
emit GenesisStateSet(_genesisEndBlock, _genesisGlobalExitRoot, _genesisAccountRoot);
}
/**
* @notice Function to activate emergency state, which also enables the emergency mode on bridge contract
* Emergency can either be called by the Emergency council(multisig and then governance later on) or
* Emergency can be trigerred by anyone if no proof has been submitted in _HALT_VERIFICATION_TIMEOUT
*/
function activateEmergencyState() ifNotEmergencyState external {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
if (!hasRole(_EMERGENCY_COUNCIL_ROLE, msg.sender)) {
if (
s.outputRoots[s.totalVerifiedProofs].timestamp +
_HALT_VERIFICATION_TIMEOUT >
block.timestamp
) {
revert HaltTimeoutNotExpired();
}
}
// Activate emergency state on Bridge
IKalqiXBridge(s.bridge).activateEmergencyState();
// Activate emergency state on this contract
super._activateEmergencyState();
}
/**
* @notice Function to deactivate emergency state on bridge contract
*/
function deactivateEmergencyState()
external
ifEmergencyState
onlyRole(_EMERGENCY_COUNCIL_ROLE)
{
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
// Deactivate emergency state on bridge
IKalqiXBridge(s.bridge).deactivateEmergencyState();
// Deactivate emergency state on this contract
super._deactivateEmergencyState();
}
//return the latest global exit root
function globalExitRoot() external view override returns (bytes32) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
return s.outputRoots[s.totalVerifiedProofs].globalExitRoot;
}
//Returns the latest account root
function accountRoot() external view override returns (bytes32) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
return s.outputRoots[s.totalVerifiedProofs].accountRoot;
}
//Returns the latest proven block number. Reads outputRoots[0] before the
//first proof, which holds 0 on a fresh deployment or the genesis end block
//set via setGenesisState on a chain joining an existing deployment.
function latestBlockNumber() public view returns (uint256) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
return s.outputRoots[s.totalVerifiedProofs].endBlock;
}
//Allows to change the verifier
function changeVerifier(
address _verifier
) external onlyRole(_EMERGENCY_COUNCIL_ADMIN) {
if (_verifier == address(0)) {
revert InvalidAddress();
}
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
address oldVerifer = s.verifier;
s.verifier = _verifier;
emit VerifierChanged(oldVerifer, _verifier);
}
//return the KalqiX Bridge address
function bridge() override external view returns (address) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
return s.bridge;
}
//return the KalqiX proof verifier contract address
function verifier() override external view returns(address) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
return s.verifier;
}
//returns the output roots at the given index
function outputRoots(uint256 index) external view returns(uint256, uint256, uint128, bytes32, bytes32, bytes32, bytes32) {
KalqiXStorage.Layout storage s = KalqiXStorage.layout();
KalqiXStorage.OutputRoots memory o = s.outputRoots[index];
return (o.startBlock, o.endBlock, o.timestamp, o.globalExitRoot, o.accountRoot, o.depositRoot, o.priorityExitRoot);
}
}
npm/@openzeppelin/[email protected]/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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]
* ```solidity
* 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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
npm/@openzeppelin/[email protected]/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
npm/@openzeppelin/[email protected]/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @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 to signal this.
*/
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. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
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 `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
project/contracts/interfaces/IKalqiX.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.30;
import "./IKalqiXVerifier.sol";
interface IKalqiX {
event BlockVerified(
uint256 indexed startBlock,
uint256 indexed endBlock,
uint256 indexed index,
uint256 timestamp
);
event VerifierChanged(address oldVerifier, address newVerifier);
event GenesisStateSet(
uint256 endBlock,
bytes32 globalExitRoot,
bytes32 accountRoot
);
/**
* @dev Thrown when the zkproof is not valid
*/
error InvalidProof();
/**
* @dev Thrown when new batch number is lower then last verified batch number
*/
error StartBlockGreaterThanEndBlock();
error HaltTimeoutNotExpired();
error UnprocessedPriorityExitsWithTimeLimitReached();
error InvalidAddress();
error InvalidStartBlock();
error InvalidDepositCount();
error InvalidProcessedPriorityExitCount();
/**
* @dev Thrown when the proof's committed deposit root for this network does
* not match the local bridge's deposit tree root at the claimed count
*/
error DepositRootMismatch();
/**
* @dev Thrown when the proof's committed priority exit root for this network
* does not match the local bridge's priority exit tree root at the claimed count
*/
error PriorityExitRootMismatch();
/**
* @dev Thrown when the proof carries no entry for this network but non-zero
* counts were claimed
*/
error NetworkRootsEntryMissing();
/**
* @dev Thrown when setGenesisState is called after proofs have been verified
*/
error GenesisAlreadySet();
function verifyBlock(
uint256 _startBlock,
uint256 _endBlock,
bytes32 _globalExitRoot,
bytes32 _accountRoot,
IKalqiXVerifier.NetworkRoots[] calldata _networkRoots,
IKalqiXVerifier.AssetActivation[] calldata _assetActivations,
uint32 _depositCount,
uint32 _processedPriorityExitCount,
bytes calldata proof
) external;
function setGenesisState(
uint256 _genesisEndBlock,
bytes32 _genesisGlobalExitRoot,
bytes32 _genesisAccountRoot
) external;
function globalExitRoot() external view returns(bytes32);
function accountRoot() external view returns(bytes32);
function latestBlockNumber() external view returns (uint256);
function bridge() external view returns (address);
function verifier() external view returns(address);
function outputRoots(uint256 index) external view returns(uint256, uint256, uint128, bytes32, bytes32, bytes32, bytes32);
}
project/contracts/interfaces/IKalqiXBridge.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.30;
interface IKalqiXBridge {
function bridgeAsset(
address destinationAddress,
uint256 amount,
address token,
bytes calldata permitData
) external payable;
function claimAsset(
bytes32[32] calldata smtProofLocalExitRoot,
bytes32[32] calldata smtProofRollupExitRoot,
uint256 globalIndex,
address tokenAddress,
uint32 destinationNetwork,
address destinationAddress,
uint256 amount
) external;
function activateEmergencyState() external;
function deactivateEmergencyState() external;
function depositVsRoot(uint32 depositNumber) external view returns(bytes32);
function updateLastVerifiedDepositNumber(uint32 depositNumber) external;
function updateProcessedPriorityExits(uint256 _processedPriorityExits) external;
function updatePriorityExitFee(uint256 _priorityExitFee) external;
function networkID() external view returns(uint32);
function assetConfigs(uint32 assetId) external view returns(address, bool, uint256, uint256, uint256, uint16, bool, bool);
function activateAsset(uint32 assetId, address token) external;
function assetIdForToken(address token) external view returns(uint32);
function tokenVsDeposits(address token) external view returns(uint256);
function claimedMap(uint256 index) external view returns(bool);
function tokenVsFeesAccrued(address token) external view returns(uint256);
function kalqiX() external view returns(address);
function depositCount() external view returns(uint256);
function priorityExitCount() external view returns(uint256);
function deposits(uint32 depositNumber) external view returns(address, address, uint256);
function cancelledDeposits(uint32 depositNumber) external view returns(bool);
function lastVerifiedDepositNumber() external view returns(uint256);
function maxUnprocessedPriorityExits() external view returns(uint256);
function processedPriorityExits() external view returns(uint256);
function priorityExits(uint32 priorityExitNumber) external view returns(address, address, uint256, uint256);
function priorityExitVsRoot(uint32 priorityExitNumber) external view returns(bytes32);
function updateMaxUnprocessedPriorityExits(uint256 num) external;
function requestPriorityExit(address token, uint256 amount) external payable;
/**
* @dev Thrown when the Asset is not valid
*/
error InvalidAsset();
/**
* @dev Thrown when the withdrawal fee is more then permissible limit
*/
error InvalidWithdrawalFee();
/**
* @dev Thrown when the value does not match msg.value in case deposit asset is native token
*/
error ValueDoesNotMatchMsgValue();
error TokenMismatch();
error InvalidNetworkId();
error InvalidAddress();
error InvalidPriorityExitDeposit();
error AssetDoesNotMatch();
error InvalidMsgValue();
error PriorityExitNotProcessed();
error PriorityExitDepositAlreadyClaimed();
error FailedToVerifyJMTProof();
error NotValidOwner();
error NotValidSpender();
error NotValidAmount();
error NotValidSignature();
error DepositNotSupportedForToken();
error BreachingMaxDepositAllowed();
error LessThanAllowedMinDepositAmount();
error LessThanAllowedMinWithdrawAmount();
error DestinationNetworkInvalid();
error EtherTransferFailed();
error RollupExitRootInvalid();
error InvalidSmtProof();
error ExitAlreadyclaimed();
error OnlyKalqiX();
error InvalidLocalExitRootProof();
error InvalidRollupExitRootProof();
error AssetAlreadyExists();
/**
* @dev Thrown when a token is already registered under a different asset id
*/
error TokenAlreadyRegistered();
/**
* @dev Thrown when the asset id is not valid (id 0 is the unregistered sentinel)
*/
error InvalidAssetId();
/**
* @dev Thrown on deposit/priority-exit for an asset the zk service has not
* yet attested via an aggregation proof
*/
error AssetNotVerified();
/**
* @dev Thrown when a proof-committed activation does not match this
* bridge's registration for the asset id
*/
error AssetActivationMismatch(uint32 assetId, address token);
/**
* @dev Thrown when the upgrade migration is called by anyone other than
* the proxy admin (i.e. outside ProxyAdmin.upgradeAndCall)
*/
error OnlyProxyAdmin();
error InvalidDepositNumberToUpdate();
error InvalidDespositNumberForCancellation();
error DespositHasAlreadyBeenCancelled();
error PriorityExitNotSupportedForToken();
error LessThanAllowedMinWithdrawalAmount();
error ZeroAmount();
error MaxUnprocessedPriorityExitsReached();
error InvalidProcessedPriorityExitsToUpdate();
error InvalidRollupIndex();
event FeesClaimed(
address indexed token,
uint256 indexed amount,
address indexed receiver,
address sender
);
event AssetActivated(
uint32 indexed assetId,
address indexed asset
);
event AssetUpdated(
uint32 indexed assetId,
address indexed asset,
bool depositOn,
uint256 minDeposit,
uint256 maxDeposit,
uint256 minWithdrawal,
uint16 withdrawalFee,
uint32 networkId
);
event BridgeEvent(
uint32 indexed assetId,
address indexed token,
address indexed destinationAddress,
uint256 amount,
uint32 depositCount
);
event ClaimEvent(
uint256 globalIndex,
address indexed tokenAddress,
address indexed destinationAddress,
uint256 amount
);
event DepositCancelled(
uint32 indexed depositNumber,
address indexed token,
address indexed to,
uint256 amount
);
event PriorityExitRequest(
uint32 indexed priorityExitNumber,
address indexed token,
address indexed to,
uint256 amount
);
event ForcedExit(
address indexed initiator,
address indexed receiver
);
event FailedToTransferEther();
event TokenTransferFailed();
event PriorityExitDepositClaimed(uint32 indexed priorityExitNumber);
}project/contracts/interfaces/IKalqiXVerifier.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.30;
interface IKalqiXVerifier {
/**
* One network's committed tree roots. The array in `AggregationOutputs` is
* sorted strictly ascending by networkId (enforced in-circuit); each chain's
* KalqiX validates only its own entry against its local bridge — the other
* entries are bound by the proof and validated on their home chains.
*/
struct NetworkRoots {
uint32 networkId;
bytes32 depositRoot;
bytes32 priorityExitRoot;
}
/**
* One asset activation committed by the aggregation program after the zk
* service has checked the asset is registered on the claimed chain and on
* no other chain (each asset lives on exactly one chain). Ordering and
* dedup of the array are enforced in-circuit; each chain's KalqiX acts
* only on the entries matching its own networkId — the rest are bound by
* the proof and consumed on their home chains.
*/
struct AssetActivation {
uint32 networkId;
uint32 assetId;
address token;
}
/**
* Public values of the aggregation program. Must ABI-match the Rust-side
* `AggregationOutputs` in kalqix-zk-service `shared/src/types.rs` exactly —
* the verifier re-encodes these bytes to verify the SP1 proof.
*/
struct AggregationOutputs {
uint256 startBlock;
uint256 endBlock;
bytes32 globalExitRoot;
bytes32 accountRoot;
bytes32 oldGlobalExitRoot;
bytes32 oldAccountRoot;
bytes32 rangeVKey;
NetworkRoots[] networkRoots;
AssetActivation[] assetActivations;
}
function verify(
uint256 _startBlock,
uint256 _endBlock,
bytes32 _globalExitRoot,
bytes32 _accountRoot,
bytes32 _oldGlobalExitRoot,
bytes32 _oldAccountRoot,
NetworkRoots[] calldata _networkRoots,
AssetActivation[] calldata _assetActivations,
bytes calldata proof
) external view;
}
project/contracts/lib/EmergencyManager.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.30;
/**
* @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();
// Indicates whether the emergency state is active or not
bool public isEmergencyState;
/**
* @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.
*/
uint256[50] private _gap;
/**
* @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();
}
}
project/contracts/lib/KalqiXAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)
pragma solidity 0.8.30;
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/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 KalqiXAccessControlUpgradeable is
Initializable,
ContextUpgradeable,
IAccessControl
{
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;
}project/contracts/lib/KalqiXStorage.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.30;
library KalqiXStorage {
bytes32 internal constant SLOT = keccak256("kalqix.main.storage");
struct OutputRoots {
uint256 startBlock;
uint256 endBlock;
uint128 timestamp;
bytes32 globalExitRoot;
bytes32 accountRoot;
bytes32 depositRoot;
bytes32 priorityExitRoot;
}
struct Layout {
address bridge;
address verifier;
uint256 totalVerifiedProofs;
//Indexing will start from 1
mapping(uint256 => OutputRoots) outputRoots;
}
function layout() internal pure returns (Layout storage s) {
bytes32 slot = SLOT;
assembly { s.slot := slot }
}
}Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 2000,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts-upgradeable/=npm/@openzeppelin/[email protected]/",
"project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.