S Price: $0.070257 (-2.97%)
Gas: 55 Gwei

Contract

0x4b161e312D9b63d8f02Eb9b7a2B09677dCF0772C

Overview

S Balance

Sonic LogoSonic LogoSonic Logo7.899883516498845162 S

S Value

$0.56 (@ $0.07/S)

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Transfer548999512025-11-11 17:28:1974 days ago1762882099IN
0x4b161e31...7dCF0772C
9 S0.001216655

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
610627082026-01-24 16:28:002 hrs ago1769272080
0x4b161e31...7dCF0772C
0.02138584 S
610618652026-01-24 16:08:122 hrs ago1769270892
0x4b161e31...7dCF0772C
0.04505272 S
610618562026-01-24 16:08:002 hrs ago1769270880
0x4b161e31...7dCF0772C
0.01702562 S
610605792026-01-24 15:38:002 hrs ago1769269080
0x4b161e31...7dCF0772C
0.01770681 S
610601952026-01-24 15:27:593 hrs ago1769268479
0x4b161e31...7dCF0772C
0.04419096 S
605803842026-01-17 16:28:007 days ago1768667280
0x4b161e31...7dCF0772C
0.02138584 S
605794612026-01-17 16:08:127 days ago1768666092
0x4b161e31...7dCF0772C
0.04505272 S
605794532026-01-17 16:08:007 days ago1768666080
0x4b161e31...7dCF0772C
0.01702562 S
605779142026-01-17 15:38:007 days ago1768664280
0x4b161e31...7dCF0772C
0.01770681 S
605774952026-01-17 15:27:597 days ago1768663679
0x4b161e31...7dCF0772C
0.04419096 S
600930372026-01-10 16:28:0114 days ago1768062481
0x4b161e31...7dCF0772C
0.02138584 S
600921542026-01-10 16:08:0914 days ago1768061289
0x4b161e31...7dCF0772C
0.04551235 S
600921452026-01-10 16:08:0014 days ago1768061280
0x4b161e31...7dCF0772C
0.01702562 S
600905562026-01-10 15:38:0014 days ago1768059480
0x4b161e31...7dCF0772C
0.01799948 S
600901092026-01-10 15:27:5914 days ago1768058879
0x4b161e31...7dCF0772C
0.04419096 S
595111602026-01-03 16:28:0021 days ago1767457680
0x4b161e31...7dCF0772C
0.02138584 S
595098242026-01-03 16:08:1021 days ago1767456490
0x4b161e31...7dCF0772C
0.04505272 S
595098132026-01-03 16:08:0021 days ago1767456480
0x4b161e31...7dCF0772C
0.01702562 S
595082432026-01-03 15:38:0021 days ago1767454680
0x4b161e31...7dCF0772C
0.01770681 S
595077222026-01-03 15:27:5921 days ago1767454079
0x4b161e31...7dCF0772C
0.04419096 S
590530532025-12-27 16:28:0128 days ago1766852881
0x4b161e31...7dCF0772C
0.02138584 S
590519862025-12-27 16:08:1328 days ago1766851693
0x4b161e31...7dCF0772C
0.04730992 S
590519752025-12-27 16:08:0128 days ago1766851681
0x4b161e31...7dCF0772C
0.01702562 S
590503232025-12-27 15:38:0128 days ago1766849881
0x4b161e31...7dCF0772C
0.01770681 S
590498712025-12-27 15:28:0028 days ago1766849280
0x4b161e31...7dCF0772C
0.04419096 S
View All Internal Transactions
Cross-Chain Transactions
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x9A4Ee8D2...C82e6717f
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
SilverLswTaskManager

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 10 runs

Other Settings:
paris EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {AutomateTaskCreator} from "../integrations/gelato/AutomateTaskCreator.sol";
import {Module, ModuleData} from "../integrations/gelato/Types.sol";
import {GaugeTaskExecutor} from "./GaugeTaskExecutor.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "../Security/ContractPermissionManager.sol";

interface ISilverLswManager {
    function syncLswSystem() external;
    function syncGaugeRewardsCalc() external;
    function executeSyncGaugesRewards() external;
    function startBreakLiquidityAndCompound() external;
    function clearLswSystem() external;
    function setGaugeExecutor(address poolGauge, address executor) external;
    function resetTaskId(bytes32 taskId) external;
}

interface IGaugeTaskExecutor {
    enum TaskType { SNAPSHOT, BREAK_LIQUIDITY }
    function execute(TaskType taskType) external;
}

/**
 * @title SilverLswTaskManager
 * @author github.com/SifexPro
 * @notice This contract is used to manage the Gelato tasks for the LSW system
 */
