DEXStakingIntegration

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "DEXStakingIntegration.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./AccessControlUpgradeable.sol";
import "./CoreRegistry.sol";

contract DEXStakingIntegration is
    Initializable,
    ReentrancyGuardUpgradeable,
    UUPSUpgradeable,
    LaxceAccessControlUpgradeable
{
    using SafeERC20 for IERC20;

    uint256 public constant BASIS_POINTS = 10000;
    uint256 public constant REVENUE_SHARE_PERCENTAGE = 3000;
    uint256 public constant STAKING_SHARE_PERCENTAGE = 7000;

    CoreRegistry public coreRegistry;
    address public dexEngine;
    address public stakingManager;
    address public treasuryAddress;

    uint256 public totalRevenueCollected;
    uint256 public totalDistributedToStaking;
    uint256 public totalDistributedToTreasury;

    event RevenueDistributed(
        uint256 totalRevenue,
        uint256 stakingAmount,
        uint256 treasuryAmount,
        uint256 timestamp
    );

    function initialize(
        address _coreRegistry,
        address _admin
    ) external initializer {
        __ReentrancyGuard_init();
        __UUPSUpgradeable_init();

        SecuritySettings memory securitySettings = SecuritySettings({
            emergencyDelay: 24 hours,
            adminDelay: 1 hours,
            emergencyMode: false,
            lastEmergencyTime: 0
        });

        __LaxceAccessControl_init(_admin, "1.0.0", securitySettings);

        coreRegistry = CoreRegistry(_coreRegistry);
    }

    function distributeRevenue(uint256 amount) external onlyRole(OPERATOR_ROLE) {
        require(amount > 0, "Invalid amount");

        uint256 stakingAmount = (amount * STAKING_SHARE_PERCENTAGE) / BASIS_POINTS;
        uint256 treasuryAmount = amount - stakingAmount;

        totalRevenueCollected += amount;
        totalDistributedToStaking += stakingAmount;
        totalDistributedToTreasury += treasuryAmount;

        emit RevenueDistributed(amount, stakingAmount, treasuryAmount, block.timestamp);
    }

    function setAddresses(
        address _dexEngine,
        address _stakingManager,
        address _treasury
    ) external onlyRole(ADMIN_ROLE) {
        dexEngine = _dexEngine;
        stakingManager = _stakingManager;
        treasuryAddress = _treasury;
    }

    function getStats() external view returns (
        uint256 totalRevenue,
        uint256 stakingDistributed,
        uint256 treasuryDistributed
    ) {
        return (totalRevenueCollected, totalDistributedToStaking, totalDistributedToTreasury);
    }

    function _authorizeUpgrade(address newImplementation)
        internal
        override(UUPSUpgradeable, LaxceAccessControlUpgradeable)
        onlyRole(UPGRADER_ROLE)
    {}
}"
    },
    "CoreRegistry.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./AccessControlUpgradeable.sol";

contract CoreRegistry is Initializable, UUPSUpgradeable, LaxceAccessControlUpgradeable {

    bytes32 public constant DEX_ENGINE = keccak256("DEX_ENGINE");
    bytes32 public constant POOL_FACTORY = keccak256("POOL_FACTORY");
    bytes32 public constant POOL_MANAGER = keccak256("POOL_MANAGER");
    bytes32 public constant TOKEN_REGISTRY = keccak256("TOKEN_REGISTRY");
    bytes32 public constant STAKING_MANAGER = keccak256("STAKING_MANAGER");
    bytes32 public constant STAKING_REWARDS = keccak256("STAKING_REWARDS");
    bytes32 public constant REFERRAL_MANAGER = keccak256("REFERRAL_MANAGER");
    bytes32 public constant ORACLE_MANAGER = keccak256("ORACLE_MANAGER");
    bytes32 public constant PRICE_ORACLE = keccak256("PRICE_ORACLE");
    bytes32 public constant SECURITY_MANAGER = keccak256("SECURITY_MANAGER");
    bytes32 public constant FEE_COLLECTOR = keccak256("FEE_COLLECTOR");
    bytes32 public constant GOVERNANCE = keccak256("GOVERNANCE");
    bytes32 public constant TREASURY = keccak256("TREASURY");
    bytes32 public constant ROUTER = keccak256("ROUTER");
    bytes32 public constant QUOTER = keccak256("QUOTER");

    struct ContractInfo {
        address contractAddress;
        string name;
        string version;
        bool isActive;
        uint256 registeredAt;
        uint256 lastUpdate;
        address registrar;
    }

    struct SystemStats {
        uint256 totalContracts;
        uint256 activeContracts;
        uint256 lastRegistration;
        uint256 totalUpdates;
    }

    mapping(bytes32 => ContractInfo) public contracts;

    mapping(address => bytes32) public addressToId;

    bytes32[] public allContractIds;

    SystemStats public systemStats;

    mapping(bytes32 => bytes32[]) public contractDependencies;

    mapping(bytes32 => bytes32[]) public dependentContracts;

    mapping(bytes32 => mapping(bytes32 => bool)) public integrationStatus;

    event ContractRegistered(
        bytes32 indexed contractId,
        address indexed contractAddress,
        string name,
        string version,
        address indexed registrar
    );

    event ContractUpdated(
        bytes32 indexed contractId,
        address indexed oldAddress,
        address indexed newAddress,
        string newVersion
    );

    event ContractStatusChanged(
        bytes32 indexed contractId,
        bool isActive,
        address indexed updater
    );

    event DependencyAdded(
        bytes32 indexed contractId,
        bytes32 indexed dependsOn
    );

    event DependencyRemoved(
        bytes32 indexed contractId,
        bytes32 indexed dependsOn
    );

    event IntegrationStatusChanged(
        bytes32 indexed contractA,
        bytes32 indexed contractB,
        bool integrated
    );

    error Registry__ContractAlreadyExists();
    error Registry__ContractNotExists();
    error Registry__InvalidAddress();
    error Registry__AddressAlreadyUsed();
    error Registry__CircularDependency();
    error Registry__DependencyNotMet();

    function initialize(
        address _deployer,
        string memory _version
    ) external initializer {
        SecuritySettings memory settings = SecuritySettings({
            emergencyDelay: 24 hours,
            adminDelay: 1 hours,
            emergencyMode: false,
            lastEmergencyTime: 0
        });

        __LaxceAccessControl_init(_deployer, _version, settings);

        systemStats.lastRegistration = block.timestamp;
    }

    function registerContract(
        bytes32 contractId,
        address contractAddress,
        string calldata name,
        string calldata version
    ) external onlyRole(ADMIN_ROLE) whenNotPaused {
        if (contracts[contractId].contractAddress != address(0)) {
            revert Registry__ContractAlreadyExists();
        }
        if (contractAddress == address(0)) {
            revert Registry__InvalidAddress();
        }
        if (addressToId[contractAddress] != bytes32(0)) {
            revert Registry__AddressAlreadyUsed();
        }

        contracts[contractId] = ContractInfo({
            contractAddress: contractAddress,
            name: name,
            version: version,
            isActive: true,
            registeredAt: block.timestamp,
            lastUpdate: block.timestamp,
            registrar: msg.sender
        });

        addressToId[contractAddress] = contractId;
        allContractIds.push(contractId);

        systemStats.totalContracts++;
        systemStats.activeContracts++;
        systemStats.lastRegistration = block.timestamp;

        emit ContractRegistered(contractId, contractAddress, name, version, msg.sender);
    }

    function updateContract(
        bytes32 contractId,
        address newAddress,
        string calldata newVersion
    ) external onlyRole(ADMIN_ROLE) whenNotPaused {
        ContractInfo storage info = contracts[contractId];
        if (info.contractAddress == address(0)) {
            revert Registry__ContractNotExists();
        }
        if (newAddress == address(0)) {
            revert Registry__InvalidAddress();
        }
        if (addressToId[newAddress] != bytes32(0) && addressToId[newAddress] != contractId) {
            revert Registry__AddressAlreadyUsed();
        }

        address oldAddress = info.contractAddress;

        delete addressToId[oldAddress];

        info.contractAddress = newAddress;
        info.version = newVersion;
        info.lastUpdate = block.timestamp;

        addressToId[newAddress] = contractId;

        systemStats.totalUpdates++;

        emit ContractUpdated(contractId, oldAddress, newAddress, newVersion);
    }

    function setContractStatus(
        bytes32 contractId,
        bool isActive
    ) external onlyRole(ADMIN_ROLE) {
        ContractInfo storage info = contracts[contractId];
        if (info.contractAddress == address(0)) {
            revert Registry__ContractNotExists();
        }

        bool wasActive = info.isActive;
        info.isActive = isActive;
        info.lastUpdate = block.timestamp;

        if (wasActive && !isActive) {
            systemStats.activeContracts--;
        } else if (!wasActive && isActive) {
            systemStats.activeContracts++;
        }

        emit ContractStatusChanged(contractId, isActive, msg.sender);
    }

    function addDependency(
        bytes32 contractId,
        bytes32 dependsOn
    ) external onlyRole(ADMIN_ROLE) {
        if (contracts[contractId].contractAddress == address(0) ||
            contracts[dependsOn].contractAddress == address(0)) {
            revert Registry__ContractNotExists();
        }

        if (_hasCircularDependency(contractId, dependsOn)) {
            revert Registry__CircularDependency();
        }

        contractDependencies[contractId].push(dependsOn);
        dependentContracts[dependsOn].push(contractId);

        emit DependencyAdded(contractId, dependsOn);
    }

    function removeDependency(
        bytes32 contractId,
        bytes32 dependsOn
    ) external onlyRole(ADMIN_ROLE) {
        _removeDependencyFromArray(contractDependencies[contractId], dependsOn);
        _removeDependencyFromArray(dependentContracts[dependsOn], contractId);

        emit DependencyRemoved(contractId, dependsOn);
    }

    function _hasCircularDependency(bytes32 contractId, bytes32 dependsOn) internal view returns (bool) {

        bytes32[] memory deps = contractDependencies[dependsOn];
        for (uint256 i = 0; i < deps.length; i++) {
            if (deps[i] == contractId) {
                return true;
            }

            if (_hasCircularDependency(contractId, deps[i])) {
                return true;
            }
        }
        return false;
    }

    function _removeDependencyFromArray(bytes32[] storage array, bytes32 item) internal {
        for (uint256 i = 0; i < array.length; i++) {
            if (array[i] == item) {
                array[i] = array[array.length - 1];
                array.pop();
                break;
            }
        }
    }

    function setIntegrationStatus(
        bytes32 contractA,
        bytes32 contractB,
        bool integrated
    ) external onlyRole(ADMIN_ROLE) {
        if (contracts[contractA].contractAddress == address(0) ||
            contracts[contractB].contractAddress == address(0)) {
            revert Registry__ContractNotExists();
        }

        integrationStatus[contractA][contractB] = integrated;
        integrationStatus[contractB][contractA] = integrated;

        emit IntegrationStatusChanged(contractA, contractB, integrated);
    }

    function getContract(bytes32 contractId) external view returns (address) {
        return contracts[contractId].contractAddress;
    }

    function getContractInfo(bytes32 contractId) external view returns (ContractInfo memory) {
        return contracts[contractId];
    }

    function getContractId(address contractAddress) external view returns (bytes32) {
        return addressToId[contractAddress];
    }

    function isContractActive(bytes32 contractId) external view returns (bool) {
        return contracts[contractId].isActive;
    }

    function getContractDependencies(bytes32 contractId) external view returns (bytes32[] memory) {
        return contractDependencies[contractId];
    }

    function getDependentContracts(bytes32 contractId) external view returns (bytes32[] memory) {
        return dependentContracts[contractId];
    }

    function areContractsIntegrated(bytes32 contractA, bytes32 contractB) external view returns (bool) {
        return integrationStatus[contractA][contractB];
    }

    function getAllContractIds() external view returns (bytes32[] memory) {
        return allContractIds;
    }

    function getSystemStats() external view returns (SystemStats memory) {
        return systemStats;
    }

    function checkSystemHealth() external view returns (
        bool allCoreContractsActive,
        uint256 totalContracts,
        uint256 activeContracts,
        uint256 inactiveContracts
    ) {

        bytes32[] memory coreContracts = new bytes32[](6);
        coreContracts[0] = DEX_ENGINE;
        coreContracts[1] = POOL_FACTORY;
        coreContracts[2] = TOKEN_REGISTRY;
        coreContracts[3] = STAKING_MANAGER;
        coreContracts[4] = ORACLE_MANAGER;
        coreContracts[5] = SECURITY_MANAGER;

        allCoreContractsActive = true;
        for (uint256 i = 0; i < coreContracts.length; i++) {
            if (!contracts[coreContracts[i]].isActive) {
                allCoreContractsActive = false;
                break;
            }
        }

        totalContracts = systemStats.totalContracts;
        activeContracts = systemStats.activeContracts;
        inactiveContracts = totalContracts - activeContracts;
    }

    function _authorizeUpgrade(address newImplementation)
        internal
        override(UUPSUpgradeable, LaxceAccessControlUpgradeable)
        onlyRole(UPGRADER_ROLE)
    {}
}
"
    },
    "AccessControlUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