contract SilverLswTaskManager is AutomateTaskCreator, Ownable2Step {
    // ============ Constants ============
    uint256 private constant SYNC_GAUGE_REWARDS_EXEC_TIME = 10 minutes;
    uint256 private constant BREAK_LIQUIDITY_EXEC_TIME = 40 minutes;
    uint256 private constant CLEAR_SYSTEM_EXEC_TIME = 1 hours;
    uint256 private constant RETRY_WINDOW = 2 minutes;

    // ============ Events ============
    event GelatoTaskCreated(bytes32 id);
    event GelatoTaskCanceled(bytes32 id);
    event GelatoTaskCancelFailed(bytes32 id);
    event GelatoFeesCheck(uint256 fees, address token);
    event ExecutorCreated(address poolGauge, address executor);

    // ============ State Variables ============
    ISilverLswManager public immutable lswManager;
    ContractPermissionManager public immutable securityManager;

    // ============ Constructor ============
    constructor(
        address _lswManager,
        address _securityManager,
        address _automate
    ) AutomateTaskCreator(_automate) Ownable(msg.sender) {
        lswManager = ISilverLswManager(_lswManager);
        securityManager = ContractPermissionManager(_securityManager);
    }

    // ============ Executor Management ============
    function getOrCreateExecutor(address _poolGauge) public returns (address executor) {
        require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
        
        executor = address(new GaugeTaskExecutor(_poolGauge, address(lswManager)));
        lswManager.setGaugeExecutor(_poolGauge, executor);
        emit ExecutorCreated(_poolGauge, executor);
    }

    // ============ Task Creation Functions ============

    function createTaskGaugeSnapshot(
        address executor
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(
            IGaugeTaskExecutor(executor).execute,
            (IGaugeTaskExecutor.TaskType.SNAPSHOT)
        );

        bytes32[][] memory topics = new bytes32[][](1);
        topics[0] = new bytes32[](1);
        topics[0][0] = keccak256("LswSystemSynced(uint256)");

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](2),
            args: new bytes[](2)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.TRIGGER;

        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _eventTriggerModuleArg(
            address(lswManager),
            topics,
            7
        );

        bytes32 taskId = _createTask(executor, execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskGaugeRewardsReinjection(
        address poolGauge,
        address projectToken,
        string memory rewardsReinjectionScriptCID,
        address wrappedNativeToken
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encode(
            Strings.toHexString(uint256(uint160(address(lswManager))), 20),
            Strings.toHexString(uint256(uint160(poolGauge)), 20),
            Strings.toHexString(uint256(uint160(projectToken)), 20),
            Strings.toString(ERC20(projectToken).decimals()),
            Strings.toHexString(uint256(uint160(wrappedNativeToken)), 20),
            Strings.toString(block.chainid)
        );

        bytes32[][] memory topics = new bytes32[][](1);
        topics[0] = new bytes32[](1);
        topics[0][0] = keccak256("GaugesRewardsSynced(uint256)");

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](3),
            args: new bytes[](3)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.WEB3_FUNCTION;
        moduleData.modules[2] = Module.TRIGGER;

        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _web3FunctionModuleArg(
            rewardsReinjectionScriptCID,
            execData
        );
        moduleData.args[2] = _eventTriggerModuleArg(
            address(lswManager),
            topics,
            7
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskBreakLiquidityAndCompoundCall(
        address executor
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(
            IGaugeTaskExecutor(executor).execute,
            (IGaugeTaskExecutor.TaskType.BREAK_LIQUIDITY)
        );

        bytes32[][] memory topics = new bytes32[][](1);
        topics[0] = new bytes32[](1);
        topics[0][0] = keccak256("StartBreakLiquidityAndCompound(uint256)");

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](2),
            args: new bytes[](2)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.TRIGGER;

        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _eventTriggerModuleArg(
            address(lswManager),
            topics,
            7
        );

        bytes32 taskId = _createTask(executor, execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskSyncGaugeRewardsCalc(
        uint256 lastSyncTimestamp
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(lswManager.syncGaugeRewardsCalc, ());

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](3),
            args: new bytes[](3)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.SINGLE_EXEC;
        moduleData.modules[2] = Module.TRIGGER;
        
        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _singleExecModuleArg();
        moduleData.args[2] = _timeTriggerModuleArg(
            uint128(lastSyncTimestamp + SYNC_GAUGE_REWARDS_EXEC_TIME) * 1000,
            uint128(SYNC_GAUGE_REWARDS_EXEC_TIME / 2) * 1000
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskGaugesRewards() external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(lswManager.executeSyncGaugesRewards, ());

        bytes32[][] memory topics = new bytes32[][](1);
        topics[0] = new bytes32[](1);
        topics[0][0] = keccak256("SyncGaugesRewardsStarted(uint256)");

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](2),
            args: new bytes[](2)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.TRIGGER;
        
        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _eventTriggerModuleArg(
            address(lswManager),
            topics,
            7
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskStartBreakLiquidityAndCompound(
        uint256 lastSyncTimestamp
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(lswManager.startBreakLiquidityAndCompound, ());

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](3),
            args: new bytes[](3)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.SINGLE_EXEC;
        moduleData.modules[2] = Module.TRIGGER;
        
        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _singleExecModuleArg();
        moduleData.args[2] = _timeTriggerModuleArg(
            uint128(lastSyncTimestamp + BREAK_LIQUIDITY_EXEC_TIME) * 1000,
            uint128(BREAK_LIQUIDITY_EXEC_TIME) * 1000
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskSyncSystem(
        uint256 nextSyncTimestamp,
        uint256 syncTime
    ) external onlyLswManager returns (bytes32) {
        bytes memory execData = abi.encodeCall(lswManager.syncLswSystem, ());

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](2),
            args: new bytes[](2)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.TRIGGER;
        
        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _timeTriggerModuleArg(
            uint128(nextSyncTimestamp) * 1000,
            uint128(syncTime) * 1000
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    function createTaskClearLswSystem(
        uint256 lastSyncTimestamp
    ) external onlyLswManager returns (bytes32) {
        require(lastSyncTimestamp + CLEAR_SYSTEM_EXEC_TIME > block.timestamp, "Invalid execution time");

        bytes memory execData = abi.encodeCall(lswManager.clearLswSystem, ());

        ModuleData memory moduleData = ModuleData({
            modules: new Module[](3),
            args: new bytes[](3)
        });

        moduleData.modules[0] = Module.PROXY;
        moduleData.modules[1] = Module.SINGLE_EXEC;
        moduleData.modules[2] = Module.TRIGGER;

        moduleData.args[0] = _proxyModuleArg();
        moduleData.args[1] = _singleExecModuleArg();
        moduleData.args[2] = _timeTriggerModuleArg(
            uint128(lastSyncTimestamp + CLEAR_SYSTEM_EXEC_TIME) * 1000,
            uint128(RETRY_WINDOW) * 1000
        );

        bytes32 taskId = _createTask(address(lswManager), execData, moduleData, ETH);
        emit GelatoTaskCreated(taskId);
        return taskId;
    }

    // ============ Task Cancellation Functions ============

	function cancelTaskCall(bytes32 taskId) public {
		require(msg.sender == address(this), "Not authorized");
		_cancelTask(taskId);
	}

    function cancelTask(bytes32 taskId) public onlyLswManager {
        if (taskId == bytes32(0)) return;

		(bool success, ) = address(this).call(
			abi.encodeWithSignature("cancelTaskCall(bytes32)", taskId)
		);
        
		if (success) {
			emit GelatoTaskCanceled(taskId);
			lswManager.resetTaskId(taskId);
		} else {
			emit GelatoTaskCancelFailed(taskId);
		}
    }

    function cancelMultipleTasks(bytes32[] calldata taskIds) external onlyLswManager {
        for (uint256 i = 0; i < taskIds.length; i++) {
            if (taskIds[i] != bytes32(0)) {
                cancelTask(taskIds[i]);
            }
        }
    }

	// ============ Gelato Fees Management ============

	function _handleGelatoFees() public onlyLswManager {
        (uint256 fee, address feeToken) = _getFeeDetails();
        _transfer(fee, feeToken);
        emit GelatoFeesCheck(fee, feeToken);
    }

	// ============ Modifiers ============
    modifier onlyLswManager() {
        require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
        _;
    }

    // ============ Receive Function ============
    receive() external payable {}
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.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 AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @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 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 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 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 `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @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 Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @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 signaling 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;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

File 8 of 41 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

File 9 of 41 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.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 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);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

File 19 of 41 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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 ReentrancyGuard {
    // 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;

    uint256 private _status;

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

    constructor() {
        _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 {
        // 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 {
        // 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) {
        return _status == ENTERED;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(buffer, add(0x20, offset)))
        }
    }
}

File 24 of 41 : GaugeManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {TransferHelper} from "../libraries/TransferHelper.sol";
import {ContractPermissionManager} from "../Security/ContractPermissionManager.sol";
import {TimelockProtection} from "../Security/TimelockProtection.sol";

import {PoolLocker, PositionInfo} from "./PoolLocker.sol";
import {SilverLswManager} from "../LSW/SilverLswManager.sol";
import {TransferHelper} from "../libraries/TransferHelper.sol";
import {INonfungiblePositionManager} from "../interfaces/INonFungiblePositionManager.sol";

// ============ Interfaces ============
interface IAlgebraPool {
	function token0() external view returns (address);
	function token1() external view returns (address);
	function liquidity() external view returns (uint128);
}

interface IAlgebraFactory {
    function getPair(
        address tokenA,
        address tokenB
    ) external view returns (address pool);
}

// ============ Structs ============
struct GaugeInfo {
	address agsTokenPool;			// AGS/xToken LP
	address wrappedNativePool;		// wrappedNativeToken/xToken LP
	uint256 agsPositionId;			// Position ID for AGS/xToken LP
	uint256 wrappedPositionId;		// Position ID for wrappedNativeToken/xToken LP
	uint256 totalAgsDeposited;		// Total AGS deposited in the gauge
	bool exists;					// Whether the gauge exists
	bool active;					// Whether the gauge is active
}

struct UserInfo {
	uint256 totalAgsDeposited;  // Total AGS deposited across all gauges
	mapping(address => uint256) agsDeposits;  // Amount of AGS deposited per pool
	mapping(address => uint256) projectTokenDeposits;  // Amount of project token deposited per pool
	mapping(address => uint128) liquidityDeposits;  // Amount of liquidity deposited per pool
}

/**
 * @title GaugeManager
 * @author github.com/SifexPro
 * @notice This contract is used to manage the gauges for the SilverLsw protocol
 */
contract GaugeManager is Ownable2Step, TimelockProtection {
	// ============ Interfaces ============
	PoolLocker public poolLocker;
	SilverLswManager public silverLswManager;
	IERC20 public silverStakeToken;
	INonfungiblePositionManager public positionManager;
	IERC721 public positionManagerERC721;
	ContractPermissionManager public immutable securityManager;

	// ============ Utils variables ============
	uint256 public totalAgsLocked; // Total AGS locked in LockedLP
	uint256 public totalAgsDeposited; // Total AGS deposited in gauges
	address public immutable wrappedNativeToken;
	address[] public unlockedPools;

	// ============ Mapping ============
	mapping(address => GaugeInfo) public gaugeInfo;
	mapping(address => UserInfo) public userInfo;

	// ============ Events for gauge management ============
	event GaugeInitialized(
		address indexed pool, 
		address agsTokenPool, 
		address wrappedNativePool,
		uint256 agsPositionId,
		uint256 wrappedPositionId
	);
	event GaugeDesactivated(address indexed pool);
	event PoolUnlocked(address indexed pool);
	
	// ============ Events for liquidity ============
	event LiquidityAdded(address indexed pool, uint256 tokenId, uint256 amount0, uint256 amount1);
	event LiquidityRemoved(address indexed pool, uint256 tokenId, uint256 amount0, uint256 amount1);
	event LiquidityReinjected(address indexed pool, uint256 tokenId, uint256 amount0, uint256 amount1);
	
	// ============ Events for AGS ============
	event LockedAgsUpdated(uint256 newTotal);
	
	// ============ Events for refunds ============
	event PendingTokensRefunded(address indexed projectToken, address indexed recipient, uint256 projectTokenAmount, uint256 silverStakeAmount);
	
	// ============ Events for setters ============
	event SilverLswManagerSet(address indexed newSilverLswManager);
	event PoolLockerSet(address indexed newPoolLocker);

	// ============ Events for owner ============
	event WithdrawnNative(address indexed to, uint256 amount);
	event WithdrawnToken(address indexed token, address to, uint256 amount);

	// ============ Constructor ============
	constructor(
		address _positionManager, 
		address _poolLocker, 
		address _silverStakeToken,
		address _wrappedNativeToken,
		address _securityManager,
		address _timelockMain,
		address _timelockAdmin
	) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
		poolLocker = PoolLocker(payable(_poolLocker));
		positionManager = INonfungiblePositionManager(_positionManager);
		positionManagerERC721 = IERC721(_positionManager);
		silverStakeToken = IERC20(_silverStakeToken);
		wrappedNativeToken = _wrappedNativeToken;
		securityManager = ContractPermissionManager(_securityManager);
	}


	// ============ Gauge functions ============

	/**
	 * @notice Initialize a new gauge with AGS/xToken and wrappedNativeToken/xToken pools
	 * @param lockedPositionId The locked position ID
	 * @dev Protected by admin timelock due to impact on gauge operations
	 */
	function initGauge(uint256 lockedPositionId) public requireTimelockAdmin {
		require(!isLswLocked(), "Lsw system is locked");
		PositionInfo memory position = getPositionInfoByLockedPositionId(lockedPositionId);
		
		require(!position.gaugeCreated, "Gauge already created");
		require(position.locked, "Position not locked");
		require(position.token0 == address(silverStakeToken) || position.token1 == address(silverStakeToken), "Invalid pool tokens");

		
		address projectToken = position.token0 == address(silverStakeToken) ? position.token1 : position.token0;

		// Get wrappedNativeToken/xToken pool
		address wrappedNativePool = _getWrappedNativePool(projectToken);
		
		// Create empty positions for both pools
		uint256 agsPositionId = _createEmptyPosition(position.pool);
		uint256 wrappedPositionId = _createEmptyPosition(wrappedNativePool);

		require(agsPositionId != 0 && wrappedPositionId != 0, "Failed to create empty positions");

		poolLocker.gaugeCreated(position.tokenId);

		silverLswManager.syncNewGauge(position.pool);

		gaugeInfo[position.pool] = GaugeInfo({
			agsTokenPool: position.pool,
			wrappedNativePool: wrappedNativePool,
			agsPositionId: agsPositionId,
			wrappedPositionId: wrappedPositionId,
			totalAgsDeposited: 0,
			exists: true,
			active: true
		});

		emit GaugeInitialized(position.pool, position.pool, wrappedNativePool, agsPositionId, wrappedPositionId);
	}

	/**
	 * @notice Refuse a gauge
	 * @dev Protected by admin timelock due to impact on gauge operations
	 * @param lockedPositionId The locked position ID
	 */
	function refuseGauge(uint256 lockedPositionId) public requireTimelockAdmin {
		PositionInfo memory position = getPositionInfoByLockedPositionId(lockedPositionId);
		require(!position.gaugeCreated, "Gauge already created");
		require(position.locked, "Position not locked");
		
		poolLocker.gaugeRefused(position.tokenId);
	}

	/**
	 * @notice Add liquidity to a gauge's AGS/xToken position
	 * @param pool The pool address
	 * @param amount0Desired Amount of token0 to add
	 * @param amount1Desired Amount of token1 to add
	 * @param slippagePercent The percentage of slippage tolerance (e.g. 10 for 10%)
	 */
	function addLiquidityInGauge(
		address pool,
		uint256 amount0Desired,
		uint256 amount1Desired,
		uint256 slippagePercent
	) public {
		require(!isLswLocked(), "Lsw system is locked");
		GaugeInfo storage info = gaugeInfo[pool];
		require(info.active, "Gauge not active");
		require(slippagePercent > 0 && slippagePercent < 100, "Invalid slippage percentage");
		
		(address token0, address token1) = (IAlgebraPool(pool).token0(), IAlgebraPool(pool).token1());

		// Transfer tokens from user
		TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amount0Desired);
		TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amount1Desired);

		// Approve tokens to position manager
		TransferHelper.safeApprove(token0, address(positionManager), amount0Desired);
		TransferHelper.safeApprove(token1, address(positionManager), amount1Desired);
		
		// Increase liquidity of AGS/xToken position
		(uint128 liquidityAdded, uint256 amount0, uint256 amount1) = positionManager.increaseLiquidity(
			INonfungiblePositionManager.IncreaseLiquidityParams({
				tokenId: info.agsPositionId,
				amount0Desired: amount0Desired,
				amount1Desired: amount1Desired,
				amount0Min: (amount0Desired * (100 - slippagePercent)) / 100,
				amount1Min: (amount1Desired * (100 - slippagePercent)) / 100,
				deadline: block.timestamp + 1 hours
			})
		);

		// Sort amounts into AGS and project token
		(uint256 agsAmount, uint256 projectTokenAmount) = _sortTokenAmounts(pool, amount0, amount1);
		
		// Update user's deposits
		UserInfo storage user = userInfo[msg.sender];
		user.totalAgsDeposited += agsAmount;
		user.agsDeposits[pool] += agsAmount;
		user.projectTokenDeposits[pool] += projectTokenAmount;
		user.liquidityDeposits[pool] += liquidityAdded;
		
		info.totalAgsDeposited += agsAmount;
		totalAgsDeposited += agsAmount;

		emit LiquidityAdded(pool, info.agsPositionId, amount0, amount1);
	}

	/**
	 * @notice Remove liquidity from a gauge's AGS/xToken position
	 * @param pool The pool address
	 * @param liquidity The amount of liquidity to remove
	 */
	function removeLiquidityFromGauge(
		address pool,
		uint128 liquidity
	) public {
		require(!isLswLocked(), "Lsw system is locked");
		GaugeInfo storage info = gaugeInfo[pool];
		require(info.exists, "Gauge does not exist");
		
		UserInfo storage user = userInfo[msg.sender];
		require(user.liquidityDeposits[pool] >= liquidity, "Insufficient liquidity deposit");
		
		// Get current position info
		(, , , , , , uint128 currentLiquidity, , , , ) = positionManager.positions(info.agsPositionId);
		require(currentLiquidity >= liquidity, "Insufficient position liquidity");
		
		// Remove liquidity from AGS/xToken position
		(uint256 amount0, uint256 amount1) = positionManager.decreaseLiquidity(
			INonfungiblePositionManager.DecreaseLiquidityParams({
				tokenId: info.agsPositionId,
				liquidity: liquidity,
				amount0Min: 0,
				amount1Min: 0,
				deadline: block.timestamp + 1 hours
			})
		);

		// Sort amounts into AGS and project token
		(uint256 agsAmount, uint256 projectTokenAmount) = _sortTokenAmounts(pool, amount0, amount1);

		// Collect tokens
		positionManager.collect(
			INonfungiblePositionManager.CollectParams({
				tokenId: info.agsPositionId,
				recipient: msg.sender,
				amount0Max: uint128(amount0),
				amount1Max: uint128(amount1)
			})
		);

		// Handle edge case: if removing all liquidity, cap withdrawal amounts to prevent underflow
		if (liquidity == user.liquidityDeposits[pool]) {
			uint256 storedAgsDeposit = user.agsDeposits[pool];
			
			// Update gauge and global totals safely
			info.totalAgsDeposited = info.totalAgsDeposited > storedAgsDeposit ? 
				info.totalAgsDeposited - storedAgsDeposit : 0;
			totalAgsDeposited = totalAgsDeposited > storedAgsDeposit ? 
				totalAgsDeposited - storedAgsDeposit : 0;
			
			// Clear user deposits for this pool
			user.totalAgsDeposited = user.totalAgsDeposited > storedAgsDeposit ? 
				user.totalAgsDeposited - storedAgsDeposit : 0;
			user.agsDeposits[pool] = 0;
			user.projectTokenDeposits[pool] = 0;
			user.liquidityDeposits[pool] = 0;
		} else {
			// For partial withdrawals, use calculated values but ensure no underflow
			uint256 agsDiff = user.agsDeposits[pool] < agsAmount ? user.agsDeposits[pool] : agsAmount;
			uint256 projectTokenDiff = user.projectTokenDeposits[pool] < projectTokenAmount ? 
				user.projectTokenDeposits[pool] : projectTokenAmount;
			
			// Update user's deposits
			user.totalAgsDeposited -= agsDiff;
			user.agsDeposits[pool] -= agsDiff;
			user.projectTokenDeposits[pool] -= projectTokenDiff;
			user.liquidityDeposits[pool] -= liquidity;
			
			// Update gauge and global totals
			info.totalAgsDeposited -= agsDiff;
			totalAgsDeposited -= agsDiff;
		}

		emit LiquidityRemoved(pool, info.agsPositionId, amount0, amount1);
	}

	/**
	 * @notice Add liquidity to a gauge's wrappedNativeToken/xToken position
	 * @param pool The pool address
	 * @param amount0Desired Amount of token0 to add
	 * @param amount1Desired Amount of token1 to add
	 * @param slippagePercent The percentage of slippage tolerance (e.g. 10 for 10%)
	 */
	function addLiquidityInWrappedPool(
		address pool,
		uint256 amount0Desired,
		uint256 amount1Desired,
		uint256 slippagePercent
	) public onlySilverLswManager {
		GaugeInfo storage info = gaugeInfo[pool];
		require(info.active, "Gauge not active");
		require(slippagePercent > 0 && slippagePercent < 100, "Invalid slippage percentage");
		
		(address token0, address token1) = (IAlgebraPool(info.wrappedNativePool).token0(), IAlgebraPool(info.wrappedNativePool).token1());

		// Transfer tokens from user
		TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amount0Desired);
		TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amount1Desired);

		// Approve tokens to position manager
		TransferHelper.safeApprove(token0, address(positionManager), amount0Desired);
		TransferHelper.safeApprove(token1, address(positionManager), amount1Desired);
		
		(, uint256 amount0, uint256 amount1) = positionManager.increaseLiquidity(
			INonfungiblePositionManager.IncreaseLiquidityParams({
				tokenId: info.wrappedPositionId,
				amount0Desired: amount0Desired,
				amount1Desired: amount1Desired,
				amount0Min: (amount0Desired * (100 - slippagePercent)) / 100,
				amount1Min: (amount1Desired * (100 - slippagePercent)) / 100,
				deadline: block.timestamp + 1 hours
			})
		);

		// Handle any remaining tokens
		uint256 remaining0 = amount0Desired - amount0;
		uint256 remaining1 = amount1Desired - amount1;
		
		if (remaining0 > 0) {
			TransferHelper.safeTransfer(token0, msg.sender, remaining0);
		}
		if (remaining1 > 0) {
			TransferHelper.safeTransfer(token1, msg.sender, remaining1);
		}

		emit LiquidityReinjected(info.wrappedNativePool, info.wrappedPositionId, amount0, amount1);
	}

	/**
	 * @notice Remove 5% of liquidity from a gauge's wrappedNativeToken/xToken position
	 * @param pool The pool address
	 */
	function removeLiquidityFromWrappedPool(
		address pool
	) public onlySilverLswManager {
		GaugeInfo storage info = gaugeInfo[pool];
		require(info.active, "Gauge not active");
		
		// Get current position info
		(, , , , , , uint128 currentLiquidity, , , , ) = positionManager.positions(info.wrappedPositionId);
		require(currentLiquidity > 0, "No liquidity in position");
		
		// Calculate 5% of current liquidity
		uint128 liquidityToRemove = (currentLiquidity * 5) / 100;
		
		// Remove liquidity from wrappedNativeToken/xToken position
		(uint256 amount0, uint256 amount1) = positionManager.decreaseLiquidity(
			INonfungiblePositionManager.DecreaseLiquidityParams({
				tokenId: info.wrappedPositionId,
				liquidity: liquidityToRemove,
				amount0Min: 0,
				amount1Min: 0,
				deadline: block.timestamp + 1 hours
			})
		);

		// Collect tokens and send them to SilverLswManager
		positionManager.collect(
			INonfungiblePositionManager.CollectParams({
				tokenId: info.wrappedPositionId,
				recipient: address(silverLswManager),
				amount0Max: uint128(amount0),
				amount1Max: uint128(amount1)
			})
		);

		emit LiquidityRemoved(info.wrappedNativePool, info.wrappedPositionId, amount0, amount1);
	}

	/**
	 * @notice Get the position ID for a pool
	 * @param pool The pool address
	 * @return The position ID
	 */
	function _getPositionId(address pool) public view returns (uint256) {
		return gaugeInfo[pool].wrappedPositionId;
	}

	/**
	 * @notice Sort tokens to identify WETH and other token
	 * @param pool The pool address
	 * @param amount0 Amount of token0
	 * @param amount1 Amount of token1
	 * @return wethToken The WETH token address
	 * @return otherToken The other token address
	 * @return wethAmount The amount of WETH
	 * @return otherAmount The amount of other token
	 */
	function _sortTokens(
		address pool,
		uint256 amount0,
		uint256 amount1
	) private view returns (
		address wethToken,
		address otherToken,
		uint256 wethAmount,
		uint256 otherAmount
	) {
		IAlgebraPool poolContract = IAlgebraPool(pool);
		address token0 = poolContract.token0();
		address token1 = poolContract.token1();

		if (token0 == wrappedNativeToken) {
			return (token0, token1, amount0, amount1);
		} else {
			return (token1, token0, amount1, amount0);
		}
	}

	/**
	 * @notice Determine which token is AGS and which is project token
	 * @param pool The pool address
	 * @param amount0 Amount of token0
	 * @param amount1 Amount of token1
	 * @return agsAmount Amount of AGS
	 * @return projectTokenAmount Amount of project token
	 */
	function _sortTokenAmounts(
		address pool,
		uint256 amount0,
		uint256 amount1
	) private view returns (
		uint256 agsAmount,
		uint256 projectTokenAmount
	) {
		if (IAlgebraPool(pool).token0() == address(silverStakeToken)) {
			return (amount0, amount1);
		} else {
			return (amount1, amount0);
		}
	}


	// ============ Internal functions ============

	/**
	 * @notice Unlock all positions that are waiting for the liquidity to be unlocked
	 */
	function unlockAllPositions() external onlySilverLswManager {
		poolLocker.unlockAllPositions();
	}

	/**
	 * @notice Increase the total AGS locked in LockedLP
	 * @param amountLockedAgs The amount of AGS locked
	 */
	function increaseLockedAgs(uint256 amountLockedAgs) external onlyPoolLocker {
		totalAgsLocked += amountLockedAgs;

		emit LockedAgsUpdated(totalAgsLocked);
	}

	/**
	 * @notice Decrease the total AGS locked in LockedLP
	 * @param amountUnlockedAgs The amount of AGS unlocked
	 */
	function decreaseLockedAgs(uint256 amountUnlockedAgs) external onlyPoolLocker {
		totalAgsLocked -= amountUnlockedAgs;

		emit LockedAgsUpdated(totalAgsLocked);
	}

	/**
	 * @notice Desactivate a gauge (if liquidity is unlocked)
	 * @param pool The pool address
	 */
	function desactivateGauge(address pool) external onlyPoolLocker {
		if (!gaugeInfo[pool].exists || !gaugeInfo[pool].active) return;
		
		gaugeInfo[pool].active = false;
		silverLswManager.cancelTaskGauge(pool);

		emit GaugeDesactivated(pool);
	}
	
	/**
	 * @notice Add a pool to the unlockedPools array
	 * @param pool The pool address
	 */
	function unlockedPool(address pool) external onlyPoolLocker {
		unlockedPools.push(pool);

		emit PoolUnlocked(pool);
	}

	/**
	 * @notice Refund tokens sent during mintAndLockPosition when gauge is refused/unlocked
	 * @param projectToken The project token address
	 * @param recipient The address to refund tokens to
	 */
	function refundPendingTokens(address projectToken, address recipient) external onlyPoolLocker {
		TransferHelper.safeTransfer(projectToken, recipient, 2000);
		TransferHelper.safeTransfer(address(silverStakeToken), recipient, 1000);

		emit PendingTokensRefunded(projectToken, recipient, 2000, 1000);
	}

	/**
	 * @notice Create an empty position in a pool
	 * @param pool The pool address
	 * @return The position ID
	 */
	function _createEmptyPosition(
		address pool
	) private returns (uint256) {
		(address _token0, address _token1) = (IAlgebraPool(pool).token0(), IAlgebraPool(pool).token1());

		TransferHelper.safeApprove(_token0, address(positionManager), 1000);
		TransferHelper.safeApprove(_token1, address(positionManager), 1000);

		// Create empty position with full range
		INonfungiblePositionManager.MintParams memory params;
		params.token0 = _token0;
		params.token1 = _token1;
		params.tickLower = -887220;
		params.tickUpper = 887220;
		params.amount0Desired = 1000;
		params.amount1Desired = 1000;
		params.amount0Min = 100;
		params.amount1Min = 100;
		params.recipient = address(this);
		params.deadline = block.timestamp + 1 hours;

		(uint256 tokenId, , , ) = positionManager.mint(params);
		return tokenId;
	}

	function _getWrappedNativePool(
		address _projectToken
	) private returns (address pool) {
		(address _token0, address _token1) = _projectToken < wrappedNativeToken ? 
			(_projectToken, wrappedNativeToken) : (wrappedNativeToken, _projectToken);

		pool = IAlgebraFactory(positionManager.factory()).getPair(_token0, _token1);
		
		require(pool != address(0), "wrappedNative/projectToken pool not found");

		return pool;
	}


	// ============ Setters ============

	/**
	 * @notice Set the SilverLswManager address
	 * @dev Protected by main timelock due to critical system integration
	 * @param _silverLswManager The new SilverLswManager address
	 */
	function setSilverLswManager(address _silverLswManager) public requireTimelockMain {
		silverLswManager = SilverLswManager(payable(_silverLswManager));
		emit SilverLswManagerSet(_silverLswManager);
	}

	/**
	 * @notice Set the PoolLocker address
	 * @dev Protected by main timelock due to critical system integration
	 * @param _poolLocker The new PoolLocker address
	 */
	function setPoolLocker(address _poolLocker) public requireTimelockMain {
		poolLocker = PoolLocker(payable(_poolLocker));
		emit PoolLockerSet(_poolLocker);
	}


	// ============ Owner Functions ============

	/**
	 * @notice Withdraw native tokens to a specified address
	 * @dev Protected by admin timelock
	 * @param _to The address to withdraw to
	 */
	function withdrawNative(address _to) public requireTimelockAdmin {
		uint256 balance = address(this).balance;
		require(balance > 0, "No Native to withdraw");

		address payable _tresory = payable(_to);
		(bool success, ) = _tresory.call{value:balance}("");
		require(success, "Transaction failed");

		emit WithdrawnNative(_tresory, balance);
	}

	/**
	 * @notice Withdraw ERC20 tokens to a specified address
	 * @dev Protected by admin timelock
	 * @param _token The token address
	 * @param _to The address to withdraw to
	 */
	function withdrawToken(address _token, address _to) public requireTimelockAdmin {
		IERC20 token = IERC20(_token);
		uint256 balance = token.balanceOf(address(this));

		SafeERC20.safeTransfer(token, _to, balance);

		emit WithdrawnToken(_token, _to, balance);
	}


	// ============ Getters ============

	function getTotalAgsDeposited() public view returns (uint256) {
		return totalAgsDeposited;
	}

	function getUserVotingPower(address user) public view returns (uint256) {
		if (getTotalAgsDeposited() == 0) return 0;
		
		return (getUserTotalAgsDeposits(user) * 1e18) / getTotalAgsDeposited();
	}

	function getProjectToken(address pool) public view returns (address) {
		return IAlgebraPool(pool).token0() == address(silverStakeToken) ? IAlgebraPool(pool).token1() : IAlgebraPool(pool).token0();
	}

	function getUserAgsDeposits(address user, address pool) public view returns (uint256) {
		return userInfo[user].agsDeposits[pool];
	}

	function getUserProjectTokenDeposits(address user, address pool) public view returns (uint256) {
		return userInfo[user].projectTokenDeposits[pool];
	}

	function getUserLiquidityDeposits(address user, address pool) public view returns (uint128) {
		return userInfo[user].liquidityDeposits[pool];
	}

	function getUserTotalAgsDeposits(address user) public view returns (uint256) {
		uint256 userAgsDeposits = userInfo[user].totalAgsDeposited;
		uint256 length = unlockedPools.length;
		
		unchecked {
			for (uint256 i = 0; i < length; i++) {
				userAgsDeposits -= userInfo[user].agsDeposits[unlockedPools[i]];
			}
		}
		
		return userAgsDeposits;
	}

	function getGaugeInfo(address pool) public view returns (GaugeInfo memory) {
		return gaugeInfo[pool];
	}

	function isGaugeActive(address pool) public view returns (bool) {
		return gaugeInfo[pool].active;
	}

	function isLswLocked() public view returns (bool) {
		return silverLswManager.isLswLocked();
	}


	// ============ PoolLocker getters ============

	function getPositionInfoByTokenId(uint256 _tokenId) public view returns (PositionInfo memory) {
		return poolLocker._getPositionInfoByTokenId(_tokenId);
	}

	function getPositionInfoByLockedPositionId(uint256 _lockedPositionId) public view returns (PositionInfo memory) {
		return poolLocker._getPositionInfoByLockedPositionId(_lockedPositionId);
	}

	function getPendingGauges() public view returns (uint256[] memory) {
		return poolLocker._getPendingGauges();
	}

	function isGaugeCreated(uint256 _tokenId) public view returns (bool) {
		return poolLocker._isGaugeCreated(_tokenId);
	}


	// ============ Modifiers ============

	modifier onlyPoolLocker() {
		require(securityManager.hasContractRole(securityManager.POOL_LOCKER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier onlySilverLswManager () {
		require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}


	// ============ Receive function ============

	receive() external payable {}
}

File 25 of 41 : PoolLocker.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import "@openzeppelin/contracts/access/Ownable2Step.sol";

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {INonfungiblePositionManager} from "../interfaces/INonFungiblePositionManager.sol";
import "../Security/ContractPermissionManager.sol";
import "../Security/TimelockProtection.sol";
import {TransferHelper} from "../libraries/TransferHelper.sol";

// ============ Interfaces ============
interface IGaugeManager {
	function increaseLockedAgs(uint256 amountLockedAgs) external;
	function decreaseLockedAgs(uint256 amountUnlockedAgs) external;
	function desactivateGauge(address pool) external;
	function unlockedPool(address pool) external;
	function isLswLocked() external view returns (bool);
	function isGaugeActive(address pool) external view returns (bool);
	function refundPendingTokens(address projectToken, address owner) external;
}

interface IAlgebraFactory {
    function getPair(
        address tokenA,
        address tokenB
    ) external view returns (address pool);
}

// ============ Structs ============
struct PositionInfo {
	uint256 lockedPositionId;  // ID of the locked position (starts from 1)
	uint256 tokenId;
	address owner;
	address token0;
	address token1;
	uint256 silverStakeAmount;
	uint256 lockedMonths;
	uint256 creationTime;
	uint256 lockedUntil;
	bool locked;
	bool gaugeCreated;
	bool pendingUnlock;
	address pool;
}

/**
 * @title PoolLocker
 * @author github.com/SifexPro
 * @notice This contract is used to lock the LP tokens for the gauges
 */
contract PoolLocker is Ownable2Step, TimelockProtection {
	// ============ Interfaces ============
	IERC20 public silverStakeToken;
	IGaugeManager public gaugeManager;
	INonfungiblePositionManager public positionManager;
	IERC721 public positionManagerERC721;
	ContractPermissionManager public immutable securityManager;

	// ============ Storage ============
	uint256 public lockedPositionId;
    mapping(uint256 => PositionInfo) public positionByTokenId;
	mapping(address => uint256[]) public userPositions;
	mapping(uint256 => uint256) public tokenIdByLockedPositionId;
	uint256[] public pendingGaugesTokenId;
	uint256[] public pendingToUnlockTokenId;

	// ============ Events ============
	event PositionMinted(uint256 lockedPositionId, uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
	event PositionLocked(uint256 lockedPositionId, uint256 tokenId, address owner);
	event PositionUnlocked(uint256 lockedPositionId, uint256 tokenId, address owner);
	event PositionUnlockedAll();
	event PositionUnlockedAndDesactivatedGauge(uint256 lockedPositionId, uint256 tokenId, address owner);
	event PositionLockIncreased(uint256 lockedPositionId, uint256 tokenId, uint256 oldMonthsLocked, uint256 newMonthsLocked);
	event PoolFeesWithdrawn(uint256 lockedPositionId, uint256 tokenId, address pool, uint256 amount0, uint256 amount1);

	// ============ Events for gauges ============
	event PendingGaugeCreated(uint256 tokenId);
	event PendingGaugeRefused(uint256 tokenId);
	event PendingGaugeRemoved(uint256 tokenId);
	event PendingGaugePurged(uint256 tokenId);
	event PendingGaugeUnlocked(uint256 lockedPositionId, uint256 tokenId, address owner);

	// ============ Events for setters ============
	event PositionManagerSet(address positionManager);
	event GaugeManagerSet(address gaugeManager);

	// ============ Constructor ============
	constructor(
		address _positionManager,
		address _silverStakeToken, 
		address _securityManager,
		address _timelockMain,
		address _timelockAdmin
	) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
		positionManager = INonfungiblePositionManager(_positionManager);
		positionManagerERC721 = IERC721(_positionManager);
		silverStakeToken = IERC20(_silverStakeToken);
		securityManager = ContractPermissionManager(_securityManager);
	}


	// ============ LockLP functions ============

	/**	
	 * @notice mint and lock position
	 * @param lockedMonths The amount of mouths to lock the position (must be multiple of 3)
	 * @param projectToken The project token
	 * @param projectTokenAmount The amount of project tokens to lock
	 * @param silverStakeAmount The amount of silver stake to lock
	 * @param slippagePercent The percentage of slippage tolerance (e.g. 10 for 10%)
	 */
	function mintAndLockPosition(
		uint256 lockedMonths, 
		address projectToken, 
		uint256 projectTokenAmount, 
		uint256 silverStakeAmount,
		uint256 slippagePercent
	) public checkLockMonths(lockedMonths) {
		require(!gaugeManager.isLswLocked(), "Lsw system is locked");
		require(projectToken != address(0), "Invalid project token");
		require(projectToken != address(silverStakeToken), "Project token cannot be SilverStake");
		require(projectTokenAmount > 2000 && silverStakeAmount > 1000, "Amounts too low");
		require(slippagePercent > 0 && slippagePercent <= 50, "Invalid slippage percentage"); //// Increased max to 50%

		uint256 balanceSilverStakeTokenBefore = silverStakeToken.balanceOf(address(this));

		TransferHelper.safeTransferFrom(projectToken, msg.sender, address(this), projectTokenAmount);
		TransferHelper.safeTransferFrom(address(silverStakeToken), msg.sender, address(this), silverStakeAmount);
		
		projectTokenAmount -= 2000;
		silverStakeAmount -= 1000;

		TransferHelper.safeTransfer(projectToken, address(gaugeManager), 2000);
		TransferHelper.safeTransfer(address(silverStakeToken), address(gaugeManager), 1000);

		TransferHelper.safeApprove(projectToken, address(positionManager), projectTokenAmount);
		TransferHelper.safeApprove(address(silverStakeToken), address(positionManager), silverStakeAmount);

		(address token0, address token1) = projectToken < address(silverStakeToken) ? 
			(projectToken, address(silverStakeToken)) : (address(silverStakeToken), projectToken);
		(uint256 amount0Desired, uint256 amount1Desired) = projectToken < address(silverStakeToken) ? 
			(projectTokenAmount, silverStakeAmount) : (silverStakeAmount, projectTokenAmount);

		address pool = IAlgebraFactory(positionManager.factory()).getPair(token0, token1);
		require(pool != address(0), "Pool not found");
		require(!gaugeManager.isGaugeActive(pool), "Gauge already active for this projectToken");

		// Improved slippage calculation with more flexibility
		// Use a more conservative minimum, especially for low-liquidity pools
		uint256 amount0Min = amount0Desired > 0 ? (amount0Desired * (100 - slippagePercent)) / 100 : 0;
		uint256 amount1Min = amount1Desired > 0 ? (amount1Desired * (100 - slippagePercent)) / 100 : 0;
		
		// Additional safety: ensure minimum amounts are not too close to desired amounts for small amounts
		if (amount0Desired > 0 && amount0Min > (amount0Desired * 95) / 100) {
			amount0Min = (amount0Desired * 85) / 100; // More lenient for small amounts
		}
		if (amount1Desired > 0 && amount1Min > (amount1Desired * 95) / 100) {
			amount1Min = (amount1Desired * 85) / 100; // More lenient for small amounts
		}

		(uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) = positionManager.mint(
			INonfungiblePositionManager.MintParams({
				token0: token0,
				token1: token1,
				tickLower: -887220,
				tickUpper: 887220,
				amount0Desired: amount0Desired,
				amount1Desired: amount1Desired,
				amount0Min: amount0Min,
				amount1Min: amount1Min,
				recipient: address(this),
				deadline: block.timestamp + 1 hours
			})
		);

		uint256 realSilverStakeAmount = silverStakeAmount - (silverStakeToken.balanceOf(address(this)) - balanceSilverStakeTokenBefore);
		TransferHelper.safeTransfer(address(silverStakeToken), msg.sender, silverStakeAmount - realSilverStakeAmount);

		lockPosition(tokenId, token0, token1, msg.sender, realSilverStakeAmount, lockedMonths, pool);

		emit PositionMinted(positionByTokenId[tokenId].lockedPositionId, tokenId, liquidity, amount0, amount1);
	}

	function lockPosition(uint256 _tokenId, address token0, address token1, address _owner, uint256 silverStakeAmount, uint256 lockedMonths, address pool) private {
		require(!positionByTokenId[_tokenId].locked, "Position already locked");
		require(positionManagerERC721.ownerOf(_tokenId) == address(this), "Position not transferred to contract");
	
		positionByTokenId[_tokenId] = PositionInfo({
			lockedPositionId: _incrementLockedPositionId(),
			tokenId: _tokenId,
			owner: _owner,
			token0: token0,
			token1: token1,
			silverStakeAmount: silverStakeAmount,
			locked: true,
			lockedMonths: lockedMonths,
			creationTime: block.timestamp,
			lockedUntil: block.timestamp + (lockedMonths * 30 days),
			gaugeCreated: false,
			pendingUnlock: false,
			pool: pool
		});
		_increaseLockedAgs(silverStakeAmount);
		tokenIdByLockedPositionId[positionByTokenId[_tokenId].lockedPositionId] = _tokenId;
		pendingGaugesTokenId.push(_tokenId);
		userPositions[_owner].push(_tokenId);

		emit PositionLocked(positionByTokenId[_tokenId].lockedPositionId, _tokenId, _owner);
	}

	/**
	 * @notice Unlock position
	 * @param _tokenId The position tokenId
	 */
	function unlockPosition(uint256 _tokenId) public onlyPositionOwner(_tokenId) {
		require(!gaugeManager.isLswLocked(), "Lsw system is locked");
		require(positionByTokenId[_tokenId].locked, "Position not locked");
		require(!positionByTokenId[_tokenId].pendingUnlock, "Position already pending unlock");
		////testing
		////require(block.timestamp >= positionByTokenId[_tokenId].lockedUntil, "Position still locked");

		positionByTokenId[_tokenId].pendingUnlock = true;
		pendingToUnlockTokenId.push(_tokenId);

		emit PositionUnlocked(positionByTokenId[_tokenId].lockedPositionId, _tokenId, msg.sender);
	}

	function unlockAllPositions() public onlyGaugeManager {
		if (pendingToUnlockTokenId.length == 0)
			return;

		uint256 batchSize = 20;
		uint256 elementsToProcess = pendingToUnlockTokenId.length < batchSize ? pendingToUnlockTokenId.length : batchSize;
			
		for (uint256 i = 0; i < elementsToProcess; i++) {
			_unlockPositionAndDesactivateGauge(pendingToUnlockTokenId[0]);
			
			pendingToUnlockTokenId[0] = pendingToUnlockTokenId[pendingToUnlockTokenId.length - 1];
			pendingToUnlockTokenId.pop();
		}

		emit PositionUnlockedAll();
	}

	function _unlockPositionAndDesactivateGauge(uint256 _tokenId) private {
		positionByTokenId[_tokenId].locked = false;
		positionByTokenId[_tokenId].pendingUnlock = false;
		_decreaseLockedAgs(positionByTokenId[_tokenId].silverStakeAmount);
		_desactivateGauge(positionByTokenId[_tokenId].pool);
		_unlockedPool(positionByTokenId[_tokenId].pool);

		positionManagerERC721.safeTransferFrom(address(this), positionByTokenId[_tokenId].owner, _tokenId);
		removePositionFromPendingGauges(_tokenId);

		emit PositionUnlockedAndDesactivatedGauge(positionByTokenId[_tokenId].lockedPositionId, _tokenId, msg.sender);
	}

	/**
	 * @notice Increase lock time
	 * @param _tokenId The position tokenId
	 * @param lockedMonths The additional number of months to lock the position (must be multiple of 3)
	 */
	function increaseLockTime(uint256 _tokenId, uint256 lockedMonths) public onlyPositionOwner(_tokenId) {
		require(positionByTokenId[_tokenId].locked, "Position not locked");
		require(!positionByTokenId[_tokenId].pendingUnlock, "Position pending unlock");
		require(lockedMonths % 3 == 0, "Lock time must be multiple of 3 months");
		require(positionByTokenId[_tokenId].lockedMonths + lockedMonths <= 24, "Maximum lock time is 24 months");

		positionByTokenId[_tokenId].lockedMonths += lockedMonths;
		positionByTokenId[_tokenId].lockedUntil = positionByTokenId[_tokenId].creationTime + (positionByTokenId[_tokenId].lockedMonths * 30 days);

		emit PositionLockIncreased(positionByTokenId[_tokenId].lockedPositionId, _tokenId, positionByTokenId[_tokenId].lockedMonths - lockedMonths, positionByTokenId[_tokenId].lockedMonths);
	}

	function withdrawFees(uint256 _tokenId, INonfungiblePositionManager.CollectParams memory collectParams) public onlyPositionOwner(_tokenId) {
		require(positionByTokenId[_tokenId].locked, "Position not locked");
		require(!positionByTokenId[_tokenId].pendingUnlock, "Position pending unlock");
		require(positionByTokenId[_tokenId].owner == msg.sender, "Not owner of position");

		collectParams.tokenId = positionByTokenId[_tokenId].tokenId;
		collectParams.recipient = positionByTokenId[_tokenId].owner;

		(uint256 amount0, uint256 amount1) = positionManager.collect(collectParams);

		emit PoolFeesWithdrawn(positionByTokenId[_tokenId].lockedPositionId, _tokenId, positionByTokenId[_tokenId].pool, amount0, amount1);
	}


	// ============ Gauge manager functions ============

	/**
	 * @notice Set position as gauge created
	 * @param _tokenId The position tokenId
	 */
	function gaugeCreated(uint256 _tokenId) public onlyGaugeManager {
		positionByTokenId[_tokenId].gaugeCreated = true;
		removePositionFromPendingGauges(_tokenId);

		emit PendingGaugeCreated(_tokenId);
	}

	function gaugeRefused(uint256 _tokenId) public onlyGaugeManager {
		require(!positionByTokenId[_tokenId].gaugeCreated, "Gauge already created");

		positionByTokenId[_tokenId].locked = false;
		_decreaseLockedAgs(positionByTokenId[_tokenId].silverStakeAmount);

		_refundPendingTokens(_tokenId);

		removePositionFromPendingGauges(_tokenId);
		positionManagerERC721.safeTransferFrom(address(this), positionByTokenId[_tokenId].owner, _tokenId);

		emit PendingGaugeRefused(_tokenId);
	}

	/**
	 * @notice Allow user to unlock a pending position before gauge creation
	 * @param _tokenId The position tokenId
	 */
	function unlockPending(uint256 _tokenId) public onlyPositionOwner(_tokenId) {
		require(!gaugeManager.isLswLocked(), "Lsw system is locked");
		require(positionByTokenId[_tokenId].locked, "Position not locked");
		require(!positionByTokenId[_tokenId].gaugeCreated, "Gauge already created");
		require(_isPositionInPendingGauges(_tokenId), "Position not in pending gauges");

		positionByTokenId[_tokenId].locked = false;
		_decreaseLockedAgs(positionByTokenId[_tokenId].silverStakeAmount);

		_refundPendingTokens(_tokenId);

		removePositionFromPendingGauges(_tokenId);
		positionManagerERC721.safeTransferFrom(address(this), positionByTokenId[_tokenId].owner, _tokenId);

		emit PendingGaugeUnlocked(positionByTokenId[_tokenId].lockedPositionId, _tokenId, msg.sender);
	}

	/**
	 * @notice Remove a position from pending gauges
	 * @param _tokenId The position tokenId
	 */
	function removePositionFromPendingGauges(uint256 _tokenId) public onlyOwnerOrGaugeManager {
		uint256 length = pendingGaugesTokenId.length;
		for (uint256 i = 0; i < length; i++) {
			if (pendingGaugesTokenId[i] == _tokenId) {
				if (i < length - 1) {
					pendingGaugesTokenId[i] = pendingGaugesTokenId[length - 1];
				}
				pendingGaugesTokenId.pop();
				break;
			}
		}

		emit PendingGaugeRemoved(_tokenId);
	}

	/**
	 * @notice Purge pending gauges
	 * @dev Remove pending gauges that are older than 2 weeks so that don't flood the pendingGaugesTokenId array
	 */
	function purgePendingGauges() public onlyOwnerOrGaugeManager {
		uint256 length = pendingGaugesTokenId.length;
		uint256 actualTime = block.timestamp;
		uint256 i = 0;

		while (i < length) {
			uint256 tokenId = pendingGaugesTokenId[i];
			if (actualTime - positionByTokenId[tokenId].creationTime >= 2 weeks) {
				positionByTokenId[tokenId].locked = false;
				
				_refundPendingTokens(tokenId);
				
				positionManagerERC721.safeTransferFrom(address(this), positionByTokenId[tokenId].owner, tokenId);

				if (i < length - 1) {
					pendingGaugesTokenId[i] = pendingGaugesTokenId[length - 1];
				}
				pendingGaugesTokenId.pop();
				length--;

				emit PendingGaugePurged(tokenId);
			} else {
				i++;
			}
		}
	}


	// ============ Internal functions ============

	function _incrementLockedPositionId() private returns (uint256) {
		lockedPositionId++;

		return lockedPositionId;
	}

	function _increaseLockedAgs(uint256 silverStakeAmount) private {
		gaugeManager.increaseLockedAgs(silverStakeAmount);
	}

	function _decreaseLockedAgs(uint256 silverStakeAmount) private {
		gaugeManager.decreaseLockedAgs(silverStakeAmount);
	}

	function _desactivateGauge(address pool) private {
		gaugeManager.desactivateGauge(pool);
	}

	function _unlockedPool(address pool) private {
		gaugeManager.unlockedPool(pool);
	}

	function _refundPendingTokens(uint256 _tokenId) private {
		address projectToken = positionByTokenId[_tokenId].token0 == address(silverStakeToken) ? 
			positionByTokenId[_tokenId].token1 : positionByTokenId[_tokenId].token0;
		
		gaugeManager.refundPendingTokens(projectToken, positionByTokenId[_tokenId].owner);
	}


	// ============ Setters ============

	function setPositionManager(address _positionManager) public requireTimelockMain {
		positionManager = INonfungiblePositionManager(_positionManager);
		positionManagerERC721 = IERC721(_positionManager);

		emit PositionManagerSet(_positionManager);
	}

	function setGaugeManager(address _gaugeManager) public requireTimelockMain {
		gaugeManager = IGaugeManager(payable(_gaugeManager));

		emit GaugeManagerSet(_gaugeManager);
	}


	// ============ Getters ============

	function _getPositionInfoByTokenId(uint256 tokenId) public view returns (PositionInfo memory) {
		return positionByTokenId[tokenId];
	}

	function _getPositionInfoByLockedPositionId(uint256 _lockedPositionId) public view returns (PositionInfo memory) {
		return _getPositionInfoByTokenId(tokenIdByLockedPositionId[_lockedPositionId]);
	}

	function _getTokenIdByLockedPositionId(uint256 _lockedPositionId) public view returns (uint256) {
		return tokenIdByLockedPositionId[_lockedPositionId];
	}

	function _getPendingGauges() public view returns (uint256[] memory) {
		return pendingGaugesTokenId;
	}

	function _isGaugeCreated(uint256 tokenId) public view returns (bool) {
		return positionByTokenId[tokenId].gaugeCreated;
	}

	function _getUserPositions(address user) public view returns (uint256[] memory) {
		return userPositions[user];
	}

	function _isPositionInPendingGauges(uint256 _tokenId) public view returns (bool) {
		uint256 length = pendingGaugesTokenId.length;
		for (uint256 i = 0; i < length; i++) {
			if (pendingGaugesTokenId[i] == _tokenId) {
				return true;
			}
		}
		return false;
	}

	// ============ Modifiers ============

	modifier onlyOwnerOrGaugeManager() {
		require(msg.sender == owner() || securityManager.hasContractRole(securityManager.GAUGE_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier onlyGaugeManager () {
		require(securityManager.hasContractRole(securityManager.GAUGE_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier onlyPositionOwner(uint256 _tokenId) {
		require(positionByTokenId[_tokenId].owner == msg.sender, "Only position owner");
		_;
	}

	modifier checkLockMonths(uint256 lockedMonths) {
		require(lockedMonths >= 6, "Minimum lock time is 6 months");
		require(lockedMonths <= 24, "Maximum lock time is 24 months");
		require(lockedMonths % 3 == 0, "Lock time must be multiple of 3 months");
		_;
	}

	
	// ============ Receive function ============

	receive() external payable {}
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.14;

import "./Types.sol";

abstract contract AutomateModuleHelper {
    function _resolverModuleArg(
        address _resolverAddress,
        bytes memory _resolverData
    ) internal pure returns (bytes memory) {
        return abi.encode(_resolverAddress, _resolverData);
    }

    function _proxyModuleArg() internal pure returns (bytes memory) {
        return bytes("");
    }

    function _singleExecModuleArg() internal pure returns (bytes memory) {
        return bytes("");
    }

    function _web3FunctionModuleArg(
        string memory _web3FunctionHash,
        bytes memory _web3FunctionArgsHex
    ) internal pure returns (bytes memory) {
        return abi.encode(_web3FunctionHash, _web3FunctionArgsHex);
    }

    function _timeTriggerModuleArg(uint128 _start, uint128 _interval)
        internal
        pure
        returns (bytes memory)
    {
        bytes memory triggerConfig = abi.encode(_start, _interval);

        return abi.encode(TriggerType.TIME, triggerConfig);
    }

    function _cronTriggerModuleArg(string memory _expression)
        internal
        pure
        returns (bytes memory)
    {
        bytes memory triggerConfig = abi.encode(_expression);

        return abi.encode(TriggerType.CRON, triggerConfig);
    }

    function _eventTriggerModuleArg(
        address _address,
        bytes32[][] memory _topics,
        uint256 _blockConfirmations
    ) internal pure returns (bytes memory) {
        bytes memory triggerConfig = abi.encode(
            _address,
            _topics,
            _blockConfirmations
        );

        return abi.encode(TriggerType.EVENT, triggerConfig);
    }

    function _blockTriggerModuleArg() internal pure returns (bytes memory) {
        bytes memory triggerConfig = abi.encode(bytes(""));

        return abi.encode(TriggerType.BLOCK, triggerConfig);
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.14;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Types.sol";

/**
 * @dev Inherit this contract to allow your smart contract to
 * - Make synchronous fee payments.
 * - Have call restrictions for functions to be automated.
 */
// solhint-disable private-vars-leading-underscore
abstract contract AutomateReady {
    IAutomate public immutable automate;
    address public immutable dedicatedMsgSender;
    address private immutable feeCollector;
    address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /**
     * @dev
     * Only tasks created by _taskCreator defined in constructor can call
     * the functions with this modifier.
     */
    modifier onlyDedicatedMsgSender() {
        require(msg.sender == dedicatedMsgSender, "Only dedicated msg.sender");
        _;
    }

    /**
     * @dev
     * _taskCreator is the address which will create tasks for this contract.
     */
    constructor(address _automate, address _taskCreator) {
        automate = IAutomate(_automate);
        IGelato gelato = IGelato(IAutomate(_automate).gelato());

        feeCollector = gelato.feeCollector();

        address proxyModuleAddress = IAutomate(_automate).taskModuleAddresses(
            Module.PROXY
        );

        address opsProxyFactoryAddress = IProxyModule(proxyModuleAddress)
            .opsProxyFactory();

        (dedicatedMsgSender, ) = IOpsProxyFactory(opsProxyFactoryAddress)
            .getProxyOf(_taskCreator);
    }

    /**
     * @dev
     * Transfers fee to gelato for synchronous fee payments.
     *
     * _fee & _feeToken should be queried from IAutomate.getFeeDetails()
     */
    function _transfer(uint256 _fee, address _feeToken) internal {
        if (_feeToken == ETH) {
            (bool success, ) = feeCollector.call{value: _fee}("");
            require(success, "_transfer: ETH transfer failed");
        } else {
            SafeERC20.safeTransfer(IERC20(_feeToken), feeCollector, _fee);
        }
    }

    function _getFeeDetails()
        internal
        view
        returns (uint256 fee, address feeToken)
    {
        (fee, feeToken) = automate.getFeeDetails();
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.14;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./AutomateReady.sol";
import {AutomateModuleHelper} from "./AutomateModuleHelper.sol";

/**
 * @dev Inherit this contract to allow your smart contract
 * to be a task creator and create tasks.
 */
//solhint-disable const-name-snakecase
//solhint-disable no-empty-blocks
abstract contract AutomateTaskCreator is AutomateModuleHelper, AutomateReady {
    using SafeERC20 for IERC20;

    IGelato1Balance public constant gelato1Balance =
        IGelato1Balance(0x7506C12a824d73D9b08564d5Afc22c949434755e);

    constructor(address _automate) AutomateReady(_automate, address(this)) {}

    function _depositFunds1Balance(
        uint256 _amount,
        address _token,
        address _sponsor
    ) internal {
        if (_token == ETH) {
            ///@dev Only deposit ETH on goerli for now.
            require(block.chainid == 5, "Only deposit ETH on goerli");
            gelato1Balance.depositNative{value: _amount}(_sponsor);
        } else {
            ///@dev Only deposit USDC on polygon for now.
            require(
                block.chainid == 137 &&
                    _token ==
                    address(0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174),
                "Only deposit USDC on polygon"
            );
            IERC20(_token).approve(address(gelato1Balance), _amount);
            gelato1Balance.depositToken(_sponsor, _token, _amount);
        }
    }

    function _createTask(
        address _execAddress,
        bytes memory _execDataOrSelector,
        ModuleData memory _moduleData,
        address _feeToken
    ) internal returns (bytes32) {
        return
            automate.createTask(
                _execAddress,
                _execDataOrSelector,
                _moduleData,
                _feeToken
            );
    }

    function _cancelTask(bytes32 _taskId) internal {
        automate.cancelTask(_taskId);
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.12;

enum Module {
    RESOLVER,
    DEPRECATED_TIME,
    PROXY,
    SINGLE_EXEC,
    WEB3_FUNCTION,
    TRIGGER
}

enum TriggerType {
    TIME,
    CRON,
    EVENT,
    BLOCK
}

struct ModuleData {
    Module[] modules;
    bytes[] args;
}

interface IAutomate {
    function createTask(
        address execAddress,
        bytes calldata execDataOrSelector,
        ModuleData calldata moduleData,
        address feeToken
    ) external returns (bytes32 taskId);

    function cancelTask(bytes32 taskId) external;

    function getFeeDetails() external view returns (uint256, address);

    function gelato() external view returns (address payable);

    function taskModuleAddresses(Module) external view returns (address);
}

interface IProxyModule {
    function opsProxyFactory() external view returns (address);
}

interface IOpsProxyFactory {
    function getProxyOf(address account) external view returns (address, bool);
}

interface IGelato1Balance {
    function depositNative(address _sponsor) external payable;

    function depositToken(
        address _sponsor,
        address _token,
        uint256 _amount
    ) external;
}

interface IGelato {
    function feeCollector() external view returns (address);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface INonfungiblePositionManager {
    struct MintParams {
        address token0;
        address token1;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

	struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

	struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

	 struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

	function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);

    function mint(
        MintParams calldata params
    ) external payable returns (
        uint256 tokenId, 
        uint128 liquidity, 
        uint256 amount0, 
        uint256 amount1
    );

	function increaseLiquidity(
        IncreaseLiquidityParams calldata params
    ) external payable returns (
		uint128 liquidity,
		uint256 amount0,
		uint256 amount1
	);

    function decreaseLiquidity(
        DecreaseLiquidityParams calldata params
    ) external payable returns (
		uint256 amount0,
		uint256 amount1
	);

    function collect(
        CollectParams calldata params
    ) external payable returns (
        uint256 amount0, 
        uint256 amount1
    );

	function positions(
        uint256 tokenId
    ) external view returns (
		uint88 nonce,
		address operator,
		address token0,
		address token1,
		int24 tickLower,
		int24 tickUpper,
		uint128 liquidity,
		uint256 feeGrowthInside0LastX128,
		uint256 feeGrowthInside1LastX128,
		uint128 tokensOwed0,
		uint128 tokensOwed1
    );

    function factory() external returns (address);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface ISFC {
    error StakeIsFullySlashed();

	function createValidator(bytes calldata pubkey) external payable;

	function getValidatorID(address auth) external view returns (uint256);

    function currentEpoch() external view returns (uint256);

    function getStake(address, uint256) external view returns (uint256);

    function delegate(uint256 toValidatorID) external payable;

    function undelegate(uint256 toValidatorID, uint256 wrID, uint256 amount) external;

    function withdraw(uint256 toValidatorID, uint256 wrID) external;

    function pendingRewards(address delegator, uint256 toValidatorID) external view returns (uint256);

    function claimRewards(uint256 toValidatorID) external;

    function getSelfStake(uint256 validatorID) external view returns (uint256);

    function isSlashed(uint256 validatorID) external view returns (bool);

    function slashingRefundRatio(uint256 validatorID) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

/**
 * @title ITimelock
 * @author github.com/SifexPro
 * @notice Interface for timelock contracts
 */
interface ITimelock {
    /**
     * @notice Check if the timelock is active and return the delay
     * @return activated Whether the timelock is activated
     * @return delay The minimum delay in seconds
     */
    function checkTimelock() external view returns (bool activated, uint256 delay);
    
    /**
     * @notice Schedule a transaction
     * @param target Address of the contract to call
     * @param value Amount of native tokens to send with the call
     * @param data Encoded function call data (function signature + parameters)
     * @param predecessor Transaction hash that must be executed before this one (0 for no dependency)
     * @param salt Random value to ensure uniqueness of the transaction hash
     */
    function schedule(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) external;
    
    /**
     * @notice Execute a scheduled transaction
     * @param target Address of the contract to call
     * @param value Amount of native tokens to send
     * @param data Encoded function call data
     * @param predecessor Transaction hash dependency
     * @param salt Random value used when scheduling
     */
    function execute(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) external payable;
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IWrappedNative {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-periphery
library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)
        );
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers NativeToken to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferNative(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "./SilverLswManager.sol";
import "./SilverLswTaskManager.sol";

/**
 * @title GaugeTaskExecutor
 * @author github.com/SifexPro
 * @notice This contract is dedicated to Gelato tasks related to a specific gauge
 */
contract GaugeTaskExecutor {
    SilverLswManager public immutable manager;
    SilverLswTaskManager public immutable taskManager;
    address public immutable poolGauge;

    enum TaskType { SNAPSHOT, BREAK_LIQUIDITY }

    constructor(address _poolGauge, address _manager) {
        require(_poolGauge != address(0), "Zero address");
        require(_manager != address(0), "Zero manager address");
        manager = SilverLswManager(payable(_manager));
        taskManager = SilverLswTaskManager(payable(msg.sender));
        poolGauge = _poolGauge;
    }

    function execute(TaskType taskType) external {
        require(msg.sender == taskManager.dedicatedMsgSender(), "Unauthorized executor caller");

        if (taskType == TaskType.SNAPSHOT) {
            manager.calcVotedGaugeData(poolGauge);
        } else {
            manager.breakLiquidityAndCompound(poolGauge);
        }
    }
}

File 36 of 41 : SilverLswManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {TransferHelper} from "../libraries/TransferHelper.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

import {IWrappedNative} from "../interfaces/IWrappedNative.sol";
import {SilverStake} from "../SilverStake/SilverStake.sol";
import {GaugeManager, GaugeInfo} from "../Gauge/GaugeManager.sol";
import {SilverVoteLSW} from "./SilverVoteLSW.sol";
import {SilverValidatorAuth} from "../Validator/SilverValidatorAuth.sol";
import {ContractPermissionManager} from "../Security/ContractPermissionManager.sol";
import {TimelockProtection} from "../Security/TimelockProtection.sol";
import {SilverLswTaskManager} from "./SilverLswTaskManager.sol";
import {GaugeTaskExecutor} from "./GaugeTaskExecutor.sol";

// ============ Interfaces ============
interface IAlgebraSwapRouter {
	function exactInput(ExactInputParams memory data) external payable returns (uint256);
}

interface IAlgebraPool {
	function token0() external view returns (address);
	function token1() external view returns (address);
}

// ============ Structs ============
struct ExactInputParams {
	bytes path;
	address recipient;
	uint256 deadline;
	uint256 amountIn;
	uint256 amountOutMinimum;
}

struct LswSystemTaskIds {
	bytes32 clearLswSystemTaskId;
	bytes32 syncGaugesRewardsCalcTaskId;
	bytes32 breakLiquidityAndCompoundTaskId;
}

struct LswSystemGaugeSaveData {
	uint256 gaugesBrokenLiquidityRewards;
	address gaugeExecutor;
	bytes32 snapshotTaskId;
	bytes32 rewardsReinjectionTaskId;
	bytes32 breakLiquidityAndCompoundCallTaskId;
}

struct LswSystemData {
	bool isLswLocked;
	GaugeData[] gauges;
	mapping(address => LswSystemGaugeSaveData) gaugesSaveData;
	string rewardsReinjectionScriptCID;
	LswSystemTaskIds taskIds;
	uint256 lastExecutionTimestamp;
}

struct UserData {
	address user;
	uint256 votingPower;
	uint256 votingPowerPercentage;
}

struct GaugeData {
	address poolGauge;
	address projectToken;
	UserData[] users;
	uint256 totalVoters;
	uint256 gaugeVotingPower;
	uint256 gaugeVotingPowerPercentage;
	uint256 wrappedNativeAmount;
}

struct SyncLswSystemData {
	uint256 syncTime;
	uint256 lastSyncTimestamp;
	uint256 nextSyncTimestamp;
	bytes32 lswSystemSyncTaskId;
	bytes32 syncGaugesRewardsTaskId;
}

/**
 * @title SilverLswManager
 * @author github.com/SifexPro
 * @notice This contract is used to manage the LSW system
 */
contract SilverLswManager is Ownable2Step, TimelockProtection {
	// ============ Constants ============
	uint256 private constant PRECISION = 1e18;
	uint256 private constant MAX_PERCENTAGE = 10000;

	// ============ State Variables ============
	ContractPermissionManager public immutable securityManager;
	GaugeManager public gaugeManager;
	SilverStake public silverStake;
	SilverVoteLSW public silverVoteLSW;
	SilverValidatorAuth public validatorAuth;
	IAlgebraSwapRouter public swapRouter;
	address public immutable wrappedNativeToken;
	SilverLswTaskManager public taskManager;

	LswSystemData public lswSystemData;
	SyncLswSystemData public syncLswSystemData;
	mapping(address => address) public gaugeExecutors;
	uint256 public totalRewardsAmount;
	
	// ============ Events for rewards ============
	event RewardsClaimed(uint256 nativeAmount);
	event RewardsReinjected(address poolGauge, uint256 wrappedNativeAmount, uint256 projectTokenAmountClaimed);
	
	// ============ Events for gauges ============
	event GaugeDataCalculated(uint32 gaugeIndex, address poolGauge);
	event GaugeRewardsCalculated(uint32 gaugeIndex, uint256 wrappedNativeAmount);
	event GaugesRewardsExecuted(uint256 timestamp);
	event GaugeSynced(address poolGauge, address executor);
	event SyncGaugesRewardsStarted(uint256 timestamp);
	event GaugesRewardsSynced(uint256 timestamp);
	
	// ============ Events for system sync ============
	event SyncLswSystemStarted(uint256 syncTime, uint256 startTimestamp);
	event SyncLswSystemStopped(uint256 stopTimestamp);
	event LswSystemSynced(uint256 timestamp);
	event LswSystemCleared();
	event StartBreakLiquidityAndCompound(uint256 timestamp);
	event BreakLiquidityAndCompound(address poolGauge, uint256 wrappedNativeAmount, uint256 projectTokenAmount);
	event BrokenLiquidityRewardsDistributed(address poolGauge, address user, uint256 amount);
	event BrokenLiquidityRewardsSaved(address poolGauge, uint256 amount);
	event Compounding(uint256 wrappedNativeAmount);

	// ============ Events for withdrawals ============
	event WithdrawnNative(address indexed to, uint256 amount);
	event WithdrawnToken(address indexed token, address to, uint256 amount);
	
	// ============ Events for setters ============
	event LswTaskManagerSet(address indexed newLswTaskManager);
	event GaugeManagerSet(address indexed newGaugeManager);
	event GaugeExecutorFactorySet(address indexed newGaugeExecutorFactory);
	event SilverVoteLSWSet(address indexed newSilverVoteLSW);
	event SilverStakeSet(address indexed newSilverStake);
	event SilverValidatorAuthSet(address indexed newSilverValidatorAuth);
	event SwapRouterSet(address indexed newSwapRouter);

	// ============ Events for system ============
	event LswSystemManuallyLocked(uint256 timestamp);
	event LswSystemManuallyUnlocked(uint256 timestamp);

	// ============ Constructor ============
	constructor(
		address _securityManager,
		address _gaugeManager, 
		address _silverStake, 
		address _validatorAuth, 
		address _silverVoteLSW, 
		string memory _rewardsReinjectionScriptCID, 
		address _wrappedNativeToken, 
		address _swapRouter,
		address _timelockMain,
		address _timelockAdmin
	) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
		securityManager = ContractPermissionManager(_securityManager);
		gaugeManager = GaugeManager(payable(_gaugeManager));
		silverStake = SilverStake(payable(_silverStake));
		if (_validatorAuth != address(0))
			validatorAuth = SilverValidatorAuth(payable(_validatorAuth));
		else
			validatorAuth = SilverValidatorAuth(payable(address(0)));
		silverVoteLSW = SilverVoteLSW(_silverVoteLSW);
		lswSystemData.rewardsReinjectionScriptCID = _rewardsReinjectionScriptCID;
		wrappedNativeToken = _wrappedNativeToken;
		swapRouter = IAlgebraSwapRouter(_swapRouter);
	}

	// ============ Sync System Functions ============

	function syncLswSystem() public onlyLswTaskManagerGelato {
		////testing
		////require(block.timestamp >= syncLswSystemData.nextSyncTimestamp - 10 minutes, "Too early to sync");
		
		syncLswSystemData.lastSyncTimestamp = block.timestamp;
		syncLswSystemData.nextSyncTimestamp = block.timestamp + syncLswSystemData.syncTime;

		lswSystemData.isLswLocked = true;

		lswSystemData.taskIds.syncGaugesRewardsCalcTaskId = taskManager.createTaskSyncGaugeRewardsCalc(syncLswSystemData.lastSyncTimestamp);
		lswSystemData.taskIds.breakLiquidityAndCompoundTaskId = taskManager.createTaskStartBreakLiquidityAndCompound(syncLswSystemData.lastSyncTimestamp);
		lswSystemData.taskIds.clearLswSystemTaskId = taskManager.createTaskClearLswSystem(syncLswSystemData.lastSyncTimestamp);

		emit LswSystemSynced(block.timestamp);
	}

	function startSyncSystem(uint256 _syncTime) public requireTimelockAdmin {
		////testing
		////require(_syncTime == 0 || _syncTime > 10 minutes, "Invalid sync time");

		if (lswSystemData.isLswLocked) {
			delete lswSystemData.gauges;
			totalRewardsAmount = 0;
			lswSystemData.isLswLocked = false;
		}

		syncLswSystemData.syncTime = _syncTime;
		syncLswSystemData.lastSyncTimestamp = block.timestamp;
		syncLswSystemData.nextSyncTimestamp = block.timestamp + _syncTime;
		
		// Cancel all existing tasks
		bytes32[] memory tasksToCancel = new bytes32[](5);
		tasksToCancel[0] = syncLswSystemData.lswSystemSyncTaskId;
		tasksToCancel[1] = syncLswSystemData.syncGaugesRewardsTaskId;
		tasksToCancel[2] = lswSystemData.taskIds.clearLswSystemTaskId;
		tasksToCancel[3] = lswSystemData.taskIds.syncGaugesRewardsCalcTaskId;
		tasksToCancel[4] = lswSystemData.taskIds.breakLiquidityAndCompoundTaskId;
		taskManager.cancelMultipleTasks(tasksToCancel);

		if (_syncTime != 0) {
			syncLswSystemData.lswSystemSyncTaskId = taskManager.createTaskSyncSystem(
				syncLswSystemData.nextSyncTimestamp,
				syncLswSystemData.syncTime
			);
			syncLswSystemData.syncGaugesRewardsTaskId = taskManager.createTaskGaugesRewards();
			emit SyncLswSystemStarted(_syncTime, block.timestamp);
		} else {
			emit SyncLswSystemStopped(block.timestamp);
		}
	}

	function syncGaugeRewardsCalc() public onlyLswTaskManagerGelato {
		lswSystemData.taskIds.syncGaugesRewardsCalcTaskId = bytes32(0);
		emit SyncGaugesRewardsStarted(block.timestamp);
	}

	function clearLswSystem() public onlyLswTaskManagerGelato {
		require(lswSystemData.isLswLocked, "LSW is not locked");

		// Clear vote info and update rates and unlock all positions
		silverVoteLSW.clearVoteInfo();
		silverStake.updateRateForOneToken();
		gaugeManager.unlockAllPositions();

		// Clear system data
		delete lswSystemData.gauges;
		totalRewardsAmount = 0;
		lswSystemData.isLswLocked = false;
		lswSystemData.taskIds.clearLswSystemTaskId = bytes32(0);
		lswSystemData.taskIds.syncGaugesRewardsCalcTaskId = bytes32(0);
		lswSystemData.taskIds.breakLiquidityAndCompoundTaskId = bytes32(0);

		lswSystemData.lastExecutionTimestamp = block.timestamp;

		emit LswSystemCleared();
	}


	// ============ Gauge Management Functions ============

	function syncNewGauge(address _poolGauge) public onlyGaugeManager {
		address executor = taskManager.getOrCreateExecutor(_poolGauge);
		lswSystemData.gaugesSaveData[_poolGauge].snapshotTaskId = taskManager.createTaskGaugeSnapshot(executor);
		lswSystemData.gaugesSaveData[_poolGauge].rewardsReinjectionTaskId = taskManager.createTaskGaugeRewardsReinjection(
			_poolGauge,
			getGaugeProjectToken(_poolGauge),
			lswSystemData.rewardsReinjectionScriptCID,
			wrappedNativeToken
		);
		lswSystemData.gaugesSaveData[_poolGauge].breakLiquidityAndCompoundCallTaskId = taskManager.createTaskBreakLiquidityAndCompoundCall(executor);
		lswSystemData.gaugesSaveData[_poolGauge].gaugeExecutor = executor;
		
		emit GaugeSynced(_poolGauge, executor);
	}

	function calcVotedGaugeData(address _poolGauge) public gaugeTaskExecutorOnly(_poolGauge) {
		require(isGaugeVoted(_poolGauge), "Gauge not voted");

		address projectToken = getGaugeProjectToken(_poolGauge);

		lswSystemData.gauges.push(GaugeData({
			poolGauge: _poolGauge,
			projectToken: projectToken,
			users: new UserData[](0),
			gaugeVotingPower: 0,
			gaugeVotingPowerPercentage: 0,
			totalVoters: 0,
			wrappedNativeAmount: 0
		}));

		uint32 gaugeIndex = uint32(lswSystemData.gauges.length - 1);
		uint256 gaugeVotingPower = 0;
		address[] memory gaugeVoters = silverVoteLSW.getGaugeVoters(_poolGauge);

		unchecked {
			for (uint32 i = 0; i < gaugeVoters.length; i++) {
				address user = gaugeVoters[i];
				uint256 userVotingPower = gaugeManager.getUserVotingPower(user);
				
				gaugeVotingPower += userVotingPower;

				lswSystemData.gauges[gaugeIndex].users.push(UserData({
					user: user,
					votingPower: userVotingPower,
					votingPowerPercentage: 0
				}));

				lswSystemData.gauges[gaugeIndex].totalVoters++;
			}
		}

		lswSystemData.gauges[gaugeIndex].gaugeVotingPower = gaugeVotingPower;
		calcGaugeUserPercentages(gaugeIndex);

		emit GaugeDataCalculated(gaugeIndex, _poolGauge);
	}

	function calcGaugeUserPercentages(uint32 gaugeIndex) private {
		GaugeData storage gauge = lswSystemData.gauges[gaugeIndex];
		require(gauge.gaugeVotingPower > 0, "No voting power in gauge");

		unchecked {
			for (uint32 i = 0; i < gauge.users.length; i++) {
				gauge.users[i].votingPowerPercentage = 
					(gauge.users[i].votingPower * PRECISION) / gauge.gaugeVotingPower;
			}
		}
	}


	// ============ Rewards Management Functions ============

	function executeSyncGaugesRewards() public onlyLswTaskManagerGelato {
		require(lswSystemData.isLswLocked, "LSW is not locked");

		claimRewards();
		calcGaugesPercentages();
		calcGaugesRewards();

		emit GaugesRewardsSynced(block.timestamp);
	}

	function claimRewards() private {
		uint256 nativeAmountBefore = address(this).balance;
		uint256 wrappedNativeAmountBefore = IERC20(wrappedNativeToken).balanceOf(address(this));

		silverStake._claimRewards();
		if (address(validatorAuth) != address(0))
			validatorAuth._claimRewards();
		
		uint256 nativeAmountClaimed = address(this).balance - nativeAmountBefore;
		IWrappedNative(wrappedNativeToken).deposit{value: nativeAmountClaimed}();
		uint256 wrappedNativeAmountClaimed = IERC20(wrappedNativeToken).balanceOf(address(this)) - wrappedNativeAmountBefore;

		totalRewardsAmount = wrappedNativeAmountClaimed / 2;

		emit RewardsClaimed(wrappedNativeAmountClaimed);
	}

	function calcGaugesRewards() private {
		unchecked {
			for (uint32 i = 0; i < lswSystemData.gauges.length; i++) {
				uint256 gaugePercentage = lswSystemData.gauges[i].gaugeVotingPowerPercentage;
				
				lswSystemData.gauges[i].wrappedNativeAmount = 
					(totalRewardsAmount * gaugePercentage) / PRECISION;

				emit GaugeRewardsCalculated(i, lswSystemData.gauges[i].wrappedNativeAmount);
			}
		}
	}

	function calcGaugesPercentages() private {
		uint256 totalVotingPower = 0;

		unchecked {
			for (uint32 i = 0; i < lswSystemData.gauges.length; i++) {
				totalVotingPower += lswSystemData.gauges[i].gaugeVotingPower;
			}
		}

		unchecked {
			for (uint32 i = 0; i < lswSystemData.gauges.length; i++) {
				lswSystemData.gauges[i].gaugeVotingPowerPercentage = 
					(lswSystemData.gauges[i].gaugeVotingPower * PRECISION) / totalVotingPower;
			}
		}
	}

	function reinjectRewards(
		address _gaugePool, 
		address _projectToken, 
		uint256 wrappedNativeAmount, 
		ExactInputParams memory swapToProjectTokenArgs
	) public onlyLswTaskManagerGelato {
		require(_gaugePool != address(0), "Zero address");
		require(_projectToken != address(0), "Zero address");
		require(wrappedNativeAmount > 0, "Zero amount");
		require(isGaugeVoted(_gaugePool), "Gauge not voted");
		require(wrappedNativeAmount == getGaugeRewards(_gaugePool), "Wrong wrappedNativeAmount");
		require(_projectToken == getGaugeProjectToken(_gaugePool), "Wrong projectToken");

		swapToProjectTokenArgs.recipient = address(this);
		swapToProjectTokenArgs.amountIn = wrappedNativeAmount;
		
		TransferHelper.safeApprove(address(wrappedNativeToken), address(swapRouter), wrappedNativeAmount);
		
		uint256 projectTokenAmountBefore = IERC20(address(_projectToken)).balanceOf(address(this));
		swapRouter.exactInput(swapToProjectTokenArgs);
		uint256 projectTokenAmountClaimed = IERC20(address(_projectToken)).balanceOf(address(this)) - projectTokenAmountBefore;

		TransferHelper.safeApprove(_projectToken, address(gaugeManager), projectTokenAmountClaimed);
		TransferHelper.safeApprove(wrappedNativeToken, address(gaugeManager), wrappedNativeAmount);

		uint256 amount0Desired;
		uint256 amount1Desired;
		
		if (IAlgebraPool(gaugeManager.getGaugeInfo(_gaugePool).wrappedNativePool).token0() == wrappedNativeToken) {
			amount0Desired = wrappedNativeAmount;
			amount1Desired = projectTokenAmountClaimed;
		} else {
			amount0Desired = projectTokenAmountClaimed;
			amount1Desired = wrappedNativeAmount;
		}
		
		gaugeManager.addLiquidityInWrappedPool(_gaugePool, amount0Desired, amount1Desired, 10);

		emit RewardsReinjected(_gaugePool, wrappedNativeAmount, projectTokenAmountClaimed);
	}


	// ============ Liquidity Management Functions ============

	function startBreakLiquidityAndCompound() public onlyLswTaskManagerGelato {
		lswSystemData.taskIds.breakLiquidityAndCompoundTaskId = bytes32(0);
		emit StartBreakLiquidityAndCompound(block.timestamp);
	}

	function breakLiquidityAndCompound(address _poolGauge) public gaugeTaskExecutorOnly(_poolGauge) {
		require(_poolGauge != address(0), "Zero address");
		require(gaugeManager.getGaugeInfo(_poolGauge).active, "Gauge not active");
		
		address projectToken = getGaugeProjectToken(_poolGauge);
		
		uint256 balanceWrappedNativeBefore = IERC20(wrappedNativeToken).balanceOf(address(this));
		uint256 balanceProjectTokenBefore = IERC20(projectToken).balanceOf(address(this));
		
		gaugeManager.removeLiquidityFromWrappedPool(_poolGauge);
		
		uint256 wrappedNativeAmount = IERC20(wrappedNativeToken).balanceOf(address(this)) - balanceWrappedNativeBefore;
		uint256 projectTokenAmount = IERC20(projectToken).balanceOf(address(this)) - balanceProjectTokenBefore;

		if (wrappedNativeAmount > 0) {
			_handleCompounding(wrappedNativeAmount);
		}

		if (projectTokenAmount > 0) {
			_handleBrokenLiquidityRewards(_poolGauge, projectToken, projectTokenAmount + getGaugesBrokenLiquidityRewards(_poolGauge));
		}

		emit BreakLiquidityAndCompound(_poolGauge, wrappedNativeAmount, projectTokenAmount);
	}

	function _handleBrokenLiquidityRewards(
		address _poolGauge, 
		address _projectToken, 
		uint256 _projectTokenAmount
	) private {
		(bool exists, uint32 gaugeIndex) = _getGaugeIndex(_poolGauge);
		
		if (exists) {
			GaugeData storage gauge = lswSystemData.gauges[gaugeIndex];
			require(gauge.gaugeVotingPower > 0, "No voting power in gauge");

			unchecked {
				for (uint32 i = 0; i < gauge.users.length; i++) {
					uint256 userReward = (_projectTokenAmount * gauge.users[i].votingPowerPercentage) / PRECISION;
					if (userReward > 0) {
						TransferHelper.safeTransfer(_projectToken, gauge.users[i].user, userReward);
					}
					emit BrokenLiquidityRewardsDistributed(_poolGauge, gauge.users[i].user, userReward);
				}
			}
		} else {
			lswSystemData.gaugesSaveData[_poolGauge].gaugesBrokenLiquidityRewards += _projectTokenAmount;
			emit BrokenLiquidityRewardsSaved(_poolGauge, _projectTokenAmount);
		}
	}

	function _handleCompounding(uint256 wrappedNativeAmount) private {
		TransferHelper.safeTransfer(wrappedNativeToken, address(silverStake), wrappedNativeAmount);
		silverStake.compounding(wrappedNativeAmount);
		emit Compounding(wrappedNativeAmount);
	}


	// ============ Setters ============

	function setLswTaskManager(address _lswTaskManager) public requireTimelockMain {
		taskManager = SilverLswTaskManager(payable(_lswTaskManager));
		emit LswTaskManagerSet(_lswTaskManager);
	}

	function setGaugeManager(address _gaugeManager) public requireTimelockMain {
		gaugeManager = GaugeManager(payable(_gaugeManager));
		emit GaugeManagerSet(_gaugeManager);
	}

	function setSilverVoteLSW(address _silverVoteLSW) public requireTimelockMain {
		silverVoteLSW = SilverVoteLSW(payable(_silverVoteLSW));
		emit SilverVoteLSWSet(_silverVoteLSW);
	}

	function setSilverStake(address _silverStake) public requireTimelockMain {
		silverStake = SilverStake(payable(_silverStake));
		emit SilverStakeSet(_silverStake);
	}

	function setSilverValidatorAuth(address _silverValidatorAuth) public requireTimelockMain {
		validatorAuth = SilverValidatorAuth(payable(_silverValidatorAuth));
		emit SilverValidatorAuthSet(_silverValidatorAuth);
	}

	function setSwapRouter(address _swapRouter) public requireTimelockAdmin {
		swapRouter = IAlgebraSwapRouter(_swapRouter);
		emit SwapRouterSet(_swapRouter);
	}

	function cancelTaskGauge(address _poolGauge) public onlyGaugeManager {
		if (gaugeExecutors[_poolGauge] == address(0)) return;

		bytes32[] memory tasksToCancel = new bytes32[](3);
		tasksToCancel[0] = lswSystemData.gaugesSaveData[_poolGauge].snapshotTaskId;
		tasksToCancel[1] = lswSystemData.gaugesSaveData[_poolGauge].rewardsReinjectionTaskId;
		tasksToCancel[2] = lswSystemData.gaugesSaveData[_poolGauge].breakLiquidityAndCompoundCallTaskId;
		taskManager.cancelMultipleTasks(tasksToCancel);

		lswSystemData.gaugesSaveData[_poolGauge].snapshotTaskId = bytes32(0);
		lswSystemData.gaugesSaveData[_poolGauge].rewardsReinjectionTaskId = bytes32(0);
		lswSystemData.gaugesSaveData[_poolGauge].breakLiquidityAndCompoundCallTaskId = bytes32(0);
	}

	function setGaugeExecutor(address _poolGauge, address _executor) external onlyLswTaskManager {
		gaugeExecutors[_poolGauge] = _executor;
	}

	function resetTaskId(bytes32 taskId) external onlyLswTaskManager {
		if (taskId == syncLswSystemData.lswSystemSyncTaskId)
			syncLswSystemData.lswSystemSyncTaskId = bytes32(0);
		if (taskId == syncLswSystemData.syncGaugesRewardsTaskId)
			syncLswSystemData.syncGaugesRewardsTaskId = bytes32(0);
		if (taskId == lswSystemData.taskIds.clearLswSystemTaskId)
			lswSystemData.taskIds.clearLswSystemTaskId = bytes32(0);
		if (taskId == lswSystemData.taskIds.syncGaugesRewardsCalcTaskId)
			lswSystemData.taskIds.syncGaugesRewardsCalcTaskId = bytes32(0);
		if (taskId == lswSystemData.taskIds.breakLiquidityAndCompoundTaskId)
			lswSystemData.taskIds.breakLiquidityAndCompoundTaskId = bytes32(0);
	}

	function cancelTask(bytes32 taskId) external onlyOwner {
		taskManager.cancelTask(taskId);
	}

	// ============ Getters ============
	
	function getGaugeProjectToken(address _poolGauge) public view returns (address projectToken) {
		projectToken = gaugeManager.getProjectToken(_poolGauge);
	}

	function getGaugeData(address _poolGauge) public view returns (address poolGauge, address projectToken, uint256 totalVoters, uint256 gaugeVotingPower, uint256 gaugeVotingPowerPercentage, uint256 wrappedNativeAmount) {
		(bool voted, uint32 index) = _getGaugeIndex(_poolGauge);
		require(voted, "Gauge not voted");

		return (lswSystemData.gauges[index].poolGauge, lswSystemData.gauges[index].projectToken, lswSystemData.gauges[index].totalVoters, lswSystemData.gauges[index].gaugeVotingPower, lswSystemData.gauges[index].gaugeVotingPowerPercentage, lswSystemData.gauges[index].wrappedNativeAmount);
	}

	function getGaugeUserData(address _poolGauge) public view returns (UserData[] memory userData) {
		(bool voted, uint32 index) = _getGaugeIndex(_poolGauge);
		require(voted, "Gauge not voted");

		return lswSystemData.gauges[index].users;
	}

	function _getGaugeIndex(address _poolGauge) private view returns (bool voted, uint32 index) {
		if (_poolGauge == address(0)) {
			return (false, 0);
		}
		
		unchecked {
			for (uint32 i = 0; i < lswSystemData.gauges.length; i++) {
				if (lswSystemData.gauges[i].poolGauge == _poolGauge) {
					return (true, i);
				}
			}
		}
		return (false, 0);
	}

	function getGaugeRewards(address _poolGauge) public view returns (uint256 wrappedNativeAmount) {
		(bool voted, uint32 index) = _getGaugeIndex(_poolGauge);
		require(voted, "Gauge not voted");

		return lswSystemData.gauges[index].wrappedNativeAmount;
	}

	function isGaugeVoted(address _poolGauge) public view returns (bool) {
		return silverVoteLSW._isGaugeVoted(_poolGauge);
	}

	function getLswSystemData() public view returns (
		bool _isLswLocked,
		GaugeData[] memory _gauges,
		string memory _rewardsReinjectionScriptCID,
		uint256 _lastExecutionTimestamp
	) {
		return (
			lswSystemData.isLswLocked,
			lswSystemData.gauges,
			lswSystemData.rewardsReinjectionScriptCID,
			lswSystemData.lastExecutionTimestamp
		);
	}

	function getLswSystemTaskIds() public view returns (bytes32 clearLswSystemTaskId, bytes32 syncGaugesRewardsCalcTaskId, bytes32 breakLiquidityAndCompoundTaskId) {
		return (lswSystemData.taskIds.clearLswSystemTaskId, lswSystemData.taskIds.syncGaugesRewardsCalcTaskId, lswSystemData.taskIds.breakLiquidityAndCompoundTaskId);
	}

	function getLswSystemGaugesSaveData(address _poolGauge) public view returns (uint256 gaugesBrokenLiquidityRewards, address gaugeExecutor, bytes32 snapshotTaskId, bytes32 rewardsReinjectionTaskId, bytes32 breakLiquidityAndCompoundCallTaskId) {
		return (lswSystemData.gaugesSaveData[_poolGauge].gaugesBrokenLiquidityRewards, lswSystemData.gaugesSaveData[_poolGauge].gaugeExecutor, lswSystemData.gaugesSaveData[_poolGauge].snapshotTaskId, lswSystemData.gaugesSaveData[_poolGauge].rewardsReinjectionTaskId, lswSystemData.gaugesSaveData[_poolGauge].breakLiquidityAndCompoundCallTaskId);
	}

	function getLastExecutionTimestamp() public view returns (uint256) {
		return lswSystemData.lastExecutionTimestamp;
	}

	function isLswLocked() public view returns (bool) {
		return lswSystemData.isLswLocked;
	}

	/**
	 * @notice Lock the LSW system manually
	 * @dev Only callable by SilverStake during critical operations like validator transfer
	 */
	function lockLswSystem() external onlySilverStake {
		lswSystemData.isLswLocked = true;
		emit LswSystemManuallyLocked(block.timestamp);
	}

	/**
	 * @notice Unlock the LSW system manually
	 * @dev Only callable by SilverStake after critical operations are completed
	 */
	function unlockLswSystem() external onlySilverStake {
		lswSystemData.isLswLocked = false;
		emit LswSystemManuallyUnlocked(block.timestamp);
	}

	/**
	 * @notice Stop all LSW system tasks for maintenance operations
	 * @dev Only callable by SilverStake during critical operations like validator transfer
	 */
	function stopLswSystemForMaintenance() external onlySilverStake {
		bytes32[] memory tasksToCancel = new bytes32[](5);
		tasksToCancel[0] = syncLswSystemData.lswSystemSyncTaskId;
		tasksToCancel[1] = syncLswSystemData.syncGaugesRewardsTaskId;
		tasksToCancel[2] = lswSystemData.taskIds.clearLswSystemTaskId;
		tasksToCancel[3] = lswSystemData.taskIds.syncGaugesRewardsCalcTaskId;
		tasksToCancel[4] = lswSystemData.taskIds.breakLiquidityAndCompoundTaskId;
		taskManager.cancelMultipleTasks(tasksToCancel);

		syncLswSystemData.syncTime = 0;
		syncLswSystemData.lastSyncTimestamp = block.timestamp;
		syncLswSystemData.nextSyncTimestamp = 0;

		emit SyncLswSystemStopped(block.timestamp);
	}

	function getGaugesBrokenLiquidityRewards(address _poolGauge) public view returns (uint256) {
		return lswSystemData.gaugesSaveData[_poolGauge].gaugesBrokenLiquidityRewards;
	}

	function getUserVotingPower(address user) public view returns (uint256) {
		return gaugeManager.getUserVotingPower(user);
	}

	function getNextSyncTimestamp() public view returns (uint256) {
		return syncLswSystemData.nextSyncTimestamp;
	}


	// ============ Owner Functions ============

	function withdrawNative(address _to) public requireTimelockAdmin {
		uint256 balance = address(this).balance;
		require(balance > 0, "No Native to withdraw");

		address payable _tresory = payable(_to);
		(bool success, ) = _tresory.call{value:balance}("");
		require(success, "Transaction failed");

		emit WithdrawnNative(_tresory, balance);
	}

	function withdrawToken(address _token, address _to) public requireTimelockAdmin {
		IERC20 token = IERC20(_token);
		uint256 balance = token.balanceOf(address(this));

		SafeERC20.safeTransfer(token, _to, balance);

		emit WithdrawnToken(_token, _to, balance);
	}

	function editRewardsReinjectionScriptCID(string memory _rewardsReinjectionScriptCID) public requireTimelockAdmin {
		lswSystemData.rewardsReinjectionScriptCID = _rewardsReinjectionScriptCID;
	}
	
	// ============ Modifiers ============

	modifier gaugeTaskExecutorOnly(address _poolGauge) {
		require(msg.sender == gaugeExecutors[_poolGauge], "Not authorized");
		_;
		taskManager._handleGelatoFees();
	}

	modifier onlyLswTaskManagerGelato() {
		require(msg.sender == taskManager.dedicatedMsgSender(), "Not authorized");
		_;
		taskManager._handleGelatoFees();
	}

	modifier onlyGaugeManager() {
		require(securityManager.hasContractRole(securityManager.GAUGE_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier onlySilverStake() {
		require(securityManager.hasContractRole(securityManager.SILVER_STAKE_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier onlyLswTaskManager() {
		require(securityManager.hasContractRole(securityManager.SILVER_LSW_TASK_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	// ============ Receive Function ============

	receive() external payable {}
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import "@openzeppelin/contracts/access/Ownable2Step.sol";

import {GaugeManager} from "../Gauge/GaugeManager.sol";
import {SilverLswManager} from "./SilverLswManager.sol";
import "../Security/ContractPermissionManager.sol";
import "../Security/TimelockProtection.sol";

// ============ Structs ============
struct GaugeVoteInfo {
	uint256 totalVoters;	// Total voters for this gauge
	address[] voters;		// List of voters (need to reset)
}

struct UserVoteInfo {
	address poolGauge;
	uint256 timestamp;
}

/**
 * @title SilverVoteLSW
 * @author github.com/SifexPro
 * @notice Contract for managing gauge voting in the LSW system
 */
contract SilverVoteLSW is Ownable2Step, TimelockProtection {
	// ============ Interfaces ============
	GaugeManager public gaugeManager;
	SilverLswManager public silverLswManager;
	ContractPermissionManager public immutable securityManager;

	// ============ Storage ============
	mapping(address => GaugeVoteInfo) public voteInfoByGauge;
	mapping(address => UserVoteInfo) public voteInfoByUser;
	address[] public votedGauges;

	// ============ Events for voting ============
	event GaugeVoted(address indexed gauge, address indexed voter);
	event VoteCleared(address indexed gauge, address indexed voter);
	
	// ============ Events for setters ============
	event GaugeManagerSet(address indexed newGaugeManager);
	event SilverLswManagerSet(address indexed newSilverLswManager);


	// ============ Constructor ============
	constructor(
		address _gaugeManager, 
		address _securityManager,
		address _timelockMain,
		address _timelockAdmin
	) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
		gaugeManager = GaugeManager(payable(_gaugeManager));
		securityManager = ContractPermissionManager(_securityManager);
	}

	// ============ Vote functions ============

	/**
	 * @notice Vote on a gauge
	 * @param _poolGauge The gauge address
	 */
	function voteOnGauge(address _poolGauge) external eligibleUser {
		require(!silverLswManager.isLswLocked(), "Lsw system is locked");
		require(_poolGauge != address(0), "Zero address");
		require(gaugeManager.isGaugeActive(_poolGauge), "Gauge not active for voting");
		require(getUserVotedGauge(msg.sender) != _poolGauge, "User already voted on this gauge");
		
		address previousGauge = getUserVotedGauge(msg.sender);
		if (previousGauge != address(0)) {
			_removeVoterFromGauge(previousGauge, msg.sender);
		}

		require(gaugeManager.getUserVotingPower(msg.sender) > 0, "User has no voting power");
		
		_addVoterToGauge(_poolGauge, msg.sender);
		_addVotedGauge(_poolGauge);
		
		emit GaugeVoted(_poolGauge, msg.sender);
	}


	// ============ SilverLswManager functions ============

	/**
	 * @notice Clear all vote information
	 * @dev Only callable by SilverLswManager
	 */
	function clearVoteInfo() public onlySilverLswManager {
		if (votedGauges.length == 0) return;
		
		uint256 length = votedGauges.length;
		for (uint256 i = 0; i < length;) {
			address gauge = votedGauges[i];
			voteInfoByGauge[gauge].voters = new address[](0);
			voteInfoByGauge[gauge].totalVoters = 0;
			unchecked { ++i; }
		}
		delete votedGauges;
	}


	// ============ Internal functions ============

	/**
	 * @notice Add a voter to a gauge's voter list
	 * @param gauge The gauge address
	 * @param voter The voter address to add
	 */
	function _addVoterToGauge(address gauge, address voter) private {
		voteInfoByGauge[gauge].voters.push(voter);
		voteInfoByGauge[gauge].totalVoters++;
		voteInfoByUser[voter].poolGauge = gauge;
		voteInfoByUser[voter].timestamp = block.timestamp;
	}

	/**
	 * @notice Remove a voter from a gauge's voter list
	 * @param gauge The gauge address
	 * @param voter The voter address to remove
	 */
	function _removeVoterFromGauge(address gauge, address voter) private {
		address[] storage voters = voteInfoByGauge[gauge].voters;
		uint256 length = voters.length;
		
		for (uint256 i = 0; i < length;) {
			if (voters[i] == voter) {
				if (i < length - 1) {
					voters[i] = voters[length - 1];
				}
				voters.pop();
				voteInfoByUser[voter].poolGauge = address(0);
				voteInfoByGauge[gauge].totalVoters--;

				if (voteInfoByGauge[gauge].totalVoters == 0) {
					_removeVotedGauge(gauge);
				}
				emit VoteCleared(gauge, voter);
				break;
			}
			unchecked { ++i; }
		}
	}

	/**
	 * @notice Check if a gauge has been voted on
	 * @param gauge The gauge address
	 * @return bool Whether the gauge has been voted on
	 */
	function _isGaugeVoted(address gauge) public view returns (bool) {
		uint256 length = votedGauges.length;
		for (uint256 i = 0; i < length;) {
			if (votedGauges[i] == gauge) {
				return true;
			}
			unchecked { ++i; }
		}
		return false;
	}

	/**
	 * @notice Add a gauge to the voted gauges list
	 * @param gauge The gauge address
	 */
	function _addVotedGauge(address gauge) private {
		if (!_isGaugeVoted(gauge)) {
			votedGauges.push(gauge);
		}
	}

	/**
	 * @notice Remove a gauge from the voted gauges list
	 * @param gauge The gauge address
	 */
	function _removeVotedGauge(address gauge) private {
		uint256 length = votedGauges.length;
		for (uint256 i = 0; i < length;) {
			if (votedGauges[i] == gauge) {
				if (i < length - 1) {
					votedGauges[i] = votedGauges[length - 1];
				}
				votedGauges.pop();
				break;
			}
			unchecked { ++i; }
		}
	}


	// ============ Setters ============

	function setSilverLswManager(address _silverLswManager) public requireTimelockMain {
		silverLswManager = SilverLswManager(payable(_silverLswManager));
		emit SilverLswManagerSet(_silverLswManager);
	}

	function setGaugeManager(address _gaugeManager) public requireTimelockMain {
		gaugeManager = GaugeManager(payable(_gaugeManager));
		emit GaugeManagerSet(_gaugeManager);
	}


	// ============ Getters ============

	/**
	 * @notice Get the total number of voters for a gauge
	 * @param gauge The gauge address
	 * @return The total number of voters
	 */
	function getGaugeTotalVoters(address gauge) public view returns (uint256) {
		return voteInfoByGauge[gauge].totalVoters;
	}

	/**
	 * @notice Get the voters for a gauge
	 * @param gauge The gauge address
	 * @return The voters
	 */
	function getGaugeVoters(address gauge) public view returns (address[] memory) {
		return voteInfoByGauge[gauge].voters;
	}

	/**
	 * @notice Get the voted gauge for a user
	 * @param user The user address
	 * @return The voted gauge
	 */
	function getUserVotedGauge(address user) public view returns (address) {
		if (voteInfoByUser[user].timestamp > silverLswManager.getLastExecutionTimestamp()) {
			return voteInfoByUser[user].poolGauge;
		}
		return address(0);
	}

	/**
	 * @notice Get all voted gauges
	 * @return Array of voted gauge addresses
	 */
	function getVotedGauges() public view returns (address[] memory) {
		return votedGauges;
	}


	// ============ Modifiers ============

	/**
	 * @notice Ensures only the SilverLswManager contract can call the function
	 */
	modifier onlySilverLswManager() {
		require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}

	modifier eligibleUser() {
		require(gaugeManager.getUserTotalAgsDeposits(msg.sender) > 0, "User has no voting power");
		_;
	}
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "./TimelockProtection.sol";

/**
 * @title ContractPermissionManager
 * @author github.com/SifexPro
 * @notice Contract managing access control between Silver LSW protocol contracts
 * @dev Centralizes permission management for cross-contract calls
 */
contract ContractPermissionManager is AccessControl, Ownable2Step, TimelockProtection {
    // ============ Role Definitions ============
    bytes32 public constant SILVER_LSW_MANAGER_ROLE = keccak256("SILVER_LSW_MANAGER_ROLE");
    bytes32 public constant SILVER_LSW_TASK_MANAGER_ROLE = keccak256("SILVER_LSW_TASK_MANAGER_ROLE");
    bytes32 public constant POOL_LOCKER_ROLE = keccak256("POOL_LOCKER_ROLE");
    bytes32 public constant GAUGE_MANAGER_ROLE = keccak256("GAUGE_MANAGER_ROLE");
    bytes32 public constant SILVER_STAKE_ROLE = keccak256("SILVER_STAKE_ROLE");
    
    // ============ Role mapping ============
    mapping(bytes32 => address) private roleToAddress;
    
    // ============ Events ============
    event ContractRoleGranted(bytes32 indexed role, address indexed account);
    event ContractRoleRevoked(bytes32 indexed role, address indexed account);

    // ============ Constructor ============
    constructor(
        address _timelockMain,
        address _timelockAdmin
    ) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }

    // ============ Admin Functions ============
    
    /**
     * @notice Grants a contract role to an account
     * @dev Protected by main timelock due to critical security implications
     * @param role The role to grant
     * @param account The account to grant the role to
     */
    function grantContractRole(bytes32 role, address account) external requireTimelockMain {
        require(account != address(0), "ContractPermissionManager: Invalid address");
        _grantRole(role, account);
        roleToAddress[role] = account;
        emit ContractRoleGranted(role, account);
    }
    
    /**
     * @notice Revokes a contract role from an account
     * @dev Protected by main timelock due to critical security implications
     * @param role The role to revoke
     * @param account The account to revoke the role from
     */
    function revokeContractRole(bytes32 role, address account) external requireTimelockMain {
        require(account != address(0), "ContractPermissionManager: Invalid address");
        _revokeRole(role, account);
        if (roleToAddress[role] == account) {
            delete roleToAddress[role];
        }
        emit ContractRoleRevoked(role, account);
    }

    // ============ View Functions ============
    
    /**
     * @notice Gets the address assigned to a specific role
     * @param role The role to get the address for
     * @return The address assigned to the role
     */
    function getRoleAddress(bytes32 role) external view returns (address) {
        return roleToAddress[role];
    }
    
    /**
     * @notice Checks if an account has a contract role
     * @param role The role to check
     * @param account The account to check
     * @return True if the account has the role
     */
    function hasContractRole(bytes32 role, address account) external view returns (bool) {
        return hasRole(role, account);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "../interfaces/ITimelock.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title TimelockProtection
 * @author github.com/SifexPro
 * @notice Contract that provides timelock protection functionality
 * @dev This contract is meant to be inherited by contracts that need timelock protection
 */
abstract contract TimelockProtection {
    // ============ State Variables ============
    ITimelock public timelockMain;
    ITimelock public timelockAdmin;
    
    // ============ Events ============
    event TimelockMainSet(address indexed newTimelock);
    event TimelockAdminSet(address indexed newTimelock);
    
    // ============ Constructor ============
    constructor(address _timelockMain, address _timelockAdmin) {
        if (_timelockMain != address(0)) {
            timelockMain = ITimelock(_timelockMain);
        }
        if (_timelockAdmin != address(0)) {
            timelockAdmin = ITimelock(_timelockAdmin);
        }
    }
    
    // ============ Admin Functions ============
    /**
     * @notice Set the main timelock address
     * @param _timelockMain The new timelock address
     */
    function _setTimelockMain(address _timelockMain) internal {
        require(_timelockMain != address(0), "TimelockProtection: zero address");
        timelockMain = ITimelock(_timelockMain);
        emit TimelockMainSet(_timelockMain);
    }
    
    /**
     * @notice Set the admin timelock address
     * @param _timelockAdmin The new timelock address
     */
    function _setTimelockAdmin(address _timelockAdmin) internal {
        require(_timelockAdmin != address(0), "TimelockProtection: zero address");
        timelockAdmin = ITimelock(_timelockAdmin);
        emit TimelockAdminSet(_timelockAdmin);
    }
    
    // ============ Modifiers ============
    /**
     * @notice Modifier that requires the main timelock to be activated or allows owner if not active
     * @dev This should be used for critical functions that change the system's structure
     */
    modifier requireTimelockMain() {
        // First check if timelock is set and active
        if (address(timelockMain) != address(0)) {
            (bool activated, ) = timelockMain.checkTimelock();
            if (activated) {
                // If active, only allow the timelock to call
                require(msg.sender == address(timelockMain), "TimelockProtection: caller is not main timelock");
                _;
                return;
            }
        }
        
        // If timelock is not set or not active, allow the owner to call
        require(msg.sender == Ownable(address(this)).owner(), "TimelockProtection: caller is not owner");
        _;
    }
    
    /**
     * @notice Modifier that requires the admin timelock to be activated or allows owner if not active
     * @dev This should be used for administrative functions that need some protection
     */
    modifier requireTimelockAdmin() {
        // First check if timelock is set and active
        if (address(timelockAdmin) != address(0)) {
            (bool activated, ) = timelockAdmin.checkTimelock();
            if (activated) {
                // If active, only allow the timelock to call
                require(msg.sender == address(timelockAdmin), "TimelockProtection: caller is not admin timelock");
                _;
                return;
            }
        }
        
        // If timelock is not set or not active, allow the owner to call
        require(msg.sender == Ownable(address(this)).owner(), "TimelockProtection: caller is not owner");
        _;
    }
}

File 40 of 41 : SilverStake.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import "../integrations/gelato/AutomateTaskCreator.sol";
import "../Security/ContractPermissionManager.sol";
import "../Security/TimelockProtection.sol";

import {ISFC} from "../interfaces/ISFC.sol";
import {IWrappedNative} from "../interfaces/IWrappedNative.sol";
	
// ============ Interfaces ============
interface ISilverStakeToken {
	function mint(uint256 _amount) external;
	function burn(uint256 _amount) external;
}

interface ISilverLswManager {
	function isLswLocked() external view returns (bool);
	function lockLswSystem() external;
	function unlockLswSystem() external;
	function stopLswSystemForMaintenance() external;
}

// ============ Structs ============
struct StakeSettings {
	uint256 validatorID;
	uint256 withdrawDelay;
	uint256 rateForOneNative;
	uint256 minStakeAmount;
}

struct StakeInfo {
	uint96 startTime;
	uint96 lastStakeTime;
	uint96 lastUnstakeTime;
	uint256 weightedStakeTimestamp;
	uint256 weightedEntryRate;
	uint256 totalStaked;
}

struct UnstakeRequest {
	address user;
	uint256 wrID;
    uint256 nativeAmount;
    uint256 stakedTokenAmount;
    uint96 timestamp;
	uint96 withdrawableTimestamp;
    bool withdrawn;
	bytes32 taskID;
}

struct ValidatorTransfer {
	uint256 validatorID;
	uint256 amount;
	uint256 wrID;
	uint256 timestamp;
	bool transferInitiated;
}

/**
 * @title SilverStake
 * @author github.com/SifexPro
 * @notice A contract for staking Native
 */
contract SilverStake is AutomateTaskCreator, Ownable2Step, ReentrancyGuard, TimelockProtection {
	// ============ Interfaces ============
	ISilverStakeToken public immutable silverStakeToken;
	IERC20 public immutable silverStakeTokenERC20;
	ContractPermissionManager public immutable securityManager;
	ISFC public immutable sfc;
	IWrappedNative public immutable wrappedNativeToken;
	ISilverLswManager public silverLswManager;

	// ============ Utils variables ============
	uint256 public totalStakedNative;
	uint256 public withdrawIndex = 0;

	// ============ Stake settings ============
	StakeSettings public stakeSettings;
	ValidatorTransfer public validatorTransfer;

	// ============ Anti-frontrunning  ============
	uint256 public vestingDuration = 30 days;
	uint256 public baseReward = 10;
	uint256 public maxBonusReward = 90;

	// ============ Stake/Unstake info ============
	mapping(address => StakeInfo) public userStakeInfo;
	mapping(uint256 => UnstakeRequest) public unstakeRequests;

	// ============ Events for staking ============
	event Staked(address indexed user, uint256 nativeAmount, uint256 stakedTokenAmount, uint96 timestamp);
	event Unstaked(address indexed user, uint256 wrID, uint256 nativeAmount, uint256 stakedTokenAmount);
	event Withdrawn(address indexed user, uint256 wrID, uint256 nativeAmount);
	event Compounded(uint256 nativeAmount);
	event RateUpdated(uint256 rate);
	event StakeRewardsClaimed(uint256 amount, uint256 timestamp);
	event StakeRewardsClaimFailed(uint256 amount, uint256 timestamp);
	event VestingInfoTransferred(address indexed from, address indexed to, uint256 amount);

	// ============ Events for setters ============
	event ValidatorIDUpdated(uint256 newValidatorID);
	event ValidatorTransferConfirmed(uint256 validatorID, uint256 wrID, uint256 amount, uint256 timestamp);
	event SlashingLossDetected(uint256 expectedAmount, uint256 actualAmount, uint256 lossAmount);
	event LswSystemStoppedForValidatorTransfer(uint256 timestamp);
	event MinStakeAmountUpdated(uint256 newMinStakeAmount);
	event VestingParametersUpdated(uint256 vestingDuration, uint256 baseReward, uint256 maxBonusReward);
	event SilverLswManagerSet(address indexed newSilverLswManager);

	// ============ Events for Gelato ============
	event GelatoTaskCreated(bytes32 id);
	event GelatoTaskCanceled(bytes32 id);
	event GelatoTaskCancelFailed(bytes32 id);
	event GelatoFeesCheck(uint256 fees, address token);

	// ============ Events for owner ============
	event WithdrawnNative(address indexed to, uint256 amount);
	event WithdrawnToken(address indexed token, address to, uint256 amount);

	// ============ Constructor ============
	constructor(
		address _silverStakeToken, 
		address _securityManager, 
		address _sfc, 
		uint256 _validatorID, 
		address _wrappedNativeToken, 
		address _automate,
		address _timelockMain,
		address _timelockAdmin
	) AutomateTaskCreator(_automate) Ownable(msg.sender) TimelockProtection(_timelockMain, _timelockAdmin) {
		silverStakeToken = ISilverStakeToken(_silverStakeToken);
		silverStakeTokenERC20 = IERC20(_silverStakeToken);
		securityManager = ContractPermissionManager(_securityManager);
		wrappedNativeToken = IWrappedNative(_wrappedNativeToken);
		sfc = ISFC(_sfc);

		stakeSettings = StakeSettings({
			validatorID: _validatorID,
			withdrawDelay: 14 days + 5 minutes,
			rateForOneNative: 1 ether, // 1:1 default
			minStakeAmount: 1 ether
		});
	}

	// ============ Stake/Unstake/Withdraw ============
	
	/**
	 * @notice Stake Native tokens
	 * @dev Mints AGS tokens in exchange for Native tokens and delegates to validator
	 */
	function stake() public payable nonReentrant {
		require(!validatorTransfer.transferInitiated, "Validator transfer in progress");
		require(!silverLswManager.isLswLocked(), "Lsw system is locked");
		uint256 nativeAmount = msg.value;
		require(nativeAmount >= stakeSettings.minStakeAmount, "Amount below minimum");

		uint256 stakedTokenAmount = nativeToAGS(nativeAmount);
		
		unchecked {
			totalStakedNative += nativeAmount;
		}

		sfc.delegate{value: nativeAmount}(stakeSettings.validatorID);

		silverStakeToken.mint(stakedTokenAmount);
		SafeERC20.safeTransfer(silverStakeTokenERC20, msg.sender, stakedTokenAmount);
		
		_updateUserStakeInfo(msg.sender, stakedTokenAmount);

		emit Staked(msg.sender, nativeAmount, stakedTokenAmount, uint96(block.timestamp));
	}

	/**
	 * @notice Updates user staking information with new stake
	 * @dev Handles weighted averages for anti-frontrunning mechanism
	 * @param user Address of the user
	 * @param stakedAmount Amount of AGS tokens staked
	 */
	function _updateUserStakeInfo(address user, uint256 stakedAmount) private {
		StakeInfo storage userInfo = userStakeInfo[user];
		
		if (userInfo.startTime == 0) {
			userInfo.startTime = uint96(block.timestamp);
			userInfo.weightedStakeTimestamp = block.timestamp;
			userInfo.weightedEntryRate = stakeSettings.rateForOneNative;
			userInfo.totalStaked = stakedAmount;
		} else {
			uint256 newTotalStaked = userInfo.totalStaked + stakedAmount;
			
			userInfo.weightedStakeTimestamp = (
				userInfo.totalStaked * userInfo.weightedStakeTimestamp + 
				stakedAmount * block.timestamp
			) / newTotalStaked;
			
			userInfo.weightedEntryRate = (
				userInfo.totalStaked * userInfo.weightedEntryRate + 
				stakedAmount * stakeSettings.rateForOneNative
			) / newTotalStaked;
			
			userInfo.totalStaked = newTotalStaked;
		}
		
		userInfo.lastStakeTime = uint96(block.timestamp);
	}

	/**
	 * @notice Unstake native by burning $AGS
	 * @param stakedTokenAmount The amount of $AGS to burn
	 */
	function unstake(uint256 stakedTokenAmount) public nonReentrant {
		require(!validatorTransfer.transferInitiated, "Validator transfer in progress");
		require(!silverLswManager.isLswLocked(), "Lsw system is locked");
		require(stakedTokenAmount > 0, "Amount must be greater than 0");
		require(silverStakeTokenERC20.balanceOf(msg.sender) >= stakedTokenAmount, "$AGS: insufficient balance");
		require(silverStakeTokenERC20.allowance(msg.sender, address(this)) >= stakedTokenAmount, "$AGS: insufficient allowance");

		(uint256 nativeAmount, ) = _calculateUnstakeAmount(msg.sender, stakedTokenAmount);
		
		uint256 wrID = _incrementWithdrawIndex();

		unchecked {
			totalStakedNative -= nativeAmount;
		}
		
		sfc.undelegate(stakeSettings.validatorID, wrID, nativeAmount);
		
		SafeERC20.safeTransferFrom(silverStakeTokenERC20, msg.sender, address(this), stakedTokenAmount);
		silverStakeToken.burn(stakedTokenAmount);
		
		_createUnstakeRequest(msg.sender, wrID, nativeAmount, stakedTokenAmount);
		userStakeInfo[msg.sender].lastUnstakeTime = uint96(block.timestamp);

		emit Unstaked(msg.sender, wrID, nativeAmount, stakedTokenAmount);
	}

	/**
	 * @notice Calculate the native amount to return when unstaking, applying vesting
	 * @dev Handles both tracked stakes and external tokens with different vesting rules
	 * @param user Address of the user unstaking
	 * @param stakedTokenAmount Amount of $AGS tokens to unstake
	 * @return nativeAmount The amount of native tokens to be returned
	 * @return trackedAmount The amount of tokens from tracked stakes
	 */
	function _calculateUnstakeAmount(address user, uint256 stakedTokenAmount) private returns (uint256 nativeAmount, uint256 trackedAmount) {
		StakeInfo storage userInfo = userStakeInfo[user];
		
		trackedAmount = stakedTokenAmount;
		uint256 externalAmount = 0;
		
		if (userInfo.totalStaked < stakedTokenAmount) {
			trackedAmount = userInfo.totalStaked;
			externalAmount = stakedTokenAmount - trackedAmount;
		}
		
		nativeAmount = 0;
		
		if (trackedAmount > 0) {
			uint256 timeStaked = block.timestamp > userInfo.weightedStakeTimestamp ? block.timestamp - userInfo.weightedStakeTimestamp : 0;
			uint256 vestedPortion = timeStaked >= vestingDuration ? 100 : (timeStaked * 100) / vestingDuration;
			
			uint256 rewardShare = baseReward + ((maxBonusReward * vestedPortion) / 100);
			
			uint256 baseAmount = (trackedAmount * userInfo.weightedEntryRate) / 1e18;
			uint256 potentialGain = 0;
			
			if (stakeSettings.rateForOneNative > userInfo.weightedEntryRate) {
				potentialGain = (trackedAmount * (stakeSettings.rateForOneNative - userInfo.weightedEntryRate)) / 1e18;
				potentialGain = (potentialGain * rewardShare) / 100;
			}

			nativeAmount += baseAmount + potentialGain;
			userInfo.totalStaked -= trackedAmount;
		}
		
		if (externalAmount > 0) {
			uint256 baseAmount = (externalAmount * stakeSettings.rateForOneNative) / 1e18;
			nativeAmount += (baseAmount * baseReward) / 100;
		}
		
		return (nativeAmount, trackedAmount);
	}
	
	/**
	 * @notice Create an unstake request and schedule automatic withdrawal
	 * @param user Address of the user unstaking
	 * @param wrID Withdrawal request ID
	 * @param nativeAmount Amount of native tokens to be returned
	 * @param stakedTokenAmount Amount of $AGS tokens unstaked
	 */
	function _createUnstakeRequest(address user, uint256 wrID, uint256 nativeAmount, uint256 stakedTokenAmount) private {
		unstakeRequests[wrID] = UnstakeRequest({
			user: user,
			wrID: wrID,
			nativeAmount: nativeAmount,
			stakedTokenAmount: stakedTokenAmount,
			timestamp: uint96(block.timestamp),
			withdrawableTimestamp: uint96(block.timestamp + stakeSettings.withdrawDelay),
			withdrawn: false,
			taskID: bytes32(0)
		});
		
		createTaskWithdraw(wrID);
	}

	/**
	 * @notice Withdraw native that is ready to be withdrawn
	 * @param wrID The withdrawal request ID
	 * @dev Can be called by the user or automatically by Gelato
	 */
	function withdraw(uint256 wrID) public onlyUserOrGelatoTask(wrID) nonReentrant {
		UnstakeRequest storage request = unstakeRequests[wrID];
		
		require(request.user != address(0), "Invalid wrID");
		require(!request.withdrawn, "Already withdrawn");
		require(block.timestamp >= request.withdrawableTimestamp, "Withdrawal delay not passed");
		
		request.withdrawn = true;
		
		sfc.withdraw(stakeSettings.validatorID, request.wrID);
		
		(bool success,) = payable(request.user).call{value: request.nativeAmount}("");
		require(success, "Transfer failed");

		if (msg.sender != dedicatedMsgSender && request.taskID != bytes32(0)) {
			cancelTask(request.taskID);
		}

		request.taskID = bytes32(0);

		emit Withdrawn(request.user, wrID, request.nativeAmount);
	}

	// ============ SilverLswManager functions ============

	function compounding(uint256 wrappedNativeAmount) public onlySilverLswManager {
		uint256 balanceBefore = address(this).balance;
		wrappedNativeToken.withdraw(wrappedNativeAmount);
		uint256 nativeAmount = address(this).balance - balanceBefore;
		
		sfc.delegate{value: nativeAmount}(stakeSettings.validatorID);

		totalStakedNative += nativeAmount;

		emit Compounded(nativeAmount);
	}
	
	/**
	 * @notice Claim validator rewards
	 * @dev Only callable by SilverLswManager
	 */
	function _claimRewards() public onlySilverLswManager {
		////sfc.claimRewards(stakeSettings.validatorID); testing
		(bool success,) = payable(msg.sender).call{value: 1 ether}("");
		require(success, "Transfer failed");
		////testing
	}

	/**
	 * @notice Claim validator rewards
	 * @dev Only callable by SilverLswManager
	 */
	function _claimRewardsReal() public onlyOwner { ////testing -> onlySilverLswManager
		uint256 rewards = sfc.pendingRewards(address(this), stakeSettings.validatorID);
		if (rewards == 0) return;
		
		sfc.claimRewards(stakeSettings.validatorID);
		(bool success,) = payable(msg.sender).call{value: rewards}("");

		if (!success)
			emit StakeRewardsClaimFailed(rewards, block.timestamp);
		else
			emit StakeRewardsClaimed(rewards, block.timestamp);
	}

	function updateRateForOneToken() public onlySilverLswManager {
		uint256 totalMintedAGS = silverStakeTokenERC20.totalSupply();
		if (totalMintedAGS == 0) return;
		

		uint256 newRate = (totalStakedNative * 1e18) / totalMintedAGS;
		
		if (newRate != stakeSettings.rateForOneNative) {
			if (newRate < stakeSettings.rateForOneNative) {
				uint256 minAllowedRate = (stakeSettings.rateForOneNative * 90) / 100;
				if (newRate < minAllowedRate) {
					newRate = minAllowedRate;
				}
			}
			
			stakeSettings.rateForOneNative = newRate;
			emit RateUpdated(stakeSettings.rateForOneNative);
		}
	}

	// ============ Gelato functions ============

	/**
	 * @notice Create a task to withdraw automatically after the delay
	 * @param wrID The withdrawal request ID
	 */
	function createTaskWithdraw(uint256 wrID) private {
		uint256 execTime = 30 minutes;

		bytes memory execData = abi.encodeCall(this.withdraw, (wrID));

		ModuleData memory moduleData = ModuleData({
			modules: new Module[](3),
			args: new bytes[](3)
		});

		moduleData.modules[0] = Module.PROXY;
		moduleData.modules[1] = Module.SINGLE_EXEC;
		moduleData.modules[2] = Module.TRIGGER;
		
		moduleData.args[0] = _proxyModuleArg();
		moduleData.args[1] = _singleExecModuleArg();
		moduleData.args[2] = _timeTriggerModuleArg(
			uint128(unstakeRequests[wrID].withdrawableTimestamp) * 1000, 
			uint128(execTime) * 1000
		);

		bytes32 taskId = _createTask(address(this), execData, moduleData, ETH);
		unstakeRequests[wrID].taskID = taskId;

		emit GelatoTaskCreated(taskId);
	}

	function cancelTaskCall(bytes32 taskId) public {
		require(msg.sender == address(this));
		_cancelTask(taskId);
	}

	/**
	 * @notice Cancel a gelato task
	 * @param taskId The task ID
	 */
	function cancelTask(bytes32 taskId) public onlyOwner {
		if (taskId == bytes32(0))
			return;

		(bool success, ) = address(this).call(
            abi.encodeWithSignature("cancelTaskCall(bytes32)", taskId)
        );

		if (success)
			emit GelatoTaskCanceled(taskId);
		else
			emit GelatoTaskCancelFailed(taskId);
	}

	function _handleGelatoFees() private {
		(uint256 fee, address feeToken) = _getFeeDetails();
		_transfer(fee, feeToken);
		emit GelatoFeesCheck(fee, feeToken);
	}
		
	
	// ============ Internal functions ============

	function _incrementWithdrawIndex() private returns (uint256) {
		withdrawIndex++;
	
		uint256 timestampComponent = uint256(block.timestamp & 0xFFFFFFFF) << 16;
		uint256 indexComponent = withdrawIndex & 0xFFFF;
		uint256 prefixComponent = 0x000 << 48;
		
		return prefixComponent | timestampComponent | indexComponent;
	}


	// ============ Setters ============

	/**
	 * @notice Update the validator ID
	 * @dev Protected by main timelock due to critical nature
	 * @param newValidatorID The new validator ID
	 */
	function updateValidatorID(uint256 newValidatorID) external requireTimelockMain {
		require(newValidatorID != stakeSettings.validatorID, "Validator ID is already set");
		require(newValidatorID != 0, "Validator ID cannot be 0");

		silverLswManager.stopLswSystemForMaintenance();
		silverLswManager.lockLswSystem();

		uint256 wrId = _incrementWithdrawIndex();
		uint256 currentStake = sfc.getStake(address(this), stakeSettings.validatorID);
		
		sfc.undelegate(stakeSettings.validatorID, wrId, currentStake);

		validatorTransfer.validatorID = newValidatorID;
		validatorTransfer.wrID = wrId;
		validatorTransfer.amount = currentStake;
		validatorTransfer.timestamp = uint96(block.timestamp) + stakeSettings.withdrawDelay;
		validatorTransfer.transferInitiated = true;

		emit ValidatorIDUpdated(stakeSettings.validatorID);
		emit LswSystemStoppedForValidatorTransfer(block.timestamp);
	}

	/**
	 * @notice Confirm validator transfer
	 * @dev Protected by main timelock due to critical nature
	 */
	function confirmValidatorTransfer() external requireTimelockMain {
		require(validatorTransfer.validatorID != 0, "No validator transfer");
		require(block.timestamp >= validatorTransfer.timestamp, "Not yet");

		uint256 expectedAmount = validatorTransfer.amount;
		uint256 balanceBefore = address(this).balance;
		sfc.withdraw(stakeSettings.validatorID, validatorTransfer.wrID);
		uint256 actualAmount = address(this).balance - balanceBefore;

		if (actualAmount < expectedAmount) {
			uint256 slashingLoss = expectedAmount - actualAmount;

			if (totalStakedNative >= slashingLoss) {
				totalStakedNative -= slashingLoss;
			} else {
				totalStakedNative = 0;
			}
			
			emit SlashingLossDetected(expectedAmount, actualAmount, slashingLoss);
		}

		stakeSettings.validatorID = validatorTransfer.validatorID;

		sfc.delegate{value: actualAmount}(stakeSettings.validatorID);

		uint256 oldValidatorID = validatorTransfer.validatorID;
		uint256 oldWrID = validatorTransfer.wrID;
		uint256 oldTimestamp = validatorTransfer.timestamp;
		
		validatorTransfer.validatorID = 0;
		validatorTransfer.wrID = 0;
		validatorTransfer.amount = 0;
		validatorTransfer.timestamp = 0;
		validatorTransfer.transferInitiated = false;

		silverLswManager.unlockLswSystem();

		emit ValidatorTransferConfirmed(oldValidatorID, oldWrID, actualAmount, oldTimestamp);
	}

	/**
	 * @notice Update the minimum stake amount
	 * @dev Protected by admin timelock
	 * @param newMinStakeAmount The new minimum stake amount
	 */
	function updateMinStakeAmount(uint256 newMinStakeAmount) external requireTimelockAdmin {
		stakeSettings.minStakeAmount = newMinStakeAmount;
		emit MinStakeAmountUpdated(newMinStakeAmount);
	}

	/**
	 * @notice Set vesting parameters
	 * @dev Protected by main timelock due to economic impact
	 * @param _vestingDuration The vesting duration in seconds
	 * @param _baseReward The base reward percentage
	 * @param _maxBonusReward The maximum bonus reward percentage
	 */
	function setVestingParameters(uint256 _vestingDuration, uint256 _baseReward, uint256 _maxBonusReward) public requireTimelockMain {
		require(_baseReward + _maxBonusReward == 100, "Rewards must sum to 100%");
		vestingDuration = _vestingDuration;
		baseReward = _baseReward;
		maxBonusReward = _maxBonusReward;
		
		emit VestingParametersUpdated(_vestingDuration, _baseReward, _maxBonusReward);
	}

	/**
	 * @notice Set the SilverLswManager address
	 * @dev Protected by main timelock due to critical integration
	 * @param _silverLswManager The new SilverLswManager address
	 */
	function setSilverLswManager(address _silverLswManager) public requireTimelockMain {
		silverLswManager = ISilverLswManager(payable(_silverLswManager));
		emit SilverLswManagerSet(_silverLswManager);
	}

	// ============ Owner Functions ============

	/**
	 * @notice Withdraw native tokens to a specified address
	 * @dev Protected by admin timelock
	 * @param _to The address to withdraw to
	 */
	function withdrawNative(address _to) public requireTimelockAdmin {
		uint256 balance = address(this).balance;
		require(balance > 0, "No Native to withdraw");

		address payable _tresory = payable(_to);
		(bool success, ) = _tresory.call{value:balance}("");
		require(success, "Transaction failed");

		emit WithdrawnNative(_tresory, balance);
	}

	/**
	 * @notice Withdraw ERC20 tokens to a specified address
	 * @dev Protected by admin timelock
	 * @param _token The token address
	 * @param _to The address to withdraw to
	 */
	function withdrawToken(address _token, address _to) public requireTimelockAdmin {
		IERC20 token = IERC20(_token);
		uint256 balance = token.balanceOf(address(this));

		SafeERC20.safeTransfer(token, _to, balance);

		emit WithdrawnToken(_token, _to, balance);
	}


	// ============ Getters ============

	function getStakeInfo(address user) public view returns (StakeInfo memory) {
		return userStakeInfo[user];
	}

	function getUnstakeRequest(uint256 wrID) public view returns (UnstakeRequest memory) {
		return unstakeRequests[wrID];
	}

	/**
	 * @notice Get the current vesting percentage for a user
	 * @param user Address of the user
	 * @return vestingPercentage Vesting percentage (0-100)
	 */
	function getUserVestingPercentage(address user) public view returns (uint256 vestingPercentage) {
		StakeInfo storage userInfo = userStakeInfo[user];
		
		if (userInfo.startTime == 0 || userInfo.totalStaked == 0) return 0;
		
		uint256 timeStaked = block.timestamp > userInfo.weightedStakeTimestamp ? 
			block.timestamp - userInfo.weightedStakeTimestamp : 0;
		
		vestingPercentage = timeStaked >= vestingDuration ? 
			100 : (timeStaked * 100) / vestingDuration;
			
		return vestingPercentage;
	}

	/**
	 * @notice Convert Native amount to AGS amount using current rate
	 * @param nativeAmount Amount in Native (1e18)
	 * @return Amount in AGS (1e18)
	 */
	function nativeToAGS(uint256 nativeAmount) public view returns (uint256) {
		return (nativeAmount * 1 ether) / stakeSettings.rateForOneNative;
	}

	/**
	 * @notice Convert AGS amount to Native amount using current rate
	 * @param agsAmount Amount in AGS (1e18)
	 * @return Amount in Native (1e18)
	 */
	function agsToNative(uint256 agsAmount) public view returns (uint256) {
		return (agsAmount * stakeSettings.rateForOneNative) / 1 ether;
	}

	/**
	 * @notice Receive token transfer notifications from SilverStakeToken
	 * @dev Only callable by SilverStakeToken contract
	 * @param from The sender address
	 * @param to The recipient address
	 * @param amount The amount of tokens transferred
	 */
	function notifyTokenTransfer(address from, address to, uint256 amount) external {
		require(msg.sender == address(silverStakeToken), "Only $AGS");
		
		if (userStakeInfo[from].totalStaked > 0)
			_transferVestingInfo(from, to, amount);
	}

	/**
	 * @notice Transfer vesting information proportionally between users
	 * @dev Internal function called during token transfers
	 * @param from The sender address
	 * @param to The recipient address
	 * @param amount The amount of tokens transferred
	 */
	function _transferVestingInfo(address from, address to, uint256 amount) private {
		StakeInfo storage fromInfo = userStakeInfo[from];
		StakeInfo storage toInfo = userStakeInfo[to];
		
		if (toInfo.totalStaked == 0) {
			toInfo.startTime = uint96(block.timestamp);
			toInfo.weightedStakeTimestamp = fromInfo.weightedStakeTimestamp;
			toInfo.weightedEntryRate = fromInfo.weightedEntryRate;
			toInfo.totalStaked = amount;
		} else {
			uint256 newTotal = toInfo.totalStaked + amount;
			
			toInfo.weightedStakeTimestamp = (
				toInfo.totalStaked * toInfo.weightedStakeTimestamp +
				amount * fromInfo.weightedStakeTimestamp
			) / newTotal;
			
			toInfo.weightedEntryRate = (
				toInfo.totalStaked * toInfo.weightedEntryRate +
				amount * fromInfo.weightedEntryRate
			) / newTotal;
			
			toInfo.totalStaked = newTotal;
		}
		
		fromInfo.totalStaked -= amount;
		
		if (fromInfo.totalStaked == 0) {
			fromInfo.weightedStakeTimestamp = 0;
			fromInfo.weightedEntryRate = 0;
		}

		emit VestingInfoTransferred(from, to, amount);
	}

	// ============ Modifiers ============

	/**
	 * @notice Ensures only the user who owns the unstake request or Gelato can call the function
	 * @param wrID The withdrawal request ID
	 */
	modifier onlyUserOrGelatoTask(uint256 wrID) {
		require(unstakeRequests[wrID].user == msg.sender || msg.sender == dedicatedMsgSender, "Not authorized");
		_;
		if (msg.sender == dedicatedMsgSender) {
			_handleGelatoFees();
		}
	}

	/**
	 * @notice Ensures only the Silver LSW Manager contract can call the function
	 */
	modifier onlySilverLswManager() {
		require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}


	// ============ Receive function ============

	receive() external payable {}
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

// ============ Imports ============
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "../Security/ContractPermissionManager.sol";
import "../Security/TimelockProtection.sol";

import {ISFC} from "../interfaces/ISFC.sol";

// ============ Interfaces ============
interface StakerInfoInterface {
    function getInfo(uint256 _stakerID) external view returns (string memory);
    function updateInfo(string calldata _configUrl) external;
}

/**
 * @title SilverValidatorAuth
 * @author github.com/SifexPro
 * @notice This contract is used to create and manage validators for the SilverLsw project
 * @dev This contract should be secured with a multisig and timelock
 */
contract SilverValidatorAuth is Ownable2Step, TimelockProtection {
	// ============ Constants ============
	uint256 private constant PUBKEY_LENGTH = 48;

	// ============ Variables ============
	StakerInfoInterface public immutable stakerInfo;
	ISFC public immutable sfc;
	uint256 public validatorID;
	bool public validatorCreated;
	uint256 public withdrawIndex = 0;
	ContractPermissionManager public immutable securityManager;

	// ============ Events for validator ============
	event ValidatorCreated(uint256 indexed validatorID, uint256 stake);
	event ValidatorInfoUpdated(string configUrl);
	event ValidatorRewardsClaimed(uint256 amount, uint256 timestamp);
	event ValidatorRewardsClaimFailed(uint256 amount, uint256 timestamp);
	
	// ============ Events for delegation ============
	event Delegated(uint256 indexed toValidatorID, uint256 amount);
	event Undelegated(uint256 indexed toValidatorID, uint256 amount);

	// ============ Constructor ============
	constructor(
		address _multisig, 
		address _sfc, 
		address _stakerInfo,
		address _securityManager,
		address _timelockMain,
		address _timelockAdmin
	) Ownable(_multisig) TimelockProtection(_timelockMain, _timelockAdmin) {
		require(_sfc != address(0), "SFC address cannot be zero address");
		require(_stakerInfo != address(0), "StakerInfo address cannot be zero address");
		require(_securityManager != address(0), "ContractPermissionManager address cannot be zero address");
		
		sfc = ISFC(_sfc);
		stakerInfo = StakerInfoInterface(_stakerInfo);
		securityManager = ContractPermissionManager(_securityManager);
	}


	// ============ Validator Creation ============

	/**
	 * @notice Create a new validator
	 * @dev Only callable once during initial setup, not protected by timelock
	 * @param pubkey The validator's public key
	 */
	function _createValidator(bytes calldata pubkey) public payable onlyOwner {
		require(!validatorCreated, "Validator already created");
		require(pubkey.length == PUBKEY_LENGTH, "Invalid pubkey length");

		sfc.createValidator{value: msg.value}(pubkey);
		validatorID = sfc.getValidatorID(address(this));

		validatorCreated = true;
		emit ValidatorCreated(validatorID, msg.value);
	}

	/**
	 * @notice Update validator information
	 * @dev Protected by main timelock due to impact on validator operation
	 * @param _configUrl The new configuration URL
	 */
	function _updateValidatorInfo(string calldata _configUrl) public requireTimelockMain {
		require(bytes(_configUrl).length > 0, "Empty config URL");
		stakerInfo.updateInfo(_configUrl);
		emit ValidatorInfoUpdated(_configUrl);
	}


	// ============ Validator Interaction ============
	
	/**
	 * @notice Claim validator rewards
	 * @dev Only callable by SilverLswManager
	 */
	function _claimRewards() public onlySilverLswManager {
		uint256 rewards = sfc.pendingRewards(address(this), validatorID);
		if (rewards == 0) return;
		
		sfc.claimRewards(validatorID);
		(bool success,) = payable(msg.sender).call{value: rewards}("");

		if (!success)
			emit ValidatorRewardsClaimFailed(rewards, block.timestamp);
		else
			emit ValidatorRewardsClaimed(rewards, block.timestamp);
	}

	/**
	 * @notice Delegate stake to a validator
	 * @dev Protected by main timelock due to security implications
	 * @param toValidatorID The validator ID to delegate to
	 */
	function _delegate(uint256 toValidatorID) public payable requireTimelockMain {
		require(msg.value > 0, "Amount must be greater than 0");
		sfc.delegate{value: msg.value}(toValidatorID);
		emit Delegated(toValidatorID, msg.value);
	}

	/**
	 * @notice Undelegate stake from a validator
	 * @dev Protected by main timelock due to security implications
	 * @param toValidatorID The validator ID to undelegate from
	 * @param amount The amount to undelegate
	 */
	function _undelegate(uint256 toValidatorID, uint256 amount) public requireTimelockMain {
		require(amount > 0, "Amount must be greater than 0");
		sfc.undelegate(toValidatorID, _incrementWithdrawIndex(), amount);
		emit Undelegated(toValidatorID, amount);
	}

	/**
	 * @notice Withdraw rewards from a validator
	 * @dev Protected by main timelock due to security implications
	 * @param wrID The withdrawal request ID
	 */
	function _withdraw(uint256 wrID) public requireTimelockMain {
		sfc.withdraw(validatorID, wrID);
	}


	// ============ Getters ============

	/**
	 * @notice Get validator information
	 * @return The validator's configuration URL
	 */
	function getValidatorInfo() public view returns (string memory) {
		return stakerInfo.getInfo(validatorID);
	}

	/**
	 * @notice Get the validator ID
	 * @return The validator ID
	 */
	function getValidatorID() public view returns (uint256) {
		return validatorID;
	}


	// ============ Internal functions ============

	/**
	 * @notice Increment and generate a new withdrawal index
	 * @return The new withdrawal index
	 */
	function _incrementWithdrawIndex() private returns (uint256) {
		unchecked {
			withdrawIndex++;
		}
		
		uint256 timestampComponent = uint256(block.timestamp & 0xFFFFFFFF) << 16;
		uint256 indexComponent = withdrawIndex & 0xFFFF;
		uint256 prefixComponent = 0xFFF << 48;
		
		return prefixComponent | timestampComponent | indexComponent;
	}


	// ============ Modifiers ============

	modifier onlySilverLswManager () {
		require(securityManager.hasContractRole(securityManager.SILVER_LSW_MANAGER_ROLE(), msg.sender), "Not authorized");
		_;
	}


	// ============ Receive Function ============

	receive() external payable {}
}

Settings
{
  "evmVersion": "paris",
  "optimizer": {
    "enabled": true,
    "runs": 10
  },
  "metadata": {
    "bytecodeHash": "none"
  },
  "viaIR": true,
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_lswManager","type":"address"},{"internalType":"address","name":"_securityManager","type":"address"},{"internalType":"address","name":"_automate","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"length","type":"uint256"}],"name":"StringsInsufficientHexLength","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"poolGauge","type":"address"},{"indexed":false,"internalType":"address","name":"executor","type":"address"}],"name":"ExecutorCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"fees","type":"uint256"},{"indexed":false,"internalType":"address","name":"token","type":"address"}],"name":"GelatoFeesCheck","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"GelatoTaskCancelFailed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"GelatoTaskCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"GelatoTaskCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"_handleGelatoFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"automate","outputs":[{"internalType":"contract IAutomate","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"taskIds","type":"bytes32[]"}],"name":"cancelMultipleTasks","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"taskId","type":"bytes32"}],"name":"cancelTask","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"taskId","type":"bytes32"}],"name":"cancelTaskCall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"executor","type":"address"}],"name":"createTaskBreakLiquidityAndCompoundCall","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"lastSyncTimestamp","type":"uint256"}],"name":"createTaskClearLswSystem","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"poolGauge","type":"address"},{"internalType":"address","name":"projectToken","type":"address"},{"internalType":"string","name":"rewardsReinjectionScriptCID","type":"string"},{"internalType":"address","name":"wrappedNativeToken","type":"address"}],"name":"createTaskGaugeRewardsReinjection","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"executor","type":"address"}],"name":"createTaskGaugeSnapshot","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"createTaskGaugesRewards","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"lastSyncTimestamp","type":"uint256"}],"name":"createTaskStartBreakLiquidityAndCompound","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"lastSyncTimestamp","type":"uint256"}],"name":"createTaskSyncGaugeRewardsCalc","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"nextSyncTimestamp","type":"uint256"},{"internalType":"uint256","name":"syncTime","type":"uint256"}],"name":"createTaskSyncSystem","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dedicatedMsgSender","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gelato1Balance","outputs":[{"internalType":"contract IGelato1Balance","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_poolGauge","type":"address"}],"name":"getOrCreateExecutor","outputs":[{"internalType":"address","name":"executor","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lswManager","outputs":[{"internalType":"contract ISilverLswManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"securityManager","outputs":[{"internalType":"contract ContractPermissionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

0x6101206040818152346200041257606082620038f8803803809162000025828562000417565b8339810103126200041257806200003c8362000451565b60206200004b81860162000451565b946001600160a01b0393849162000063910162000451565b166080819052845163573ea57560e01b8152600492919082818581855afa908115620003c45786918491600091620003cf575b50858951809481936331056e5760e21b8352165afa908115620003c45790839160009162000383575b5060c052865163cd3d4fb960e01b815260028582015291829060249082905afa908115620002f4578591839160009162000343575b5084885180948193632e8743fd60e21b8352165afa908115620002f4578592918791600091620002ff575b5060248251809581936337b6269f60e21b83523089840152165afa908115620002f457600091620002a4575b5060a0525033156200028d5750819060018060a01b03199384600154166001556000549433908616176000555193823391167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a31660e0526101009216825261349191826200046783396080518281816103ff01528181611929015281816123cd015281816125a90152612e18015260a05182611bd5015260c0518281816119880152611a33015260e05182818161075401528181610d95015281816117da01528181611b8e01528181611cc201528181611ffa015281816122610152612b9a0152518181816101a401528181610511015281816106cc01528181610b3001528181610b8101528181610e73015281816110970152818161130d0152818161160a0152818161189401528181611c3c01528181611e3901526120870152f35b6024906000855191631e4fbdf760e01b8352820152fd5b8683813d8311620002ec575b620002bc818362000417565b81010312620002e857620002d08362000451565b92015180151503620002e5575080386200014b565b80fd5b5080fd5b503d620002b0565b86513d6000823e3d90fd5b92935090508282813d81116200033b575b6200031c818362000417565b81010312620002e55750908562000334869362000451565b386200011f565b503d62000310565b92509082813d81116200037b575b6200035d818362000417565b81010312620002e557508162000374869262000451565b38620000f4565b503d62000351565b9182813d8311620003bc575b6200039b818362000417565b81010312620002e55750602491620003b4849262000451565b9092620000bf565b503d6200038f565b87513d6000823e3d90fd5b8281939294503d83116200040a575b620003ea818362000417565b81010312620002e85751908682168203620002e557508286913862000096565b503d620003de565b600080fd5b601f909101601f19168101906001600160401b038211908210176200043b57604052565b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b0382168203620004125756fe60808060405260043610156200001f575b5036156200001d57600080fd5b005b600090813560e01c908163049aacfe1462002593575080630eb25ac2146200205a5780631b1bf9291462001e0b5780631e8b32301462001c0457806328f150eb1462001bbd578063320647701462001b76578063382dd1b914620018665780634d67869314620015d457806357fb1d6714620015a3578063715018a6146200154b57806379ba509714620014db5780637bc1599f14620012e25780638d58143914620010645780638da5cb5b146200103b578063bb8a7df11462000e51578063c5fa65711462000b5f578063de675a6d1462000b18578063e30c39781462000aed578063eca9b6801462000615578063ee8ca3b514620004ed578063f2fde38b146200047a578063f665d08914620003db5763fec6252003620000105734620003d857602080600319360112620003d4576001600160401b03600435818111620003d05736602382011215620003d0578060040135918211620003d057602492838201918436918560051b010111620003cc57604051632fe0c29360e21b80825290927f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691908385600481865afa948515620003c15788956200038c575b5060405184818062000209635b88f08960e01b998a8352339060048401620026f8565b0381875afa8015620003815762000229918a9162000366575b5062002711565b875b86811062000237578880f35b6200024481888462002c38565b3562000271575b60001981146200025e576001016200022b565b634e487b7160e01b895260116004528789fd5b6200027e81888462002c38565b35604051908482528682600481895afa8015620003205787908c906200032b575b620002bb9350604051809481928c8352339060048401620026f8565b0381895afa9182156200032057620002e692620002e0918d91620002ec575062002711565b62002b22565b6200024b565b620003119150893d8b1162000318575b62000308818362002689565b810190620026de565b3862000222565b503d620002fc565b6040513d8d823e3d90fd5b5082813d83116200035e575b62000343818362002689565b81010312620003595786620002bb92516200029f565b600080fd5b503d62000337565b620003119150863d8811620003185762000308818362002689565b6040513d8b823e3d90fd5b9094508381813d8311620003b9575b620003a7818362002689565b810103126200035957519338620001e6565b503d6200039b565b6040513d8a823e3d90fd5b8480fd5b8380fd5b5080fd5b80fd5b5034620003d8576020366003190112620003d857620003fc30331462002711565b807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316803b156200047757819060246040518094819363ee8ca3b560e01b835260043560048401525af180156200046c576200045e575080f35b620004699062002621565b80f35b6040513d84823e3d90fd5b50fd5b5034620003d8576020366003190112620003d85762000498620025d8565b620004a2620026c9565b600180546001600160a01b0319166001600160a01b0392831690811790915582549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227008380a380f35b5034620003d857602080600319360112620003d457604051632fe0c29360e21b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316908281600481855afa80156200060a5783918591620005d2575b5062000577926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa908115620005c75762000598928492620005a5575b505062002711565b6200046960043562002b22565b620005bf9250803d10620003185762000308818362002689565b388062000590565b6040513d85823e3d90fd5b82819392503d831162000602575b620005ec818362002689565b81010312620003d0575182906200057762000553565b503d620005e0565b6040513d86823e3d90fd5b5034620003d8576080366003190112620003d85762000633620025d8565b6001600160a01b039060243582811690819003620003d057604435936001600160401b038511620003d85736602386011215620003d85784600401356200067a81620026ad565b906200068a604051928362002689565b808252366024828901011162000ae9576024968184926020998a930183860137830101526064359385851680950362000ae957604051632fe0c29360e21b81527f00000000000000000000000000000000000000000000000000000000000000008716908881600481855afa90811562000aa657908991869162000ab1575b506200072d926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a57906200074d918591620002ec575062002711565b62000788867f000000000000000000000000000000000000000000000000000000000000000016966200078088620029cb565b9216620029cb565b946004886200079787620029cb565b966040519283809263313ce56760e01b82525afa801562000aa657859062000a67575b620007c9915060ff1662002851565b90620007d590620029cb565b620007e04662002851565b916040519687948b860160c0905260e08601620007fd916200280f565b98601f19998a87820301604088015262000817916200280f565b898682030160608701526200082c916200280f565b8885820301608086015262000841916200280f565b878482030160a085015262000856916200280f565b868382030160c08401526200086b916200280f565b0384810184526200087d908462002689565b604051906200088c82620025ef565b600182526200089d87830162002769565b604051620008ab81620025ef565b60018152873681830137620008c083620027c9565b52620008cc82620027c9565b50620008d882620027c9565b51620008e490620027c9565b7fdecf7219f1c85ce57b6bf329dc23a8bc7248adf1387a4afc7fd638153d6a8f1090526040519462000916866200266d565b60038652606036898801376040519362000930856200266d565b6003855262000941898601620027a7565b604051966200095088620025ef565b8088528988019586526200096490620027c9565b6002905286516200097590620027ed565b6004905286516200098690620027fe565b6005905260405190620009998262002651565b8152845190620009a982620027c9565b52620009b590620027c9565b5060405180928982016040905260608201620009d1916200280f565b82828203016040830152620009e790876200280f565b039081018252620009f9908262002689565b82519062000a0782620027ed565b5262000a1390620027ed565b5062000a20908562002c66565b90519062000a2e82620027fe565b5262000a3a90620027fe565b5062000a469262002d50565b604051828282526000805160206200342583398151915291a1604051908152f35b508881813d831162000a9e575b62000a80818362002689565b81010312620003cc575160ff81168103620003cc5760ff90620007ba565b503d62000a74565b6040513d87823e3d90fd5b82819392503d831162000ae1575b62000acb818362002689565b81010312620003cc575188906200072d62000709565b503d62000abf565b8280fd5b5034620003d85780600319360112620003d8576001546040516001600160a01b039091168152602090f35b5034620003d85780600319360112620003d8576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5034620003d857602080600319360112620003d45760043560018060a01b03807f000000000000000000000000000000000000000000000000000000000000000016604051632fe0c29360e21b81528481600481855afa801562000e46578591879162000e0a575b5062000beb926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa801562000aa65762000c0991869162000def575062002711565b60405163167df74d60e11b84820152600481529062000c2882620025ef565b6040519262000c37846200266d565b600384526060368686013760405162000c50816200266d565b6003815262000c61868201620027a7565b600262000c856040519662000c7688620025ef565b808852888801938452620027c9565b52600362000c948651620027ed565b52600562000ca38651620027fe565b5262000cce60405162000cb68162002651565b88815282519062000cc782620027c9565b52620027c9565b5062000cf960405162000ce18162002651565b88815282519062000cf282620027ed565b52620027ed565b50610258820180921162000ddb57949562000dbb9562000d92926001600160801b039262000d7e9162000d2e90851662002aba565b9360405194168a850152620493e060408501526040845262000d508462002635565b62000d6f6040519485928c84015260408084015260608301906200280f565b03601f19810184528362002689565b519062000d8b82620027fe565b52620027fe565b507f00000000000000000000000000000000000000000000000000000000000000001662002d50565b6000805160206200342583398151915282604051838152a1604051908152f35b634e487b7160e01b87526011600452602487fd5b620003119150853d8711620003185762000308818362002689565b82819392503d831162000e3e575b62000e24818362002689565b8101031262000e3a5751849062000beb62000bc7565b8580fd5b503d62000e18565b6040513d88823e3d90fd5b5034620003d857602080600319360112620003d45760043560018060a01b03807f000000000000000000000000000000000000000000000000000000000000000016604051632fe0c29360e21b81528481600481855afa801562000e46578591879162001003575b5062000edd926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa801562000aa65762000efb91869162000def575062002711565b604051635136e46b60e01b84820152600481529062000f1a82620025ef565b6040519262000f29846200266d565b600384526060368686013760405162000f42816200266d565b6003815262000f53868201620027a7565b600262000f686040519662000c7688620025ef565b52600362000f778651620027ed565b52600562000f868651620027fe565b5262000f9960405162000cb68162002651565b5062000fac60405162000ce18162002651565b50610960820180921162000ddb57949562000dbb9562000d92926001600160801b039262000d7e9162000fe190851662002aba565b9360405194168a85015262249f0060408501526040845262000d508462002635565b82819392503d831162001033575b6200101d818362002689565b8101031262000e3a5751849062000edd62000eb9565b503d62001011565b5034620003d85780600319360112620003d857546040516001600160a01b039091168152602090f35b5034620003d857602080600319360112620003d457604051632fe0c29360e21b81526001600160a01b03929060048035917f00000000000000000000000000000000000000000000000000000000000000008616918590829081855afa9081156200060a579085918591620012aa575b50620010f8926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa908115620005c757906200111891849162000def575062002711565b610e108101809111620012965742811115620012585762000dbb929362000d9260405192637c968b2d60e11b87850152600484526200115784620025ef565b6040519462001166866200266d565b600386526060368988013762000d7e6040519162001184836200266d565b60038352620011958a8401620027a7565b6002620011b960405199620011aa8b620025ef565b808b528c8b01958652620027c9565b526003620011c88951620027ed565b526005620011d78951620027fe565b52620011fb604051620011ea8162002651565b82815284519062000cc782620027c9565b506200121f6040516200120e8162002651565b82815284519062000cf282620027ed565b506001600160801b03936200123690851662002aba565b9360405194168a8501526201d4c060408501526040845262000d508462002635565b60405162461bcd60e51b8152600481018490526016602482015275496e76616c696420657865637574696f6e2074696d6560501b6044820152606490fd5b634e487b7160e01b82526011600452602482fd5b82819392503d8311620012da575b620012c4818362002689565b81010312620003d057518490620010f8620010d4565b503d620012b8565b5034620003d8576040366003190112620003d857604051632fe0c29360e21b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116926020929091908381600481885afa908115620005c7578391620014a5575b50839062001373956040518080988194635b88f08960e01b8352339060048401620026f8565b03915afa9384156200046c5762000dbb93946200139891849162000366575062002711565b60405163972134bd60e01b858201526004815290620013b782620025ef565b62000d9260405193620013ca8562002635565b6002855260403688870137604051620013e38162002635565b60028152620013f488820162002788565b600262001418604051976200140989620025ef565b8089528a8901938452620027c9565b526005620014278751620027ed565b526200144b6040516200143a8162002651565b83815282519062000cc782620027c9565b506001600160801b0391620014989062001469600435851662002aba565b9362001479816024351662002aba565b8160405196168c8701521660408501526040845262000d508462002635565b519062000cf282620027ed565b90508381813d8311620014d3575b620014bf818362002689565b8101031262000ae95751620013736200134d565b503d620014b3565b5034620003d85780600319360112620003d8576001546001600160a01b03338183160362001533576001600160a01b03199182166001558254339281168317845516600080516020620034458339815191528380a380f35b60405163118cdaa760e01b8152336004820152602490fd5b5034620003d85780600319360112620003d85762001568620026c9565b600180546001600160a01b03199081169091558154908116825581906001600160a01b0316600080516020620034458339815191528280a380f35b5034620003d85780600319360112620003d8576020604051737506c12a824d73d9b08564d5afc22c949434755e8152f35b5034620003d857602080600319360112620003d457620015f3620025d8565b604051632fe0c29360e21b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116949290918481600481895afa9081156200060a57849162001830575b5084906200166d966040518080998194635b88f08960e01b8352339060048401620026f8565b03915afa948515620005c75762000dbb94956200169291859162001815575062002711565b6200180e85620018006040519463fa646c0f60e01b8387015286602487015260248652620016c08662002635565b60405190620016cf82620025ef565b60018252620016e084830162002769565b604051620016ee81620025ef565b600181528436818301376200170383620027c9565b526200170f82620027c9565b507fbeceec363279a98e3e7625e641ada68d6ba3b5e9c737658fa2c65540b7024390620017476200174084620027c9565b51620027c9565b52620017d7604051986200175b8a62002635565b60028a52604036878c01376002620017a88b604051986200177c8a62002635565b838a526200178c818b0162002788565b6040519d8e6200179c81620025ef565b528d01988952620027c9565b526005620017b78b51620027ed565b5260405190620017c78262002651565b815285519062000cc782620027c9565b507f00000000000000000000000000000000000000000000000000000000000000001662002c66565b90519062000cf282620027ed565b5062002d50565b620003119150873d8911620003185762000308818362002689565b90508481813d83116200185e575b6200184a818362002689565b81010312620003d057516200166d62001647565b503d6200183e565b5034620003d85780600319360112620003d857604051632fe0c29360e21b81526020906001600160a01b03907f00000000000000000000000000000000000000000000000000000000000000008216908381600481855afa801562000aa6578491869162001b3e575b50620018f3926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa80156200060a576200191191859162001b23575062002711565b60405191635c08631b60e11b835283604084600481867f0000000000000000000000000000000000000000000000000000000000000000165afa801562001b16578194829162001ac9575b5083169282919073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee850362001a2057508080809350867f00000000000000000000000000000000000000000000000000000000000000005af1620019b362002aed565b5015620019dc579160409160008051602062003465833981519152935b8351928352820152a180f35b6064906040519062461bcd60e51b82526004820152601e60248201527f5f7472616e736665723a20455448207472616e73666572206661696c656400006044820152fd5b6040518381019163a9059cbb60e01b83527f00000000000000000000000000000000000000000000000000000000000000001660248201528660448201526044815262001a6d816200266d565b519082865af115620005c75783513d62001abf5750813b155b62001aa657916040916000805160206200346583398151915293620019d0565b604051635274afe760e01b815260048101839052602490fd5b6001141562001a86565b945050506040833d60401162001b0d575b8162001ae96040938362002689565b81010312620003d05780835193015192848385168503620003d8579093836200195c565b3d915062001ada565b50604051903d90823e3d90fd5b620003119150843d8611620003185762000308818362002689565b82819392503d831162001b6e575b62001b58818362002689565b81010312620003cc57518390620018f3620018cf565b503d62001b4c565b5034620003d85780600319360112620003d8576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5034620003d85780600319360112620003d8576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b5034620003d85760209081600319360112620003d85762001c24620025d8565b604051632fe0c29360e21b81526001600160a01b03907f00000000000000000000000000000000000000000000000000000000000000008216908581600481855afa90811562000aa657908691869162001dd3575b5062001c9d926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a579062001cbd91859162000366575062002711565b6040517f000000000000000000000000000000000000000000000000000000000000000082169190610519808201906001600160401b0382118383101762001dbf578486849362001d149362002f0c86396200274f565b039085f080156200060a571692813b15620003d85780604051809363dc0fabb960e01b825281838162001d4c8a8a600484016200274f565b03925af190811562001db357509183917f94486d29be05652f2d4a4397f6844e1132cca644b21fa60d0fa88d28b1241a649362001da1575b5062001d96604051928392836200274f565b0390a1604051908152f35b62001dac9062002621565b3862001d84565b604051903d90823e3d90fd5b634e487b7160e01b87526041600452602487fd5b82819392503d831162001e03575b62001ded818362002689565b81010312620003cc5751859062001c9d62001c79565b503d62001de1565b5034620003d85780600319360112620003d857604051632fe0c29360e21b81526020906001600160a01b03907f00000000000000000000000000000000000000000000000000000000000000008216908381600481855afa801562000aa6578491869162002022575b5062001e98926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a57849162001ebe9162000dbb95969162000366575062002711565b6040516338307da760e21b85820152600481529062001edd82620025ef565b6200180e6040519162001ef083620025ef565b6001835262001f0187840162002769565b60405162001f0f81620025ef565b6001815287368183013762001f2484620027c9565b5262001f3083620027c9565b507f083ec7dd5ce4b120c28de7d7eb2f81d800263f849e3d088a179a28ae5b4595a162001f616200174085620027c9565b52620018006040519562001f758762002635565b600287526040368a89013762001ff76040519362001f938562002635565b6002855262001fa48b860162002788565b600262001fc86040519a62001fb98c620025ef565b808c528d8c01978852620027c9565b52600562001fd78a51620027ed565b526040519062001fe78262002651565b815284519062000cc782620027c9565b507f000000000000000000000000000000000000000000000000000000000000000016938462002c66565b82819392503d831162002052575b6200203c818362002689565b81010312620003cc5751839062001e9862001e74565b503d62002030565b5034620003d8576020366003190112620003d85762002078620025d8565b604051632fe0c29360e21b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690602081600481855afa9081156200060a57849162002558575b50602090620020f0926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa8015620005c7576200210e9184916200253b575062002711565b6040519063fa646c0f60e01b60208301526001602483015260248252620021358262002635565b604051906200214482620025ef565b600182526020820191620021588362002769565b6040516200216681620025ef565b60018152602036818301376200217c82620027c9565b526200218881620027c9565b507fa12c51e240c4b482074f79da6d7c0fd986892c4244775dd32386e6a3afb07e3b620021b96200174083620027c9565b5260405192620021c98462002635565b60028452604036602086013760026200221860405195620021ea8762002635565b828752620021fb6020880162002788565b604051966200220a88620025ef565b8188526020880152620027c9565b526005620022278551620027ed565b526200224e6040516200223a8162002651565b87815260208601519062000cc782620027c9565b5060405191608083019060018060a01b037f0000000000000000000000000000000000000000000000000000000000000000166020850152606060408501525180915260a083019060a08160051b850101929188905b828210620024d85750505050620022eb620022f8836200230993600760608301520393620022db601f199586810183528262002689565b6040519283916020830162002c49565b0384810183528262002689565b60208501519062000cf282620027ed565b50604051633323b46760e01b81526001600160a01b039092166004830152608060248301529092839190620023439060848401906200280f565b92600319838503016044840152604084019080519160408652825180915260206060870193019088905b808210620024985750505060200151936020818303910152835190818152602081016020808460051b84010196019388925b848410620024665773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee60648801528987602081808c0381857f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af19081156200046c5782916200242a575b6020826000805160206200342583398151915282604051838152a1604051908152f35b90506020813d6020116200245d575b81620024486020938362002689565b81010312620003d45760209150518262002407565b3d915062002439565b9193955091939560208062002486838686600196030188528a516200280f565b9801940194019187959394916200239f565b9180965093909293516006811015620024c457602082819260019452019601920187959392916200236d565b634e487b7160e01b8a52602160045260248afd5b90919293609f989597969819888203018252845190602080835192838152019201908b905b80821062002522575050506020806001929601920192019092919795969497620022a4565b90919260208060019286518152019401920190620024fd565b62000311915060203d602011620003185762000308818362002689565b90506020813d6020116200258a575b81620025766020938362002689565b81010312620003d05751620020f0620020c9565b3d915062002567565b905034620003d45781600319360112620003d4577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b600435906001600160a01b03821682036200035957565b604081019081106001600160401b038211176200260b57604052565b634e487b7160e01b600052604160045260246000fd5b6001600160401b0381116200260b57604052565b606081019081106001600160401b038211176200260b57604052565b602081019081106001600160401b038211176200260b57604052565b608081019081106001600160401b038211176200260b57604052565b601f909101601f19168101906001600160401b038211908210176200260b57604052565b6001600160401b0381116200260b57601f01601f191660200190565b6000546001600160a01b031633036200153357565b908160209103126200035957518015158103620003595790565b9081526001600160a01b03909116602082015260400190565b156200271957565b60405162461bcd60e51b815260206004820152600e60248201526d139bdd08185d5d1a1bdc9a5e995960921b6044820152606490fd5b6001600160a01b0391821681529116602082015260400190565b60005b6020811062002779575050565b6060828201526020016200276c565b60005b6040811062002798575050565b6060828201526020016200278b565b9060005b606080821015620027c35783820152602001620027ab565b50509050565b805115620027d75760200190565b634e487b7160e01b600052603260045260246000fd5b805160011015620027d75760400190565b805160021015620027d75760600190565b919082519283825260005b8481106200283c575050826000602080949584010152601f8019910116010190565b6020818301810151848301820152016200281a565b6000908072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b80821015620029bc575b506904ee2d6d415b85acef8160201b80831015620029ac575b50662386f26fc10000808310156200299c575b506305f5e100808310156200298c575b50612710808310156200297c575b5060648210156200296b575b600a8092101562002960575b60019081602181860195620028ed87620026ad565b96620028fd604051988962002689565b8088526200290e601f1991620026ad565b01366020890137860101905b62002927575b5050505090565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a8353049182156200295a579190826200291a565b62002920565b9160010191620028d8565b9190606460029104910191620028cc565b60049193920491019138620028c0565b60089193920491019138620028b2565b60109193920491019138620028a2565b602091939204910191386200288f565b60409350810491503862002876565b8060405191620029db8362002635565b602a835260208084016040368237845115620027d75760309053835190600191821015620027d75790607860218601536029915b81831162002a425750505062002a23575090565b6044906040519063e22e27eb60e01b8252600482015260146024820152fd5b909192600f8116601081101562002aa557865185101562002aa5576f181899199a1a9b1b9c1cb0b131b232b360811b901a86850183015360041c92801562002a905760001901919062002a0f565b60246000634e487b7160e01b81526011600452fd5b60246000634e487b7160e01b81526032600452fd5b6001600160801b039081166103e8029081169190820362002ad757565b634e487b7160e01b600052601160045260246000fd5b3d1562002b1d573d9062002b0182620026ad565b9162002b11604051938462002689565b82523d6000602084013e565b606090565b801562002bf95760405190602082019163f665d08960e01b83528160248201526024815262002b518162002635565b600080938192519082305af162002b6762002aed565b501562002c09577fd2b8cd190f54408a8e1f68c863951d8b6515b9694fef3330e5942ac18a1989996020604051838152a17f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690813b1562000ae9578291602483926040519586938492632d2b42d160e11b845260048401525af190811562001db3575062002bfc575b50565b62002c079062002621565b565b7fb975133a729b6e748425f7ad2ac304f2111a2f986c4daa4a769a3cd89d68a1499150602090604051908152a1565b9190811015620027d75760051b0190565b90604062002c63926002815281602082015201906200280f565b90565b906040519182608081019260209260018060a01b03168383015260606040830152805180945260a08201938360a08260051b850101920190600095865b82881062002cf1575050505062002c63935060076060830152039062002cd2601f199283810186528562002689565b62002ce4604051948592830162002c49565b0390810183528262002689565b9194509194809693609f1989820301845286519082808351928381520192019084905b80821062002d3657505050908060019297019301930195949287949162002ca3565b919380600192948651815201940192018993929162002d14565b6040518093633323b46760e01b825260018060a01b039081600494168484015262002d8860249560808786015260848501906200280f565b906003198483030160448501526040820190805195604084528651809352606084019260209889809901926000915b83831062002ec3575050505050850151918581830391015281518082528582019186808360051b8301019401926000915b83831062002e8f575050505050600083809273eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee606483015203927f0000000000000000000000000000000000000000000000000000000000000000165af190811562002e835760009162002e51575b50905090565b82813d831162002e7b575b62002e68818362002689565b81010312620003d8575051803862002e4b565b503d62002e5c565b6040513d6000823e3d90fd5b929597809194975062002eb060019396601f1986820301875289516200280f565b9701930193018895938897959262002de8565b92959194969850928097995051600681101562002ef7578a8281926001945201970193018a979593928a9997959262002db7565b82602185634e487b7160e01b600052526000fdfe60e03461013857601f61051938819003918201601f19168301916001600160401b0383118484101761013d57808492604094855283398101031261013857610052602061004b83610153565b9201610153565b6001600160a01b039082821615610104571680156100bf576080523360a05260c0526040516103b19081610168823960805181818160d5015281816101720152610309015260a051818181608b01526102c5015260c051818181610115015281816101b1015261034c0152f35b60405162461bcd60e51b815260206004820152601460248201527f5a65726f206d616e6167657220616464726573730000000000000000000000006044820152606490fd5b60405162461bcd60e51b815260206004820152600c60248201526b5a65726f206164647265737360a01b6044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036101385756fe608060409080825260048036101561001657600080fd5b600091823560e01c908163412764911461033857508063481c6a75146102f4578063a50a640e146102b05763fa646c0f1461005057600080fd5b346102ac57602092836003193601126101f35781359360028510156102a85781516328f150eb60e01b81526001600160a01b039190818186817f000000000000000000000000000000000000000000000000000000000000000087165afa90811561029e579083918791610238575b501633036101f7575083941560001461016c57807f00000000000000000000000000000000000000000000000000000000000000001692833b1561016857602485928385519687948593630cf1cfb560e11b85527f000000000000000000000000000000000000000000000000000000000000000016908401525af190811561015f575061014c57505080f35b6101559061037b565b61015c5780f35b80fd5b513d84823e3d90fd5b8480fd5b929091837f00000000000000000000000000000000000000000000000000000000000000001693843b156101f3576024908385519687948593638cc7d7a960e01b85527f000000000000000000000000000000000000000000000000000000000000000016908401525af190811561015f57506101e7575080f35b6101f09061037b565b80f35b8280fd5b8360649184519162461bcd60e51b8352820152601c60248201527b2ab730baba3437b934bd32b21032bc32b1baba37b91031b0b63632b960211b6044820152fd5b915050813d8311610297575b601f8101601f191682016001600160401b03811183821017610284578391839187528101031261028057518281168103610280578290386100bf565b8580fd5b634e487b7160e01b885260418752602488fd5b503d610244565b84513d88823e3d90fd5b8380fd5b5080fd5b8284346102ac57816003193601126102ac57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b8284346102ac57816003193601126102ac57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b8390346102ac57816003193601126102ac577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b6001600160401b03811161038e57604052565b634e487b7160e01b600052604160045260246000fdfea164736f6c6343000814000ab66c33d8dd981a05324331a06b40246adf774342c5561bc733d6134dd466a19e8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e024e583ad06c0a341b20a393419bb6b35dd48f347397d061a8531a73804420263a164736f6c6343000814000a0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c9000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e

Deployed Bytecode

0x60808060405260043610156200001f575b5036156200001d57600080fd5b005b600090813560e01c908163049aacfe1462002593575080630eb25ac2146200205a5780631b1bf9291462001e0b5780631e8b32301462001c0457806328f150eb1462001bbd578063320647701462001b76578063382dd1b914620018665780634d67869314620015d457806357fb1d6714620015a3578063715018a6146200154b57806379ba509714620014db5780637bc1599f14620012e25780638d58143914620010645780638da5cb5b146200103b578063bb8a7df11462000e51578063c5fa65711462000b5f578063de675a6d1462000b18578063e30c39781462000aed578063eca9b6801462000615578063ee8ca3b514620004ed578063f2fde38b146200047a578063f665d08914620003db5763fec6252003620000105734620003d857602080600319360112620003d4576001600160401b03600435818111620003d05736602382011215620003d0578060040135918211620003d057602492838201918436918560051b010111620003cc57604051632fe0c29360e21b80825290927f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c96001600160a01b031691908385600481865afa948515620003c15788956200038c575b5060405184818062000209635b88f08960e01b998a8352339060048401620026f8565b0381875afa8015620003815762000229918a9162000366575b5062002711565b875b86811062000237578880f35b6200024481888462002c38565b3562000271575b60001981146200025e576001016200022b565b634e487b7160e01b895260116004528789fd5b6200027e81888462002c38565b35604051908482528682600481895afa8015620003205787908c906200032b575b620002bb9350604051809481928c8352339060048401620026f8565b0381895afa9182156200032057620002e692620002e0918d91620002ec575062002711565b62002b22565b6200024b565b620003119150893d8b1162000318575b62000308818362002689565b810190620026de565b3862000222565b503d620002fc565b6040513d8d823e3d90fd5b5082813d83116200035e575b62000343818362002689565b81010312620003595786620002bb92516200029f565b600080fd5b503d62000337565b620003119150863d8811620003185762000308818362002689565b6040513d8b823e3d90fd5b9094508381813d8311620003b9575b620003a7818362002689565b810103126200035957519338620001e6565b503d6200039b565b6040513d8a823e3d90fd5b8480fd5b8380fd5b5080fd5b80fd5b5034620003d8576020366003190112620003d857620003fc30331462002711565b807f000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e6001600160a01b0316803b156200047757819060246040518094819363ee8ca3b560e01b835260043560048401525af180156200046c576200045e575080f35b620004699062002621565b80f35b6040513d84823e3d90fd5b50fd5b5034620003d8576020366003190112620003d85762000498620025d8565b620004a2620026c9565b600180546001600160a01b0319166001600160a01b0392831690811790915582549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227008380a380f35b5034620003d857602080600319360112620003d457604051632fe0c29360e21b81527f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c96001600160a01b0316908281600481855afa80156200060a5783918591620005d2575b5062000577926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa908115620005c75762000598928492620005a5575b505062002711565b6200046960043562002b22565b620005bf9250803d10620003185762000308818362002689565b388062000590565b6040513d85823e3d90fd5b82819392503d831162000602575b620005ec818362002689565b81010312620003d0575182906200057762000553565b503d620005e0565b6040513d86823e3d90fd5b5034620003d8576080366003190112620003d85762000633620025d8565b6001600160a01b039060243582811690819003620003d057604435936001600160401b038511620003d85736602386011215620003d85784600401356200067a81620026ad565b906200068a604051928362002689565b808252366024828901011162000ae9576024968184926020998a930183860137830101526064359385851680950362000ae957604051632fe0c29360e21b81527f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98716908881600481855afa90811562000aa657908991869162000ab1575b506200072d926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a57906200074d918591620002ec575062002711565b62000788867f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e16966200078088620029cb565b9216620029cb565b946004886200079787620029cb565b966040519283809263313ce56760e01b82525afa801562000aa657859062000a67575b620007c9915060ff1662002851565b90620007d590620029cb565b620007e04662002851565b916040519687948b860160c0905260e08601620007fd916200280f565b98601f19998a87820301604088015262000817916200280f565b898682030160608701526200082c916200280f565b8885820301608086015262000841916200280f565b878482030160a085015262000856916200280f565b868382030160c08401526200086b916200280f565b0384810184526200087d908462002689565b604051906200088c82620025ef565b600182526200089d87830162002769565b604051620008ab81620025ef565b60018152873681830137620008c083620027c9565b52620008cc82620027c9565b50620008d882620027c9565b51620008e490620027c9565b7fdecf7219f1c85ce57b6bf329dc23a8bc7248adf1387a4afc7fd638153d6a8f1090526040519462000916866200266d565b60038652606036898801376040519362000930856200266d565b6003855262000941898601620027a7565b604051966200095088620025ef565b8088528988019586526200096490620027c9565b6002905286516200097590620027ed565b6004905286516200098690620027fe565b6005905260405190620009998262002651565b8152845190620009a982620027c9565b52620009b590620027c9565b5060405180928982016040905260608201620009d1916200280f565b82828203016040830152620009e790876200280f565b039081018252620009f9908262002689565b82519062000a0782620027ed565b5262000a1390620027ed565b5062000a20908562002c66565b90519062000a2e82620027fe565b5262000a3a90620027fe565b5062000a469262002d50565b604051828282526000805160206200342583398151915291a1604051908152f35b508881813d831162000a9e575b62000a80818362002689565b81010312620003cc575160ff81168103620003cc5760ff90620007ba565b503d62000a74565b6040513d87823e3d90fd5b82819392503d831162000ae1575b62000acb818362002689565b81010312620003cc575188906200072d62000709565b503d62000abf565b8280fd5b5034620003d85780600319360112620003d8576001546040516001600160a01b039091168152602090f35b5034620003d85780600319360112620003d8576040517f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c96001600160a01b03168152602090f35b5034620003d857602080600319360112620003d45760043560018060a01b03807f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c916604051632fe0c29360e21b81528481600481855afa801562000e46578591879162000e0a575b5062000beb926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa801562000aa65762000c0991869162000def575062002711565b60405163167df74d60e11b84820152600481529062000c2882620025ef565b6040519262000c37846200266d565b600384526060368686013760405162000c50816200266d565b6003815262000c61868201620027a7565b600262000c856040519662000c7688620025ef565b808852888801938452620027c9565b52600362000c948651620027ed565b52600562000ca38651620027fe565b5262000cce60405162000cb68162002651565b88815282519062000cc782620027c9565b52620027c9565b5062000cf960405162000ce18162002651565b88815282519062000cf282620027ed565b52620027ed565b50610258820180921162000ddb57949562000dbb9562000d92926001600160801b039262000d7e9162000d2e90851662002aba565b9360405194168a850152620493e060408501526040845262000d508462002635565b62000d6f6040519485928c84015260408084015260608301906200280f565b03601f19810184528362002689565b519062000d8b82620027fe565b52620027fe565b507f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e1662002d50565b6000805160206200342583398151915282604051838152a1604051908152f35b634e487b7160e01b87526011600452602487fd5b620003119150853d8711620003185762000308818362002689565b82819392503d831162000e3e575b62000e24818362002689565b8101031262000e3a5751849062000beb62000bc7565b8580fd5b503d62000e18565b6040513d88823e3d90fd5b5034620003d857602080600319360112620003d45760043560018060a01b03807f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c916604051632fe0c29360e21b81528481600481855afa801562000e46578591879162001003575b5062000edd926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa801562000aa65762000efb91869162000def575062002711565b604051635136e46b60e01b84820152600481529062000f1a82620025ef565b6040519262000f29846200266d565b600384526060368686013760405162000f42816200266d565b6003815262000f53868201620027a7565b600262000f686040519662000c7688620025ef565b52600362000f778651620027ed565b52600562000f868651620027fe565b5262000f9960405162000cb68162002651565b5062000fac60405162000ce18162002651565b50610960820180921162000ddb57949562000dbb9562000d92926001600160801b039262000d7e9162000fe190851662002aba565b9360405194168a85015262249f0060408501526040845262000d508462002635565b82819392503d831162001033575b6200101d818362002689565b8101031262000e3a5751849062000edd62000eb9565b503d62001011565b5034620003d85780600319360112620003d857546040516001600160a01b039091168152602090f35b5034620003d857602080600319360112620003d457604051632fe0c29360e21b81526001600160a01b03929060048035917f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98616918590829081855afa9081156200060a579085918591620012aa575b50620010f8926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa908115620005c757906200111891849162000def575062002711565b610e108101809111620012965742811115620012585762000dbb929362000d9260405192637c968b2d60e11b87850152600484526200115784620025ef565b6040519462001166866200266d565b600386526060368988013762000d7e6040519162001184836200266d565b60038352620011958a8401620027a7565b6002620011b960405199620011aa8b620025ef565b808b528c8b01958652620027c9565b526003620011c88951620027ed565b526005620011d78951620027fe565b52620011fb604051620011ea8162002651565b82815284519062000cc782620027c9565b506200121f6040516200120e8162002651565b82815284519062000cf282620027ed565b506001600160801b03936200123690851662002aba565b9360405194168a8501526201d4c060408501526040845262000d508462002635565b60405162461bcd60e51b8152600481018490526016602482015275496e76616c696420657865637574696f6e2074696d6560501b6044820152606490fd5b634e487b7160e01b82526011600452602482fd5b82819392503d8311620012da575b620012c4818362002689565b81010312620003d057518490620010f8620010d4565b503d620012b8565b5034620003d8576040366003190112620003d857604051632fe0c29360e21b81526001600160a01b037f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98116926020929091908381600481885afa908115620005c7578391620014a5575b50839062001373956040518080988194635b88f08960e01b8352339060048401620026f8565b03915afa9384156200046c5762000dbb93946200139891849162000366575062002711565b60405163972134bd60e01b858201526004815290620013b782620025ef565b62000d9260405193620013ca8562002635565b6002855260403688870137604051620013e38162002635565b60028152620013f488820162002788565b600262001418604051976200140989620025ef565b8089528a8901938452620027c9565b526005620014278751620027ed565b526200144b6040516200143a8162002651565b83815282519062000cc782620027c9565b506001600160801b0391620014989062001469600435851662002aba565b9362001479816024351662002aba565b8160405196168c8701521660408501526040845262000d508462002635565b519062000cf282620027ed565b90508381813d8311620014d3575b620014bf818362002689565b8101031262000ae95751620013736200134d565b503d620014b3565b5034620003d85780600319360112620003d8576001546001600160a01b03338183160362001533576001600160a01b03199182166001558254339281168317845516600080516020620034458339815191528380a380f35b60405163118cdaa760e01b8152336004820152602490fd5b5034620003d85780600319360112620003d85762001568620026c9565b600180546001600160a01b03199081169091558154908116825581906001600160a01b0316600080516020620034458339815191528280a380f35b5034620003d85780600319360112620003d8576020604051737506c12a824d73d9b08564d5afc22c949434755e8152f35b5034620003d857602080600319360112620003d457620015f3620025d8565b604051632fe0c29360e21b81526001600160a01b037f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98116949290918481600481895afa9081156200060a57849162001830575b5084906200166d966040518080998194635b88f08960e01b8352339060048401620026f8565b03915afa948515620005c75762000dbb94956200169291859162001815575062002711565b6200180e85620018006040519463fa646c0f60e01b8387015286602487015260248652620016c08662002635565b60405190620016cf82620025ef565b60018252620016e084830162002769565b604051620016ee81620025ef565b600181528436818301376200170383620027c9565b526200170f82620027c9565b507fbeceec363279a98e3e7625e641ada68d6ba3b5e9c737658fa2c65540b7024390620017476200174084620027c9565b51620027c9565b52620017d7604051986200175b8a62002635565b60028a52604036878c01376002620017a88b604051986200177c8a62002635565b838a526200178c818b0162002788565b6040519d8e6200179c81620025ef565b528d01988952620027c9565b526005620017b78b51620027ed565b5260405190620017c78262002651565b815285519062000cc782620027c9565b507f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e1662002c66565b90519062000cf282620027ed565b5062002d50565b620003119150873d8911620003185762000308818362002689565b90508481813d83116200185e575b6200184a818362002689565b81010312620003d057516200166d62001647565b503d6200183e565b5034620003d85780600319360112620003d857604051632fe0c29360e21b81526020906001600160a01b03907f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98216908381600481855afa801562000aa6578491869162001b3e575b50620018f3926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa80156200060a576200191191859162001b23575062002711565b60405191635c08631b60e11b835283604084600481867f000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e165afa801562001b16578194829162001ac9575b5083169282919073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee850362001a2057508080809350867f00000000000000000000000092478c7eccb3c7a3932263712c1555dbaea7d56c5af1620019b362002aed565b5015620019dc579160409160008051602062003465833981519152935b8351928352820152a180f35b6064906040519062461bcd60e51b82526004820152601e60248201527f5f7472616e736665723a20455448207472616e73666572206661696c656400006044820152fd5b6040518381019163a9059cbb60e01b83527f00000000000000000000000092478c7eccb3c7a3932263712c1555dbaea7d56c1660248201528660448201526044815262001a6d816200266d565b519082865af115620005c75783513d62001abf5750813b155b62001aa657916040916000805160206200346583398151915293620019d0565b604051635274afe760e01b815260048101839052602490fd5b6001141562001a86565b945050506040833d60401162001b0d575b8162001ae96040938362002689565b81010312620003d05780835193015192848385168503620003d8579093836200195c565b3d915062001ada565b50604051903d90823e3d90fd5b620003119150843d8611620003185762000308818362002689565b82819392503d831162001b6e575b62001b58818362002689565b81010312620003cc57518390620018f3620018cf565b503d62001b4c565b5034620003d85780600319360112620003d8576040517f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e6001600160a01b03168152602090f35b5034620003d85780600319360112620003d8576040517f00000000000000000000000009526c98f33fd13c08a2ef1dbbd7ecef59d9d8f26001600160a01b03168152602090f35b5034620003d85760209081600319360112620003d85762001c24620025d8565b604051632fe0c29360e21b81526001600160a01b03907f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98216908581600481855afa90811562000aa657908691869162001dd3575b5062001c9d926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a579062001cbd91859162000366575062002711565b6040517f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e82169190610519808201906001600160401b0382118383101762001dbf578486849362001d149362002f0c86396200274f565b039085f080156200060a571692813b15620003d85780604051809363dc0fabb960e01b825281838162001d4c8a8a600484016200274f565b03925af190811562001db357509183917f94486d29be05652f2d4a4397f6844e1132cca644b21fa60d0fa88d28b1241a649362001da1575b5062001d96604051928392836200274f565b0390a1604051908152f35b62001dac9062002621565b3862001d84565b604051903d90823e3d90fd5b634e487b7160e01b87526041600452602487fd5b82819392503d831162001e03575b62001ded818362002689565b81010312620003cc5751859062001c9d62001c79565b503d62001de1565b5034620003d85780600319360112620003d857604051632fe0c29360e21b81526020906001600160a01b03907f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c98216908381600481855afa801562000aa6578491869162002022575b5062001e98926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa9081156200060a57849162001ebe9162000dbb95969162000366575062002711565b6040516338307da760e21b85820152600481529062001edd82620025ef565b6200180e6040519162001ef083620025ef565b6001835262001f0187840162002769565b60405162001f0f81620025ef565b6001815287368183013762001f2484620027c9565b5262001f3083620027c9565b507f083ec7dd5ce4b120c28de7d7eb2f81d800263f849e3d088a179a28ae5b4595a162001f616200174085620027c9565b52620018006040519562001f758762002635565b600287526040368a89013762001ff76040519362001f938562002635565b6002855262001fa48b860162002788565b600262001fc86040519a62001fb98c620025ef565b808c528d8c01978852620027c9565b52600562001fd78a51620027ed565b526040519062001fe78262002651565b815284519062000cc782620027c9565b507f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e16938462002c66565b82819392503d831162002052575b6200203c818362002689565b81010312620003cc5751839062001e9862001e74565b503d62002030565b5034620003d8576020366003190112620003d85762002078620025d8565b604051632fe0c29360e21b81527f0000000000000000000000001d21668877ad215c7c1018196f834ba01b6675c96001600160a01b031690602081600481855afa9081156200060a57849162002558575b50602090620020f0926040518080958194635b88f08960e01b8352339060048401620026f8565b03915afa8015620005c7576200210e9184916200253b575062002711565b6040519063fa646c0f60e01b60208301526001602483015260248252620021358262002635565b604051906200214482620025ef565b600182526020820191620021588362002769565b6040516200216681620025ef565b60018152602036818301376200217c82620027c9565b526200218881620027c9565b507fa12c51e240c4b482074f79da6d7c0fd986892c4244775dd32386e6a3afb07e3b620021b96200174083620027c9565b5260405192620021c98462002635565b60028452604036602086013760026200221860405195620021ea8762002635565b828752620021fb6020880162002788565b604051966200220a88620025ef565b8188526020880152620027c9565b526005620022278551620027ed565b526200224e6040516200223a8162002651565b87815260208601519062000cc782620027c9565b5060405191608083019060018060a01b037f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e166020850152606060408501525180915260a083019060a08160051b850101929188905b828210620024d85750505050620022eb620022f8836200230993600760608301520393620022db601f199586810183528262002689565b6040519283916020830162002c49565b0384810183528262002689565b60208501519062000cf282620027ed565b50604051633323b46760e01b81526001600160a01b039092166004830152608060248301529092839190620023439060848401906200280f565b92600319838503016044840152604084019080519160408652825180915260206060870193019088905b808210620024985750505060200151936020818303910152835190818152602081016020808460051b84010196019388925b848410620024665773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee60648801528987602081808c0381857f000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e6001600160a01b03165af19081156200046c5782916200242a575b6020826000805160206200342583398151915282604051838152a1604051908152f35b90506020813d6020116200245d575b81620024486020938362002689565b81010312620003d45760209150518262002407565b3d915062002439565b9193955091939560208062002486838686600196030188528a516200280f565b9801940194019187959394916200239f565b9180965093909293516006811015620024c457602082819260019452019601920187959392916200236d565b634e487b7160e01b8a52602160045260248afd5b90919293609f989597969819888203018252845190602080835192838152019201908b905b80821062002522575050506020806001929601920192019092919795969497620022a4565b90919260208060019286518152019401920190620024fd565b62000311915060203d602011620003185762000308818362002689565b90506020813d6020116200258a575b81620025766020938362002689565b81010312620003d05751620020f0620020c9565b3d915062002567565b905034620003d45781600319360112620003d4577f000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e6001600160a01b03168152602090f35b600435906001600160a01b03821682036200035957565b604081019081106001600160401b038211176200260b57604052565b634e487b7160e01b600052604160045260246000fd5b6001600160401b0381116200260b57604052565b606081019081106001600160401b038211176200260b57604052565b602081019081106001600160401b038211176200260b57604052565b608081019081106001600160401b038211176200260b57604052565b601f909101601f19168101906001600160401b038211908210176200260b57604052565b6001600160401b0381116200260b57601f01601f191660200190565b6000546001600160a01b031633036200153357565b908160209103126200035957518015158103620003595790565b9081526001600160a01b03909116602082015260400190565b156200271957565b60405162461bcd60e51b815260206004820152600e60248201526d139bdd08185d5d1a1bdc9a5e995960921b6044820152606490fd5b6001600160a01b0391821681529116602082015260400190565b60005b6020811062002779575050565b6060828201526020016200276c565b60005b6040811062002798575050565b6060828201526020016200278b565b9060005b606080821015620027c35783820152602001620027ab565b50509050565b805115620027d75760200190565b634e487b7160e01b600052603260045260246000fd5b805160011015620027d75760400190565b805160021015620027d75760600190565b919082519283825260005b8481106200283c575050826000602080949584010152601f8019910116010190565b6020818301810151848301820152016200281a565b6000908072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b80821015620029bc575b506904ee2d6d415b85acef8160201b80831015620029ac575b50662386f26fc10000808310156200299c575b506305f5e100808310156200298c575b50612710808310156200297c575b5060648210156200296b575b600a8092101562002960575b60019081602181860195620028ed87620026ad565b96620028fd604051988962002689565b8088526200290e601f1991620026ad565b01366020890137860101905b62002927575b5050505090565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a8353049182156200295a579190826200291a565b62002920565b9160010191620028d8565b9190606460029104910191620028cc565b60049193920491019138620028c0565b60089193920491019138620028b2565b60109193920491019138620028a2565b602091939204910191386200288f565b60409350810491503862002876565b8060405191620029db8362002635565b602a835260208084016040368237845115620027d75760309053835190600191821015620027d75790607860218601536029915b81831162002a425750505062002a23575090565b6044906040519063e22e27eb60e01b8252600482015260146024820152fd5b909192600f8116601081101562002aa557865185101562002aa5576f181899199a1a9b1b9c1cb0b131b232b360811b901a86850183015360041c92801562002a905760001901919062002a0f565b60246000634e487b7160e01b81526011600452fd5b60246000634e487b7160e01b81526032600452fd5b6001600160801b039081166103e8029081169190820362002ad757565b634e487b7160e01b600052601160045260246000fd5b3d1562002b1d573d9062002b0182620026ad565b9162002b11604051938462002689565b82523d6000602084013e565b606090565b801562002bf95760405190602082019163f665d08960e01b83528160248201526024815262002b518162002635565b600080938192519082305af162002b6762002aed565b501562002c09577fd2b8cd190f54408a8e1f68c863951d8b6515b9694fef3330e5942ac18a1989996020604051838152a17f0000000000000000000000003083b8a83ad08fb59e1968b21e3fc668da610e3e6001600160a01b031690813b1562000ae9578291602483926040519586938492632d2b42d160e11b845260048401525af190811562001db3575062002bfc575b50565b62002c079062002621565b565b7fb975133a729b6e748425f7ad2ac304f2111a2f986c4daa4a769a3cd89d68a1499150602090604051908152a1565b9190811015620027d75760051b0190565b90604062002c63926002815281602082015201906200280f565b90565b906040519182608081019260209260018060a01b03168383015260606040830152805180945260a08201938360a08260051b850101920190600095865b82881062002cf1575050505062002c63935060076060830152039062002cd2601f199283810186528562002689565b62002ce4604051948592830162002c49565b0390810183528262002689565b9194509194809693609f1989820301845286519082808351928381520192019084905b80821062002d3657505050908060019297019301930195949287949162002ca3565b919380600192948651815201940192018993929162002d14565b6040518093633323b46760e01b825260018060a01b039081600494168484015262002d8860249560808786015260848501906200280f565b906003198483030160448501526040820190805195604084528651809352606084019260209889809901926000915b83831062002ec3575050505050850151918581830391015281518082528582019186808360051b8301019401926000915b83831062002e8f575050505050600083809273eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee606483015203927f000000000000000000000000afd37d0558255aa687167560cd3aaeea75c2841e165af190811562002e835760009162002e51575b50905090565b82813d831162002e7b575b62002e68818362002689565b81010312620003d8575051803862002e4b565b503d62002e5c565b6040513d6000823e3d90fd5b929597809194975062002eb060019396601f1986820301875289516200280f565b9701930193018895938897959262002de8565b92959194969850928097995051600681101562002ef7578a8281926001945201970193018a979593928a9997959262002db7565b82602185634e487b7160e01b600052526000fdfe60e03461013857601f61051938819003918201601f19168301916001600160401b0383118484101761013d57808492604094855283398101031261013857610052602061004b83610153565b9201610153565b6001600160a01b039082821615610104571680156100bf576080523360a05260c0526040516103b19081610168823960805181818160d5015281816101720152610309015260a051818181608b01526102c5015260c051818181610115015281816101b1015261034c0152f35b60405162461bcd60e51b815260206004820152601460248201527f5a65726f206d616e6167657220616464726573730000000000000000000000006044820152606490fd5b60405162461bcd60e51b815260206004820152600c60248201526b5a65726f206164647265737360a01b6044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fd5b51906001600160a01b03821682036101385756fe608060409080825260048036101561001657600080fd5b600091823560e01c908163412764911461033857508063481c6a75146102f4578063a50a640e146102b05763fa646c0f1461005057600080fd5b346102ac57602092836003193601126101f35781359360028510156102a85781516328f150eb60e01b81526001600160a01b039190818186817f000000000000000000000000000000000000000000000000000000000000000087165afa90811561029e579083918791610238575b501633036101f7575083941560001461016c57807f00000000000000000000000000000000000000000000000000000000000000001692833b1561016857602485928385519687948593630cf1cfb560e11b85527f000000000000000000000000000000000000000000000000000000000000000016908401525af190811561015f575061014c57505080f35b6101559061037b565b61015c5780f35b80fd5b513d84823e3d90fd5b8480fd5b929091837f00000000000000000000000000000000000000000000000000000000000000001693843b156101f3576024908385519687948593638cc7d7a960e01b85527f000000000000000000000000000000000000000000000000000000000000000016908401525af190811561015f57506101e7575080f35b6101f09061037b565b80f35b8280fd5b8360649184519162461bcd60e51b8352820152601c60248201527b2ab730baba3437b934bd32b21032bc32b1baba37b91031b0b63632b960211b6044820152fd5b915050813d8311610297575b601f8101601f191682016001600160401b03811183821017610284578391839187528101031261028057518281168103610280578290386100bf565b8580fd5b634e487b7160e01b885260418752602488fd5b503d610244565b84513d88823e3d90fd5b8380fd5b5080fd5b8284346102ac57816003193601126102ac57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b8284346102ac57816003193601126102ac57517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b8390346102ac57816003193601126102ac577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b6001600160401b03811161038e57604052565b634e487b7160e01b600052604160045260246000fdfea164736f6c6343000814000ab66c33d8dd981a05324331a06b40246adf774342c5561bc733d6134dd466a19e8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e024e583ad06c0a341b20a393419bb6b35dd48f347397d061a8531a73804420263a164736f6c6343000814000a

Block Transaction Gas Used Reward
view all blocks ##produced##

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.