contract LaxceAccessControlUpgradeable is
    Initializable,
    AccessControlUpgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable,
    UUPSUpgradeable
{

    bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");

    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");

    bytes32 public constant TREASURY_ROLE = keccak256("TREASURY_ROLE");

    bytes32 public constant ORACLE_ROLE = keccak256("ORACLE_ROLE");

    bytes32 public constant POOL_MANAGER_ROLE = keccak256("POOL_MANAGER_ROLE");

    bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");

    bytes32 public constant FEE_MANAGER_ROLE = keccak256("FEE_MANAGER_ROLE");

    bytes32 public constant STAKING_MANAGER_ROLE = keccak256("STAKING_MANAGER_ROLE");

    bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");

    address public deployer;

    uint256 public deploymentTime;

    string public version;

    struct SecuritySettings {
        uint256 emergencyDelay;
        uint256 adminDelay;
        bool emergencyMode;
        uint256 lastEmergencyTime;
    }

    SecuritySettings public securitySettings;

    mapping(bytes32 => address[]) public roleMembers;

    mapping(bytes32 => uint256) public roleMemberCount;

    struct RoleChange {
        bytes32 role;
        address account;
        bool granted;
        uint256 timestamp;
        address admin;
    }

    RoleChange[] public roleChanges;

    mapping(bytes32 => mapping(address => uint256)) public roleTimeRestrictions;

    event SecuritySettingsUpdated(
        uint256 emergencyDelay,
        uint256 adminDelay,
        address indexed updater
    );

    event EmergencyModeToggled(bool enabled, address indexed toggler);

    event RoleGrantedWithTimeRestriction(
        bytes32 indexed role,
        address indexed account,
        address indexed sender,
        uint256 validUntil
    );

    event RoleTimeRestrictionUpdated(
        bytes32 indexed role,
        address indexed account,
        uint256 newValidUntil
    );

    error AccessControl__EmergencyModeActive();
    error AccessControl__TimeRestrictionExpired();
    error AccessControl__InvalidDelay();
    error AccessControl__EmergencyDelayNotMet();
    error AccessControl__AdminDelayNotMet();

    modifier whenNotInEmergency() {
        if (securitySettings.emergencyMode) revert AccessControl__EmergencyModeActive();
        _;
    }

    modifier withTimeRestriction(bytes32 role) {
        uint256 validUntil = roleTimeRestrictions[role][msg.sender];
        if (validUntil > 0 && block.timestamp > validUntil) {
            revert AccessControl__TimeRestrictionExpired();
        }
        _;
    }

    modifier emergencyDelayMet() {
        if (block.timestamp < securitySettings.lastEmergencyTime + securitySettings.emergencyDelay) {
            revert AccessControl__EmergencyDelayNotMet();
        }
        _;
    }

    function __LaxceAccessControl_init(
        address _deployer,
        string memory _version,
        SecuritySettings memory _securitySettings
    ) internal onlyInitializing {
        __AccessControl_init();
        __Pausable_init();
        __ReentrancyGuard_init();
        __UUPSUpgradeable_init();

        deployer = _deployer;
        deploymentTime = block.timestamp;
        version = _version;
        securitySettings = _securitySettings;

        _setupInitialRoles(_deployer);
    }

    function initialize(
        address _deployer,
        string memory _version,
        SecuritySettings memory _securitySettings
    ) external initializer {
        __LaxceAccessControl_init(_deployer, _version, _securitySettings);
    }

    function grantRoleWithTimeRestriction(
        bytes32 role,
        address account,
        uint256 validUntil
    ) external onlyRole(getRoleAdmin(role)) whenNotInEmergency {
        grantRole(role, account);

        if (validUntil > 0) {
            roleTimeRestrictions[role][account] = validUntil;
            emit RoleGrantedWithTimeRestriction(role, account, msg.sender, validUntil);
        }

        _updateRoleMembersList(role, account, true);
    }

    function revokeRole(bytes32 role, address account)
        public
        override
        onlyRole(getRoleAdmin(role))
        whenNotInEmergency
    {
        super.revokeRole(role, account);
        _updateRoleMembersList(role, account, false);

        delete roleTimeRestrictions[role][account];
    }

    function updateRoleTimeRestriction(
        bytes32 role,
        address account,
        uint256 newValidUntil
    ) external onlyRole(getRoleAdmin(role)) {
        require(hasRole(role, account), "Account does not have role");

        roleTimeRestrictions[role][account] = newValidUntil;
        emit RoleTimeRestrictionUpdated(role, account, newValidUntil);
    }

    function _setupInitialRoles(address _deployer) internal {

        _grantRole(DEFAULT_ADMIN_ROLE, _deployer);
        _grantRole(OWNER_ROLE, _deployer);
        _grantRole(ADMIN_ROLE, _deployer);
        _grantRole(UPGRADER_ROLE, _deployer);
        _grantRole(EMERGENCY_ROLE, _deployer);
        _grantRole(PAUSER_ROLE, _deployer);

        _setRoleAdmin(ADMIN_ROLE, OWNER_ROLE);
        _setRoleAdmin(OPERATOR_ROLE, ADMIN_ROLE);
        _setRoleAdmin(TREASURY_ROLE, ADMIN_ROLE);
        _setRoleAdmin(ORACLE_ROLE, ADMIN_ROLE);
        _setRoleAdmin(POOL_MANAGER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(FEE_MANAGER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(STAKING_MANAGER_ROLE, ADMIN_ROLE);
        _setRoleAdmin(GOVERNANCE_ROLE, OWNER_ROLE);
        _setRoleAdmin(PAUSER_ROLE, EMERGENCY_ROLE);
        _setRoleAdmin(UPGRADER_ROLE, OWNER_ROLE);
    }

    function _updateRoleMembersList(bytes32 role, address account, bool granted) internal {
        if (granted) {
            roleMembers[role].push(account);
            roleMemberCount[role]++;
        } else {

            address[] storage members = roleMembers[role];
            for (uint256 i = 0; i < members.length; i++) {
                if (members[i] == account) {
                    members[i] = members[members.length - 1];
                    members.pop();
                    roleMemberCount[role]--;
                    break;
                }
            }
        }

        roleChanges.push(RoleChange({
            role: role,
            account: account,
            granted: granted,
            timestamp: block.timestamp,
            admin: msg.sender
        }));
    }

    function updateSecuritySettings(
        uint256 _emergencyDelay,
        uint256 _adminDelay
    ) external onlyRole(OWNER_ROLE) {
        if (_emergencyDelay < 1 hours || _adminDelay < 30 minutes) {
            revert AccessControl__InvalidDelay();
        }

        securitySettings.emergencyDelay = _emergencyDelay;
        securitySettings.adminDelay = _adminDelay;

        emit SecuritySettingsUpdated(_emergencyDelay, _adminDelay, msg.sender);
    }

    function toggleEmergencyMode() external virtual onlyRole(EMERGENCY_ROLE) emergencyDelayMet {
        securitySettings.emergencyMode = !securitySettings.emergencyMode;
        securitySettings.lastEmergencyTime = block.timestamp;

        emit EmergencyModeToggled(securitySettings.emergencyMode, msg.sender);
    }

    function pause() external onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() external onlyRole(PAUSER_ROLE) {
        _unpause();
    }

    function hasValidRole(bytes32 role, address account) external view returns (bool) {
        if (!hasRole(role, account)) return false;

        uint256 validUntil = roleTimeRestrictions[role][account];
        if (validUntil > 0 && block.timestamp > validUntil) return false;

        return true;
    }

    function getRoleMembers(bytes32 role) external view returns (address[] memory) {
        return roleMembers[role];
    }

    function getRoleMemberCount(bytes32 role) external view returns (uint256) {
        return roleMemberCount[role];
    }

    function getRoleChangesCount() external view returns (uint256) {
        return roleChanges.length;
    }

    function isEmergencyMode() external view returns (bool) {
        return securitySettings.emergencyMode;
    }

    function _authorizeUpgrade(address newImplementation)
        internal
        virtual
        override
        onlyRole(UPGRADER_ROLE)
        whenNotInEmergency
    {}

    function getVersion() external view returns (string memory) {
        return version;
    }

    function updateVersion(string memory _newVersion) external onlyRole(UPGRADER_ROLE) {
        version = _newVersion;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}
"
    },
    "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @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) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}
"
    },
    "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(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 The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}
"
    },
    "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
      "content": "// 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
        }
    }
}
"
    },
    "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    function __Pausable_init() internal onlyInitializing {
    }

    function __Pausable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) 

Tags:
ERC20, ERC165, Proxy, Pausable, Staking, Voting, Upgradeable, Factory, Oracle|addr:0x1659fb58e658270893a5d4f50a99b48113fbe0f4|verified:true|block:23541938|tx:0xce7790e37a2c54889adb0c1ed24e755ab5434794d5b1b2667cf22656f75175cf|first_check:1760037887

Submitted on: 2025-10-09 21:24:48

Comments

Log in to comment.

No comments yet.