Overview
ETH Balance
ETH Value
$0.00Multichain Info
Latest 1 from a total of 1 transactions
| Transaction Hash | 
                                            
                                                Method 
                                            
                                            
                                         | 
                                            
                                                Block
                                            
                                            
                                         | 
                                            
                                                From
                                            
                                            
                                         | 
                                            
                                                To
                                            
                                            
                                         | |||||
|---|---|---|---|---|---|---|---|---|---|
| Deploy Once | 14822991 | 4 days ago | IN | 0 ETH | 0.00000412 | 
Latest 5 internal transactions
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 14822991 | 4 days ago | Contract Creation | 0 ETH | |||
| 14822991 | 4 days ago | Contract Creation | 0 ETH | |||
| 14822991 | 4 days ago | Contract Creation | 0 ETH | |||
| 14822991 | 4 days ago | Contract Creation | 0 ETH | |||
| 14822991 | 4 days ago | Contract Creation | 0 ETH | 
Cross-Chain Transactions
                                         Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0xcD97B810...5138236ab  The constructor portion of the code might be different and could alter the actual behaviour of the contract
                                        
                                    
                                Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { PermissionLib } from "@aragon/osx-commons-contracts/src/permission/PermissionLib.sol";
import { PermissionManager } from "@aragon/osx/core/permission/PermissionManager.sol";
import { VotingEscrow, Lock as LockNFT } from "@setup/GaugeVoterSetup_v1_4_0.sol";
import { Action } from "@aragon/osx-commons-contracts/src/executors/IExecutor.sol";
import { DAO } from "@aragon/osx/core/dao/DAO.sol";
import { ProxyLib } from "@aragon/osx-commons-contracts/src/utils/deployment/ProxyLib.sol";
import { AvKATVault } from "src/AvKATVault.sol";
import { VKatMetadata } from "src/VKatMetadata.sol";
import { AragonMerklAutoCompoundStrategy as AutoCompoundStrategy } from
    "src/strategies/AragonMerklAutoCompoundStrategy.sol";
import { deploySwapper } from "src/utils/Deployers.sol";
import { DefaultStrategy } from "src/strategies/DefaultStrategy.sol";
struct BaseContracts {
    address vault;
    address autoCompoundStrategy;
    address defaultStrategy;
    address vkatMetadata;
}
struct DeploymentParameters {
    address merklDistributor;
    address dao;
    address escrow;
}
struct Deployment {
    address vault;
    address autoCompoundStrategy;
    address defaultStrategy;
    address swapper;
    address vkatMetadata;
}
contract Factory {
    using ProxyLib for address;
    address private owner;
    BaseContracts internal bases;
    DeploymentParameters parameters;
    Deployment deps;
    constructor(BaseContracts memory _bases) {
        owner = msg.sender;
        bases = _bases;
    }
    function deployOnce(DeploymentParameters memory _params) public returns (Deployment memory) {
        if (owner != msg.sender) revert("NOT_OWNER");
        if (deps.vault != address(0)) revert("ALREADY_DEPLOYED");
        // ======== Deploys Vkat Related contracts ========
        deps.defaultStrategy = bases.defaultStrategy.deployUUPSProxy(
            abi.encodeCall(DefaultStrategy.initialize, (_params.dao, _params.escrow, address(0)))
        );
        deps.vault = bases.vault.deployUUPSProxy(
            abi.encodeCall(
                AvKATVault.initialize,
                (_params.dao, _params.escrow, deps.defaultStrategy, "Autocompounding vKAT", "avKAT")
            )
        );
        DefaultStrategy(deps.defaultStrategy).initializeOwner(deps.vault);
        address nftLock = VotingEscrow(_params.escrow).lockNFT();
        // deploy swapper
        deps.swapper = deploySwapper(_params.merklDistributor, _params.escrow);
        deps.vkatMetadata = bases.vkatMetadata.deployUUPSProxy(
            abi.encodeCall(VKatMetadata.initialize, (_params.dao, nftLock, new address[](0)))
        );
        deps.autoCompoundStrategy = bases.autoCompoundStrategy.deployUUPSProxy(
            abi.encodeCall(
                AutoCompoundStrategy.initialize,
                (_params.dao, _params.escrow, deps.swapper, deps.vault, _params.merklDistributor)
            )
        );
        Action[] memory actions = getActions(_params.dao, _params.escrow, nftLock, deps);
        DAO(payable(_params.dao)).execute(bytes32(uint256(uint160(address(this)))), actions, 0);
        return deps;
    }
    function getActions(
        address _dao,
        address _escrow,
        address _nftLock,
        Deployment memory _deps
    )
        internal
        view
        returns (Action[] memory)
    {
        PermissionLib.MultiTargetPermission[] memory permissions = new PermissionLib.MultiTargetPermission[](6);
        // VKatMetadata permissions
        permissions[0] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Grant,
            where: _deps.vkatMetadata,
            who: _dao,
            permissionId: VKatMetadata(_deps.vkatMetadata).ADMIN_ROLE(),
            condition: PermissionLib.NO_CONDITION
        });
        // compound strategy permissions
        permissions[1] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Grant,
            where: _deps.autoCompoundStrategy,
            who: _dao,
            permissionId: AutoCompoundStrategy(_deps.autoCompoundStrategy).AUTOCOMPOUND_STRATEGY_ADMIN_ROLE(),
            condition: PermissionLib.NO_CONDITION
        });
        // default strategy permissions
        permissions[2] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Grant,
            where: _deps.defaultStrategy,
            who: _dao,
            permissionId: DefaultStrategy(_deps.defaultStrategy).DEFAULT_STRATEGY_ADMIN_ROLE(),
            condition: PermissionLib.NO_CONDITION
        });
        // vault permissions
        permissions[3] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Grant,
            where: _deps.vault,
            who: _dao,
            permissionId: AvKATVault(_deps.vault).VAULT_ADMIN_ROLE(),
            condition: PermissionLib.NO_CONDITION
        });
        permissions[4] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Grant,
            where: _deps.vault,
            who: _dao,
            permissionId: AvKATVault(_deps.vault).SWEEPER_ROLE(),
            condition: PermissionLib.NO_CONDITION
        });
        // This factory needs execute permission on dao to work.
        // This revokes execute permission as all other work
        // has been done at this point.
        permissions[5] = PermissionLib.MultiTargetPermission({
            operation: PermissionLib.Operation.Revoke,
            where: _dao,
            who: address(this),
            permissionId: DAO(payable(_dao)).EXECUTE_PERMISSION_ID(),
            condition: PermissionLib.NO_CONDITION
        });
        Action[] memory actions = new Action[](6);
        actions[0].to = _dao;
        actions[0].data = abi.encodeCall(PermissionManager.applyMultiTargetPermissions, permissions);
        // make vault and strategies whitelisted for nft transfers
        actions[1].to = _nftLock;
        actions[1].data = abi.encodeCall(LockNFT.setWhitelisted, (_deps.vault, true));
        actions[2].to = _nftLock;
        actions[2].data = abi.encodeCall(LockNFT.setWhitelisted, (_deps.defaultStrategy, true));
        actions[3].to = _nftLock;
        actions[3].data = abi.encodeCall(LockNFT.setWhitelisted, (_deps.autoCompoundStrategy, true));
        actions[4].to = _escrow;
        actions[4].data = abi.encodeCall(VotingEscrow.setEnableSplit, (_deps.defaultStrategy, true));
        actions[5].to = _escrow;
        actions[5].data = abi.encodeCall(VotingEscrow.setEnableSplit, (_deps.autoCompoundStrategy, true));
        return actions;
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title PermissionLib /// @author Aragon X - 2021-2023 /// @notice A library containing objects for permission processing. /// @custom:security-contact [email protected] library PermissionLib { /// @notice A constant expressing that no condition is applied to a permission. address public constant NO_CONDITION = address(0); /// @notice The types of permission operations available in the `PermissionManager`. /// @param Grant The grant operation setting a permission without a condition. /// @param Revoke The revoke operation removing a permission (that was granted with or without a condition). /// @param GrantWithCondition The grant operation setting a permission with a condition. enum Operation { Grant, Revoke, GrantWithCondition } /// @notice A struct containing the information for a permission to be applied on a single target contract without a condition. /// @param operation The permission operation type. /// @param who The address (EOA or contract) receiving the permission. /// @param permissionId The permission identifier. struct SingleTargetPermission { Operation operation; address who; bytes32 permissionId; } /// @notice A struct containing the information for a permission to be applied on multiple target contracts, optionally, with a condition. /// @param operation The permission operation type. /// @param where The address of the target contract for which `who` receives permission. /// @param who The address (EOA or contract) receiving the permission. /// @param condition The `PermissionCondition` that will be asked for authorization on calls connected to the specified permission identifier. /// @param permissionId The permission identifier. struct MultiTargetPermission { Operation operation; address where; address who; address condition; bytes32 permissionId; } }
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {IPermissionCondition} from "@aragon/osx-commons-contracts/src/permission/condition/IPermissionCondition.sol";
import {PermissionCondition} from "@aragon/osx-commons-contracts/src/permission/condition/PermissionCondition.sol";
import {PermissionLib} from "@aragon/osx-commons-contracts/src/permission/PermissionLib.sol";
/// @title PermissionManager
/// @author Aragon X - 2021-2023
/// @notice The abstract permission manager used in a DAO, its associated plugins, and other framework-related components.
/// @custom:security-contact [email protected]
abstract contract PermissionManager is Initializable {
    using AddressUpgradeable for address;
    /// @notice The ID of the permission required to call the `grant`, `grantWithCondition`, `revoke`, and `bulk` function.
    bytes32 public constant ROOT_PERMISSION_ID = keccak256("ROOT_PERMISSION");
    /// @notice A special address encoding permissions that are valid for any address `who` or `where`.
    address internal constant ANY_ADDR = address(type(uint160).max);
    /// @notice A special address encoding if a permissions is not set and therefore not allowed.
    address internal constant UNSET_FLAG = address(0);
    /// @notice A special address encoding if a permission is allowed.
    address internal constant ALLOW_FLAG = address(2);
    /// @notice A mapping storing permissions as hashes (i.e., `permissionHash(where, who, permissionId)`) and their status encoded by an address (unset, allowed, or redirecting to a `PermissionCondition`).
    mapping(bytes32 => address) internal permissionsHashed;
    /// @notice Thrown if a call is unauthorized.
    /// @param where The context in which the authorization reverted.
    /// @param who The address (EOA or contract) missing the permission.
    /// @param permissionId The permission identifier.
    error Unauthorized(address where, address who, bytes32 permissionId);
    /// @notice Thrown if a permission has been already granted with a different condition.
    /// @dev This makes sure that condition on the same permission can not be overwriten by a different condition.
    /// @param where The address of the target contract to grant `_who` permission to.
    /// @param who The address (EOA or contract) to which the permission has already been granted.
    /// @param permissionId The permission identifier.
    /// @param currentCondition The current condition set for permissionId.
    /// @param newCondition The new condition it tries to set for permissionId.
    error PermissionAlreadyGrantedForDifferentCondition(
        address where,
        address who,
        bytes32 permissionId,
        address currentCondition,
        address newCondition
    );
    /// @notice Thrown if a condition address is not a contract.
    /// @param condition The address that is not a contract.
    error ConditionNotAContract(IPermissionCondition condition);
    /// @notice Thrown if a condition contract does not support the `IPermissionCondition` interface.
    /// @param condition The address that is not a contract.
    error ConditionInterfaceNotSupported(IPermissionCondition condition);
    /// @notice Thrown for `ROOT_PERMISSION_ID` or `EXECUTE_PERMISSION_ID` permission grants where `who` or `where` is `ANY_ADDR`.
    error PermissionsForAnyAddressDisallowed();
    /// @notice Thrown for permission grants where `who` and `where` are both `ANY_ADDR`.
    error AnyAddressDisallowedForWhoAndWhere();
    /// @notice Thrown if `Operation.GrantWithCondition` is requested as an operation but the method does not support it.
    error GrantWithConditionNotSupported();
    /// @notice Emitted when a permission `permission` is granted in the context `here` to the address `_who` for the contract `_where`.
    /// @param permissionId The permission identifier.
    /// @param here The address of the context in which the permission is granted.
    /// @param where The address of the target contract for which `_who` receives permission.
    /// @param who The address (EOA or contract) receiving the permission.
    /// @param condition The address `ALLOW_FLAG` for regular permissions or, alternatively, the `IPermissionCondition` contract implementation to be used.
    event Granted(
        bytes32 indexed permissionId,
        address indexed here,
        address where,
        address indexed who,
        address condition
    );
    /// @notice Emitted when a permission `permission` is revoked in the context `here` from the address `_who` for the contract `_where`.
    /// @param permissionId The permission identifier.
    /// @param here The address of the context in which the permission is revoked.
    /// @param where The address of the target contract for which `_who` loses permission.
    /// @param who The address (EOA or contract) losing the permission.
    event Revoked(
        bytes32 indexed permissionId,
        address indexed here,
        address where,
        address indexed who
    );
    /// @notice A modifier to make functions on inheriting contracts authorized. Permissions to call the function are checked through this permission manager.
    /// @param _permissionId The permission identifier required to call the method this modifier is applied to.
    modifier auth(bytes32 _permissionId) {
        _auth(_permissionId);
        _;
    }
    /// @notice Initialization method to set the initial owner of the permission manager.
    /// @dev The initial owner is granted the `ROOT_PERMISSION_ID` permission.
    /// @param _initialOwner The initial owner of the permission manager.
    function __PermissionManager_init(address _initialOwner) internal onlyInitializing {
        _initializePermissionManager({_initialOwner: _initialOwner});
    }
    /// @notice Grants permission to an address to call methods in a contract guarded by an auth modifier with the specified permission identifier.
    /// @dev Requires the `ROOT_PERMISSION_ID` permission.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) receiving the permission.
    /// @param _permissionId The permission identifier.
    /// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel.
    function grant(
        address _where,
        address _who,
        bytes32 _permissionId
    ) external virtual auth(ROOT_PERMISSION_ID) {
        _grant({_where: _where, _who: _who, _permissionId: _permissionId});
    }
    /// @notice Grants permission to an address to call methods in a target contract guarded by an auth modifier with the specified permission identifier if the referenced condition permits it.
    /// @dev Requires the `ROOT_PERMISSION_ID` permission
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) receiving the permission.
    /// @param _permissionId The permission identifier.
    /// @param _condition The `PermissionCondition` that will be asked for authorization on calls connected to the specified permission identifier.
    /// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel.
    function grantWithCondition(
        address _where,
        address _who,
        bytes32 _permissionId,
        IPermissionCondition _condition
    ) external virtual auth(ROOT_PERMISSION_ID) {
        _grantWithCondition({
            _where: _where,
            _who: _who,
            _permissionId: _permissionId,
            _condition: _condition
        });
    }
    /// @notice Revokes permission from an address to call methods in a target contract guarded by an auth modifier with the specified permission identifier.
    /// @dev Requires the `ROOT_PERMISSION_ID` permission.
    /// @param _where The address of the target contract for which `_who` loses permission.
    /// @param _who The address (EOA or contract) losing the permission.
    /// @param _permissionId The permission identifier.
    /// @dev Note, that revoking permissions with `_who` or `_where` equal to `ANY_ADDR` does not revoke other permissions with specific `_who` and `_where` addresses that exist in parallel.
    function revoke(
        address _where,
        address _who,
        bytes32 _permissionId
    ) external virtual auth(ROOT_PERMISSION_ID) {
        _revoke({_where: _where, _who: _who, _permissionId: _permissionId});
    }
    /// @notice Applies an array of permission operations on a single target contracts `_where`.
    /// @param _where The address of the single target contract.
    /// @param items The array of single-targeted permission operations to apply.
    function applySingleTargetPermissions(
        address _where,
        PermissionLib.SingleTargetPermission[] calldata items
    ) external virtual auth(ROOT_PERMISSION_ID) {
        for (uint256 i; i < items.length; ) {
            PermissionLib.SingleTargetPermission memory item = items[i];
            if (item.operation == PermissionLib.Operation.Grant) {
                _grant({_where: _where, _who: item.who, _permissionId: item.permissionId});
            } else if (item.operation == PermissionLib.Operation.Revoke) {
                _revoke({_where: _where, _who: item.who, _permissionId: item.permissionId});
            } else if (item.operation == PermissionLib.Operation.GrantWithCondition) {
                revert GrantWithConditionNotSupported();
            }
            unchecked {
                ++i;
            }
        }
    }
    /// @notice Applies an array of permission operations on multiple target contracts `items[i].where`.
    /// @param _items The array of multi-targeted permission operations to apply.
    function applyMultiTargetPermissions(
        PermissionLib.MultiTargetPermission[] calldata _items
    ) external virtual auth(ROOT_PERMISSION_ID) {
        for (uint256 i; i < _items.length; ) {
            PermissionLib.MultiTargetPermission memory item = _items[i];
            if (item.operation == PermissionLib.Operation.Grant) {
                // Ensure a non-zero condition isn't passed, as `_grant` can't handle conditions.
                // This avoids the false impression that a conditional grant occurred,
                // since the transaction would still succeed without conditions.
                if (item.condition != address(0)) {
                    revert GrantWithConditionNotSupported();
                }
                _grant({_where: item.where, _who: item.who, _permissionId: item.permissionId});
            } else if (item.operation == PermissionLib.Operation.Revoke) {
                _revoke({_where: item.where, _who: item.who, _permissionId: item.permissionId});
            } else if (item.operation == PermissionLib.Operation.GrantWithCondition) {
                _grantWithCondition({
                    _where: item.where,
                    _who: item.who,
                    _permissionId: item.permissionId,
                    _condition: IPermissionCondition(item.condition)
                });
            }
            unchecked {
                ++i;
            }
        }
    }
    /// @notice Checks if the caller address has permission on the target contract via a permission identifier and relays the answer to a condition contract if this was declared during the granting process.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) for which the permission is checked.
    /// @param _permissionId The permission identifier.
    /// @param _data Optional data to be passed to the set `PermissionCondition`.
    /// @return Returns true if `_who` has the permissions on the target contract via the specified permission identifier.
    function isGranted(
        address _where,
        address _who,
        bytes32 _permissionId,
        bytes memory _data
    ) public view virtual returns (bool) {
        // Specific caller (`_who`) and target (`_where`) permission check
        {
            // This permission may have been granted directly via the `grant` function or with a condition via the `grantWithCondition` function.
            address specificCallerTargetPermission = permissionsHashed[
                permissionHash({_where: _where, _who: _who, _permissionId: _permissionId})
            ];
            // If the permission was granted directly, return `true`.
            if (specificCallerTargetPermission == ALLOW_FLAG) return true;
            // If the permission was granted with a condition, check the condition and return the result.
            if (specificCallerTargetPermission != UNSET_FLAG) {
                return
                    _checkCondition({
                        _condition: specificCallerTargetPermission,
                        _where: _where,
                        _who: _who,
                        _permissionId: _permissionId,
                        _data: _data
                    });
            }
            // If this permission is not set, continue.
        }
        // Generic caller (`_who: ANY_ADDR`)
        {
            address genericCallerPermission = permissionsHashed[
                permissionHash({_where: _where, _who: ANY_ADDR, _permissionId: _permissionId})
            ];
            // If the permission was granted directly to (`_who: ANY_ADDR`), return `true`.
            if (genericCallerPermission == ALLOW_FLAG) return true;
            // If the permission was granted with a condition, check the condition and return the result.
            if (genericCallerPermission != UNSET_FLAG) {
                return
                    _checkCondition({
                        _condition: genericCallerPermission,
                        _where: _where,
                        _who: _who,
                        _permissionId: _permissionId,
                        _data: _data
                    });
            }
            // If this permission is not set, continue.
        }
        // Generic target (`_where: ANY_ADDR`) condition check
        {
            // This permission can only be granted in conjunction with a condition via the `grantWithCondition` function.
            address genericTargetPermission = permissionsHashed[
                permissionHash({_where: ANY_ADDR, _who: _who, _permissionId: _permissionId})
            ];
            // If the permission was granted with a condition, check the condition and return the result.
            if (genericTargetPermission != UNSET_FLAG) {
                return
                    _checkCondition({
                        _condition: genericTargetPermission,
                        _where: _where,
                        _who: _who,
                        _permissionId: _permissionId,
                        _data: _data
                    });
            }
            // If this permission is not set, continue.
        }
        // No specific or generic permission applies to the `_who`, `_where`, `_permissionId`, so we return `false`.
        return false;
    }
    /// @notice Relays the question if caller address has permission on target contract via a permission identifier to a condition contract.
    /// @notice Checks a condition contract by doing an external call via try/catch.
    /// @param _condition The condition contract that is called.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) owning the permission.
    /// @param _permissionId The permission identifier.
    /// @param _data Optional data to be passed to a referenced `PermissionCondition`.
    /// @return Returns `true` if a caller (`_who`) has the permissions on the contract (`_where`) via the specified permission identifier.
    /// @dev If the external call fails, we return `false`.
    function _checkCondition(
        address _condition,
        address _where,
        address _who,
        bytes32 _permissionId,
        bytes memory _data
    ) internal view virtual returns (bool) {
        // Try-catch to skip failures
        try
            IPermissionCondition(_condition).isGranted({
                _where: _where,
                _who: _who,
                _permissionId: _permissionId,
                _data: _data
            })
        returns (bool result) {
            if (result) {
                return true;
            }
        } catch {}
        return false;
    }
    /// @notice Grants the `ROOT_PERMISSION_ID` permission to the initial owner during initialization of the permission manager.
    /// @param _initialOwner The initial owner of the permission manager.
    function _initializePermissionManager(address _initialOwner) internal {
        _grant({_where: address(this), _who: _initialOwner, _permissionId: ROOT_PERMISSION_ID});
    }
    /// @notice This method is used in the external `grant` method of the permission manager.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) owning the permission.
    /// @param _permissionId The permission identifier.
    /// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel.
    function _grant(address _where, address _who, bytes32 _permissionId) internal virtual {
        if (_where == ANY_ADDR) {
            revert PermissionsForAnyAddressDisallowed();
        }
        if (_who == ANY_ADDR) {
            if (
                _permissionId == ROOT_PERMISSION_ID ||
                isPermissionRestrictedForAnyAddr(_permissionId)
            ) {
                revert PermissionsForAnyAddressDisallowed();
            }
        }
        bytes32 permHash = permissionHash({
            _where: _where,
            _who: _who,
            _permissionId: _permissionId
        });
        address currentFlag = permissionsHashed[permHash];
        // Means permHash is not currently set.
        if (currentFlag == UNSET_FLAG) {
            permissionsHashed[permHash] = ALLOW_FLAG;
            emit Granted({
                permissionId: _permissionId,
                here: msg.sender,
                where: _where,
                who: _who,
                condition: ALLOW_FLAG
            });
        }
    }
    /// @notice This method is used in the external `grantWithCondition` method of the permission manager.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) owning the permission.
    /// @param _permissionId The permission identifier.
    /// @param _condition An address either resolving to a `PermissionCondition` contract address or being the `ALLOW_FLAG` address (`address(2)`).
    /// @dev Note, that granting permissions with `_who` or `_where` equal to `ANY_ADDR` does not replace other permissions with specific `_who` and `_where` addresses that exist in parallel.
    function _grantWithCondition(
        address _where,
        address _who,
        bytes32 _permissionId,
        IPermissionCondition _condition
    ) internal virtual {
        address conditionAddr = address(_condition);
        if (!conditionAddr.isContract()) {
            revert ConditionNotAContract(_condition);
        }
        if (
            !PermissionCondition(conditionAddr).supportsInterface(
                type(IPermissionCondition).interfaceId
            )
        ) {
            revert ConditionInterfaceNotSupported(_condition);
        }
        if (_where == ANY_ADDR && _who == ANY_ADDR) {
            revert AnyAddressDisallowedForWhoAndWhere();
        }
        if (_where == ANY_ADDR || _who == ANY_ADDR) {
            if (
                _permissionId == ROOT_PERMISSION_ID ||
                isPermissionRestrictedForAnyAddr(_permissionId)
            ) {
                revert PermissionsForAnyAddressDisallowed();
            }
        }
        bytes32 permHash = permissionHash({
            _where: _where,
            _who: _who,
            _permissionId: _permissionId
        });
        address currentCondition = permissionsHashed[permHash];
        // Means permHash is not currently set.
        if (currentCondition == UNSET_FLAG) {
            permissionsHashed[permHash] = conditionAddr;
            emit Granted({
                permissionId: _permissionId,
                here: msg.sender,
                where: _where,
                who: _who,
                condition: conditionAddr
            });
        } else if (currentCondition != conditionAddr) {
            // Revert if `permHash` is already granted, but uses a different condition.
            // If we don't revert, we either should:
            //   - allow overriding the condition on the same permission
            //     which could be confusing whoever granted the same permission first
            //   - or do nothing and succeed silently which could be confusing for the caller.
            revert PermissionAlreadyGrantedForDifferentCondition({
                where: _where,
                who: _who,
                permissionId: _permissionId,
                currentCondition: currentCondition,
                newCondition: conditionAddr
            });
        }
    }
    /// @notice This method is used in the public `revoke` method of the permission manager.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) owning the permission.
    /// @param _permissionId The permission identifier.
    /// @dev Note, that revoking permissions with `_who` or `_where` equal to `ANY_ADDR` does not revoke other permissions with specific `_who` and `_where` addresses that might have been granted in parallel.
    function _revoke(address _where, address _who, bytes32 _permissionId) internal virtual {
        bytes32 permHash = permissionHash({
            _where: _where,
            _who: _who,
            _permissionId: _permissionId
        });
        if (permissionsHashed[permHash] != UNSET_FLAG) {
            permissionsHashed[permHash] = UNSET_FLAG;
            emit Revoked({permissionId: _permissionId, here: msg.sender, where: _where, who: _who});
        }
    }
    /// @notice A private function to be used to check permissions on the permission manager contract (`address(this)`) itself.
    /// @param _permissionId The permission identifier required to call the method this modifier is applied to.
    function _auth(bytes32 _permissionId) internal view virtual {
        if (!isGranted(address(this), msg.sender, _permissionId, msg.data)) {
            revert Unauthorized({
                where: address(this),
                who: msg.sender,
                permissionId: _permissionId
            });
        }
    }
    /// @notice Generates the hash for the `permissionsHashed` mapping obtained from the word "PERMISSION", the contract address, the address owning the permission, and the permission identifier.
    /// @param _where The address of the target contract for which `_who` receives permission.
    /// @param _who The address (EOA or contract) owning the permission.
    /// @param _permissionId The permission identifier.
    /// @return The permission hash.
    function permissionHash(
        address _where,
        address _who,
        bytes32 _permissionId
    ) internal pure virtual returns (bytes32) {
        return keccak256(abi.encodePacked("PERMISSION", _who, _where, _permissionId));
    }
    /// @notice Decides if the granting permissionId is restricted when `_who == ANY_ADDR` or `_where == ANY_ADDR`.
    /// @param _permissionId The permission identifier.
    /// @return Whether or not the permission is restricted.
    /// @dev By default, every permission is unrestricted and it is the derived contract's responsibility to override it. Note, that the `ROOT_PERMISSION_ID` is included and not required to be set it again.
    function isPermissionRestrictedForAnyAddr(
        bytes32 _permissionId
    ) internal view virtual returns (bool) {
        (_permissionId); // silence the warning.
        return false;
    }
    /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)).
    uint256[49] private __gap;
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IPluginSetup} from "@aragon/osx-commons-contracts/src/plugin/setup/IPluginSetup.sol";
import {
    IProposal
} from "@aragon/osx-commons-contracts/src/plugin/extensions/proposal/IProposal.sol";
import {ProxyLib} from "@libs/ProxyLib.sol";
import {PermissionLib} from "@aragon/osx-commons-contracts/src/permission/PermissionLib.sol";
import {PluginSetup} from "@aragon/osx-commons-contracts/src/plugin/setup/PluginSetup.sol";
import {AddressGaugeVoter as GaugeVoter} from "@voting/AddressGaugeVoter.sol";
import {VotingEscrowV1_2_0 as VotingEscrow} from "@escrow/VotingEscrowIncreasing_v1_2_0.sol";
import {DynamicExitQueue as ExitQueue} from "@queue/DynamicExitQueue.sol";
import {LinearIncreasingCurve as Curve} from "@curve/LinearIncreasingCurve.sol";
import {ClockV1_2_0 as Clock} from "@clock/Clock_v1_2_0.sol";
import {LockV1_2_0 as Lock} from "@lock/Lock_v1_2_0.sol";
import {EscrowIVotesAdapter} from "@delegation/EscrowIVotesAdapter.sol";
/// @param isPaused Whether the voter contract is deployed in a paused state
/// @param veTokenName The name of the voting escrow token
/// @param veTokenSymbol The symbol of the voting escrow token
/// @param token The underlying token for the escrow
/// @param cooldown The cooldown period for the exit queue
struct IGaugeVoterSetupParams {
    // voter
    bool isPaused;
    // escrow - NFT
    string veTokenName;
    string veTokenSymbol;
    // escrow - main
    address token;
    uint256 minDeposit;
    // queue
    uint256 feePercent;
    uint48 cooldown;
    uint48 minLock;
}
contract GaugeVoterSetupV1_4_0 is PluginSetup {
    using Address for address;
    using Clones for address;
    using ERC165Checker for address;
    using ProxyLib for address;
    /// @notice The identifier of the `EXECUTE_PERMISSION` permission.
    bytes32 public constant EXECUTE_PERMISSION_ID = keccak256("EXECUTE_PERMISSION");
    /// @notice Thrown if passed helpers array is of wrong length.
    /// @param length The array length of passed helpers.
    error WrongHelpersArrayLength(uint256 length);
    /// @dev implementation of the gaugevoting plugin
    address voterBase;
    /// @dev implementation of the escrow voting curve
    address curveBase;
    /// @dev implementation of the exit queue
    address queueBase;
    /// @dev implementation of the escrow locker
    address escrowBase;
    /// @dev implementation of the clock
    address clockBase;
    /// @dev implementation of the escrow NFT
    address nftBase;
    /// @dev implementation of the delegation adapter
    address ivotesAdapterBase;
    struct Deployment {
        address curve;
        address exitQueue;
        address escrow;
        address clock;
        address nftLock;
        address ivotesAdapter;
        address plugin;
    }
    /// @notice Deploys the setup by binding the implementation contracts required during installation.
    constructor(
        address _voterBase,
        address _curveBase,
        address _queueBase,
        address _escrowBase,
        address _clockBase,
        address _nftBase,
        address _ivotesAdapterBase
    ) PluginSetup(_voterBase) {
        voterBase = _voterBase;
        curveBase = _curveBase;
        queueBase = _queueBase;
        escrowBase = _escrowBase;
        clockBase = _clockBase;
        nftBase = _nftBase;
        ivotesAdapterBase = _ivotesAdapterBase;
    }
    /// @inheritdoc IPluginSetup
    /// @dev You need to set the helpers on the plugin as a post install action.
    function prepareInstallation(
        address _dao,
        bytes calldata _data
    ) external returns (address plugin, PreparedSetupData memory preparedSetupData) {
        IGaugeVoterSetupParams memory params = abi.decode(_data, (IGaugeVoterSetupParams));
        Deployment memory deps;
        // deploy the clock
        deps.clock = address(
            clockBase.deployUUPSProxy(abi.encodeWithSelector(Clock.initialize.selector, _dao))
        );
        // deploy the escrow locker
        deps.escrow = escrowBase.deployUUPSProxy(
            abi.encodeCall(
                VotingEscrow.initialize,
                (params.token, _dao, deps.clock, params.minDeposit)
            )
        );
        deps.ivotesAdapter = ivotesAdapterBase.deployUUPSProxy(
            abi.encodeCall(EscrowIVotesAdapter.initialize, (_dao, deps.escrow, deps.clock, false))
        );
        // deploy the voting contract (plugin)
        deps.plugin = voterBase.deployUUPSProxy(
            abi.encodeCall(
                GaugeVoter.initialize,
                (_dao, deps.escrow, params.isPaused, deps.clock, deps.ivotesAdapter, true)
            )
        );
        // deploy the curve
        deps.curve = curveBase.deployUUPSProxy(
            abi.encodeCall(Curve.initialize, (deps.escrow, _dao, deps.clock))
        );
        // deploy the exit queue
        deps.exitQueue = queueBase.deployUUPSProxy(
            abi.encodeCall(
                ExitQueue.initialize,
                (deps.escrow, params.cooldown, _dao, params.feePercent, deps.clock, params.minLock)
            )
        );
        // deploy the escrow NFT
        deps.nftLock = nftBase.deployUUPSProxy(
            abi.encodeCall(
                Lock.initialize,
                (deps.escrow, params.veTokenName, params.veTokenSymbol, _dao)
            )
        );
        // encode our setup data with permissions and helpers
        PermissionLib.MultiTargetPermission[] memory permissions = getPermissions(
            _dao,
            deps.plugin,
            deps.curve,
            deps.exitQueue,
            deps.escrow,
            deps.clock,
            deps.nftLock,
            deps.ivotesAdapter,
            PermissionLib.Operation.Grant
        );
        address[] memory helpers = new address[](6);
        helpers[0] = deps.curve;
        helpers[1] = deps.exitQueue;
        helpers[2] = deps.escrow;
        helpers[3] = deps.clock;
        helpers[4] = deps.nftLock;
        helpers[5] = deps.ivotesAdapter;
        // return arguments
        preparedSetupData.helpers = helpers;
        preparedSetupData.permissions = permissions;
        plugin = deps.plugin;
    }
    /// @inheritdoc IPluginSetup
    function prepareUninstallation(
        address _dao,
        SetupPayload calldata _payload
    ) external view returns (PermissionLib.MultiTargetPermission[] memory permissions) {
        // check the helpers length
        if (_payload.currentHelpers.length != 6) {
            revert WrongHelpersArrayLength(_payload.currentHelpers.length);
        }
        address curve = _payload.currentHelpers[0];
        address queue = _payload.currentHelpers[1];
        address escrow = _payload.currentHelpers[2];
        address clock = _payload.currentHelpers[3];
        address nftLock = _payload.currentHelpers[4];
        address ivotesAdapter = _payload.currentHelpers[5];
        permissions = getPermissions(
            _dao,
            _payload.plugin,
            curve,
            queue,
            escrow,
            clock,
            nftLock,
            ivotesAdapter,
            PermissionLib.Operation.Revoke
        );
    }
    /// @notice Returns the permissions required for the plugin install and uninstall.
    /// @param _dao The DAO address on this chain.
    /// @param _plugin The plugin address.
    /// @param _grantOrRevoke The operation to perform
    function getPermissions(
        address _dao,
        address _plugin,
        address _curve,
        address _queue,
        address _escrow,
        address _clock,
        address _nft,
        address _ivotesAdapter,
        PermissionLib.Operation _grantOrRevoke
    ) public view returns (PermissionLib.MultiTargetPermission[] memory) {
        PermissionLib.MultiTargetPermission[]
            memory permissions = new PermissionLib.MultiTargetPermission[](12);
        permissions[0] = PermissionLib.MultiTargetPermission({
            permissionId: GaugeVoter(_plugin).GAUGE_ADMIN_ROLE(),
            where: _plugin,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[1] = PermissionLib.MultiTargetPermission({
            permissionId: VotingEscrow(_escrow).ESCROW_ADMIN_ROLE(),
            where: _escrow,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[2] = PermissionLib.MultiTargetPermission({
            permissionId: ExitQueue(_queue).QUEUE_ADMIN_ROLE(),
            where: _queue,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[3] = PermissionLib.MultiTargetPermission({
            permissionId: Curve(_curve).CURVE_ADMIN_ROLE(),
            where: _curve,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[4] = PermissionLib.MultiTargetPermission({
            permissionId: GaugeVoter(_plugin).UPGRADE_PLUGIN_PERMISSION_ID(),
            where: _plugin,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[5] = PermissionLib.MultiTargetPermission({
            permissionId: Clock(_clock).CLOCK_ADMIN_ROLE(),
            where: _clock,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[6] = PermissionLib.MultiTargetPermission({
            permissionId: Lock(_nft).LOCK_ADMIN_ROLE(),
            where: _nft,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[7] = PermissionLib.MultiTargetPermission({
            permissionId: EscrowIVotesAdapter(_ivotesAdapter).DELEGATION_ADMIN_ROLE(),
            where: _ivotesAdapter,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[8] = PermissionLib.MultiTargetPermission({
            permissionId: EscrowIVotesAdapter(_ivotesAdapter).DELEGATION_TOKEN_ROLE(),
            where: _ivotesAdapter,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[9] = PermissionLib.MultiTargetPermission({
            permissionId: VotingEscrow(_escrow).PAUSER_ROLE(),
            where: _escrow,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[10] = PermissionLib.MultiTargetPermission({
            permissionId: VotingEscrow(_escrow).SWEEPER_ROLE(),
            where: _escrow,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        permissions[11] = PermissionLib.MultiTargetPermission({
            permissionId: ExitQueue(_queue).WITHDRAW_ROLE(),
            where: _queue,
            who: _dao,
            operation: _grantOrRevoke,
            condition: PermissionLib.NO_CONDITION
        });
        return permissions;
    }
    function encodeSetupData(
        IGaugeVoterSetupParams calldata _params
    ) external pure returns (bytes memory) {
        return abi.encode(_params);
    }
    /// @notice  utility for external applications create the encoded setup data.
    function encodeSetupData(
        bool isPaused,
        string calldata veTokenName,
        string calldata veTokenSymbol,
        address token,
        uint48 cooldown,
        uint256 feePercent,
        uint48 minLock,
        uint256 minDeposit
    ) external pure returns (bytes memory) {
        return
            abi.encode(
                IGaugeVoterSetupParams({
                    isPaused: isPaused,
                    token: token,
                    veTokenName: veTokenName,
                    veTokenSymbol: veTokenSymbol,
                    cooldown: cooldown,
                    feePercent: feePercent,
                    minLock: minLock,
                    minDeposit: minDeposit
                })
            );
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
/// @notice The action struct to be consumed by the DAO's `execute` function resulting in an external call.
/// @param to The address to call.
/// @param value The native token value to be sent with the call.
/// @param data The bytes-encoded function selector and calldata for the call.
struct Action {
    address to;
    uint256 value;
    bytes data;
}
/// @title IExecutor
/// @author Aragon X - 2024
/// @notice The interface required for Executors within the Aragon App DAO framework.
/// @custom:security-contact [email protected]
interface IExecutor {
    /// @notice Emitted when a proposal is executed.
    /// @dev The value of `callId` is defined by the component/contract calling the execute function.
    ///      A `Plugin` implementation can use it, for example, as a nonce.
    /// @param actor The address of the caller.
    /// @param callId The ID of the call.
    /// @param actions The array of actions executed.
    /// @param allowFailureMap The allow failure map encoding which actions are allowed to fail.
    /// @param failureMap The failure map encoding which actions have failed.
    /// @param execResults The array with the results of the executed actions.
    event Executed(
        address indexed actor,
        bytes32 callId,
        Action[] actions,
        uint256 allowFailureMap,
        uint256 failureMap,
        bytes[] execResults
    );
    /// @notice Executes a list of actions. If a zero allow-failure map is provided, a failing action reverts the entire execution. If a non-zero allow-failure map is provided, allowed actions can fail without the entire call being reverted.
    /// @param _callId The ID of the call. The definition of the value of `callId` is up to the calling contract and can be used, e.g., as a nonce.
    /// @param _actions The array of actions.
    /// @param _allowFailureMap A bitmap allowing execution to succeed, even if individual actions might revert. If the bit at index `i` is 1, the execution succeeds even if the `i`th action reverts. A failure map value of 0 requires every action to not revert.
    /// @return The array of results obtained from the executed actions in `bytes`.
    /// @return The resulting failure map containing the actions have actually failed.
    function execute(
        bytes32 _callId,
        Action[] memory _actions,
        uint256 _allowFailureMap
    ) external returns (bytes[] memory, uint256);
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ERC165StorageUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC721ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import {IERC1155Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import {IERC1155ReceiverUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {IProtocolVersion} from "@aragon/osx-commons-contracts/src/utils/versioning/IProtocolVersion.sol";
import {ProtocolVersion} from "@aragon/osx-commons-contracts/src/utils/versioning/ProtocolVersion.sol";
import {VersionComparisonLib} from "@aragon/osx-commons-contracts/src/utils/versioning/VersionComparisonLib.sol";
import {hasBit, flipBit} from "@aragon/osx-commons-contracts/src/utils/math/BitMap.sol";
import {Action} from "@aragon/osx-commons-contracts/src/executors/Executor.sol";
import {IExecutor} from "@aragon/osx-commons-contracts/src/executors/IExecutor.sol";
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {PermissionManager} from "../permission/PermissionManager.sol";
import {CallbackHandler} from "../utils/CallbackHandler.sol";
import {IEIP4824} from "./IEIP4824.sol";
/// @title DAO
/// @author Aragon X - 2021-2024
/// @notice This contract is the entry point to the Aragon DAO framework and provides our users a simple and easy to use public interface.
/// @dev Public API of the Aragon DAO framework.
/// @custom:security-contact [email protected]
contract DAO is
    IEIP4824,
    Initializable,
    IERC1271,
    ERC165StorageUpgradeable,
    IDAO,
    IExecutor,
    UUPSUpgradeable,
    ProtocolVersion,
    PermissionManager,
    CallbackHandler
{
    using SafeERC20Upgradeable for IERC20Upgradeable;
    using AddressUpgradeable for address;
    using VersionComparisonLib for uint8[3];
    /// @notice The ID of the permission required to call the `execute` function.
    bytes32 public constant EXECUTE_PERMISSION_ID = keccak256("EXECUTE_PERMISSION");
    /// @notice The ID of the permission required to call the `_authorizeUpgrade` function.
    bytes32 public constant UPGRADE_DAO_PERMISSION_ID = keccak256("UPGRADE_DAO_PERMISSION");
    /// @notice The ID of the permission required to call the `setMetadata` function.
    bytes32 public constant SET_METADATA_PERMISSION_ID = keccak256("SET_METADATA_PERMISSION");
    /// @notice The ID of the permission required to call the `setTrustedForwarder` function.
    bytes32 public constant SET_TRUSTED_FORWARDER_PERMISSION_ID =
        keccak256("SET_TRUSTED_FORWARDER_PERMISSION");
    /// @notice The ID of the permission required to call the `registerStandardCallback` function.
    bytes32 public constant REGISTER_STANDARD_CALLBACK_PERMISSION_ID =
        keccak256("REGISTER_STANDARD_CALLBACK_PERMISSION");
    /// @notice The ID of the permission required to validate [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271) signatures.
    bytes32 public constant VALIDATE_SIGNATURE_PERMISSION_ID =
        keccak256("VALIDATE_SIGNATURE_PERMISSION");
    /// @notice The internal constant storing the maximal action array length.
    uint256 internal constant MAX_ACTIONS = 256;
    /// @notice The first out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set indicating that a function was not entered.
    uint256 private constant _NOT_ENTERED = 1;
    /// @notice The second out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set indicating that a function was entered.
    uint256 private constant _ENTERED = 2;
    /// @notice Removed variable that is left here to maintain the storage layout.
    /// @dev Introduced in v1.0.0. Removed in v1.4.0.
    /// @custom:oz-renamed-from signatureValidator
    address private __removed0;
    /// @notice The address of the trusted forwarder verifying meta transactions.
    /// @dev Added in v1.0.0.
    address private trustedForwarder;
    /// @notice The [EIP-4824](https://eips.ethereum.org/EIPS/eip-4824) DAO URI.
    /// @dev Added in v1.0.0.
    string private _daoURI;
    /// @notice The state variable for the reentrancy guard of the `execute` function.
    /// @dev Added in v1.3.0. The variable can be of value `_NOT_ENTERED = 1` or `_ENTERED = 2` in usage and is initialized with `_NOT_ENTERED`.
    uint256 private _reentrancyStatus;
    /// @notice Thrown if a call is reentrant.
    error ReentrantCall();
    /// @notice Thrown if the action array length is larger than `MAX_ACTIONS`.
    error TooManyActions();
    /// @notice Thrown if action execution has failed.
    /// @param index The index of the action in the action array that failed.
    error ActionFailed(uint256 index);
    /// @notice Thrown if an action has insufficient gas left.
    error InsufficientGas();
    /// @notice Thrown if the deposit amount is zero.
    error ZeroAmount();
    /// @notice Thrown if there is a mismatch between the expected and actually deposited amount of native tokens.
    /// @param expected The expected native token amount.
    /// @param actual The actual native token amount deposited.
    error NativeTokenDepositAmountMismatch(uint256 expected, uint256 actual);
    /// @notice Thrown if an upgrade is not supported from a specific protocol version .
    error ProtocolVersionUpgradeNotSupported(uint8[3] protocolVersion);
    /// @notice Thrown when a function is removed but left to not corrupt the interface ID.
    error FunctionRemoved();
    /// @notice Thrown when initialize is called after it has already been executed.
    error AlreadyInitialized();
    /// @notice Emitted when a new DAO URI is set.
    /// @param daoURI The new URI.
    event NewURI(string daoURI);
    /// @notice A modifier to protect a function from calling itself, directly or indirectly (reentrancy).
    /// @dev Currently, this modifier is only applied to the `execute()` function. If this is used multiple times, private `_beforeNonReentrant()` and `_afterNonReentrant()` functions should be created to prevent code duplication.
    modifier nonReentrant() {
        if (_reentrancyStatus == _ENTERED) {
            revert ReentrantCall();
        }
        _reentrancyStatus = _ENTERED;
        _;
        _reentrancyStatus = _NOT_ENTERED;
    }
    /// @notice This ensures that the initialize function cannot be called during the upgrade process.
    modifier onlyCallAtInitialization() {
        if (_getInitializedVersion() != 0) {
            revert AlreadyInitialized();
        }
        _;
    }
    /// @notice Disables the initializers on the implementation contract to prevent it from being left uninitialized.
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }
    /// @notice Initializes the DAO by
    /// - setting the reentrancy status variable to `_NOT_ENTERED`
    /// - registering the [ERC-165](https://eips.ethereum.org/EIPS/eip-165) interface ID
    /// - setting the trusted forwarder for meta transactions
    /// - giving the `ROOT_PERMISSION_ID` permission to the initial owner (that should be revoked and transferred to the DAO after setup).
    /// @dev This method is required to support [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822).
    /// @param _metadata IPFS hash that points to all the metadata (logo, description, tags, etc.) of a DAO.
    /// @param _initialOwner The initial owner of the DAO having the `ROOT_PERMISSION_ID` permission.
    /// @param _trustedForwarder The trusted forwarder responsible for verifying meta transactions.
    /// @param daoURI_ The DAO URI required to support [ERC-4824](https://eips.ethereum.org/EIPS/eip-4824).
    function initialize(
        bytes calldata _metadata,
        address _initialOwner,
        address _trustedForwarder,
        string calldata daoURI_
    ) external onlyCallAtInitialization reinitializer(3) {
        _reentrancyStatus = _NOT_ENTERED; // added in v1.3.0
        // In addition to the current interfaceId, also support previous version of the interfaceId.
        _registerInterface(type(IDAO).interfaceId ^ IExecutor.execute.selector);
        _registerInterface(type(IDAO).interfaceId);
        _registerInterface(type(IExecutor).interfaceId);
        _registerInterface(type(IERC1271).interfaceId);
        _registerInterface(type(IEIP4824).interfaceId);
        _registerInterface(type(IProtocolVersion).interfaceId); // added in v1.3.0
        _registerTokenInterfaces();
        _setMetadata(_metadata);
        _setTrustedForwarder(_trustedForwarder);
        _setDaoURI(daoURI_);
        __PermissionManager_init(_initialOwner);
    }
    /// @notice Initializes the DAO after an upgrade from a previous protocol version.
    /// @param _previousProtocolVersion The semantic protocol version number of the previous DAO implementation contract this upgrade is transitioning from.
    /// @param _initData The initialization data to be passed to via `upgradeToAndCall` (see [ERC-1967](https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Upgrade)).
    function initializeFrom(
        uint8[3] calldata _previousProtocolVersion,
        bytes calldata _initData
    ) external reinitializer(3) {
        _initData; // Silences the unused function parameter warning.
        // Check that the contract is not upgrading from a different major release.
        if (_previousProtocolVersion[0] != 1) {
            revert ProtocolVersionUpgradeNotSupported(_previousProtocolVersion);
        }
        // Initialize `_reentrancyStatus` that was added in v1.3.0.
        // Register Interface `ProtocolVersion` that was added in v1.3.0.
        if (_previousProtocolVersion.lt([1, 3, 0])) {
            _reentrancyStatus = _NOT_ENTERED;
            _registerInterface(type(IProtocolVersion).interfaceId);
        }
        // Revoke the `SET_SIGNATURE_VALIDATOR_PERMISSION` that was deprecated in v1.4.0.
        if (_previousProtocolVersion.lt([1, 4, 0])) {
            _revoke({
                _where: address(this),
                _who: address(this),
                _permissionId: keccak256("SET_SIGNATURE_VALIDATOR_PERMISSION")
            });
            _registerInterface(type(IDAO).interfaceId);
            _registerInterface(type(IExecutor).interfaceId);
        }
    }
    /// @inheritdoc PermissionManager
    function isPermissionRestrictedForAnyAddr(
        bytes32 _permissionId
    ) internal pure override returns (bool) {
        return
            _permissionId == EXECUTE_PERMISSION_ID ||
            _permissionId == UPGRADE_DAO_PERMISSION_ID ||
            _permissionId == SET_METADATA_PERMISSION_ID ||
            _permissionId == SET_TRUSTED_FORWARDER_PERMISSION_ID ||
            _permissionId == REGISTER_STANDARD_CALLBACK_PERMISSION_ID;
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    /// @dev The caller must have the `UPGRADE_DAO_PERMISSION_ID` permission.
    function _authorizeUpgrade(address) internal virtual override auth(UPGRADE_DAO_PERMISSION_ID) {}
    /// @inheritdoc IDAO
    function setTrustedForwarder(
        address _newTrustedForwarder
    ) external override auth(SET_TRUSTED_FORWARDER_PERMISSION_ID) {
        _setTrustedForwarder(_newTrustedForwarder);
    }
    /// @inheritdoc IDAO
    function getTrustedForwarder() external view virtual override returns (address) {
        return trustedForwarder;
    }
    /// @inheritdoc IDAO
    function hasPermission(
        address _where,
        address _who,
        bytes32 _permissionId,
        bytes memory _data
    ) external view override returns (bool) {
        return isGranted({_where: _where, _who: _who, _permissionId: _permissionId, _data: _data});
    }
    /// @inheritdoc IDAO
    function setMetadata(
        bytes calldata _metadata
    ) external override auth(SET_METADATA_PERMISSION_ID) {
        _setMetadata(_metadata);
    }
    /// @inheritdoc IExecutor
    function execute(
        bytes32 _callId,
        Action[] calldata _actions,
        uint256 _allowFailureMap
    )
        external
        override
        nonReentrant
        auth(EXECUTE_PERMISSION_ID)
        returns (bytes[] memory execResults, uint256 failureMap)
    {
        // Check that the action array length is within bounds.
        if (_actions.length > MAX_ACTIONS) {
            revert TooManyActions();
        }
        execResults = new bytes[](_actions.length);
        uint256 gasBefore;
        uint256 gasAfter;
        for (uint256 i = 0; i < _actions.length; ) {
            gasBefore = gasleft();
            (bool success, bytes memory result) = _actions[i].to.call{value: _actions[i].value}(
                _actions[i].data
            );
            gasAfter = gasleft();
            // Check if failure is allowed
            if (!hasBit(_allowFailureMap, uint8(i))) {
                // Check if the call failed.
                if (!success) {
                    revert ActionFailed(i);
                }
            } else {
                // Check if the call failed.
                if (!success) {
                    // Make sure that the action call did not fail because 63/64 of `gasleft()` was insufficient to execute the external call `.to.call` (see [ERC-150](https://eips.ethereum.org/EIPS/eip-150)).
                    // In specific scenarios, i.e. proposal execution where the last action in the action array is allowed to fail, the account calling `execute` could force-fail this action by setting a gas limit
                    // where 63/64 is insufficient causing the `.to.call` to fail, but where the remaining 1/64 gas are sufficient to successfully finish the `execute` call.
                    if (gasAfter < gasBefore / 64) {
                        revert InsufficientGas();
                    }
                    // Store that this action failed.
                    failureMap = flipBit(failureMap, uint8(i));
                }
            }
            execResults[i] = result;
            unchecked {
                ++i;
            }
        }
        emit Executed({
            actor: msg.sender,
            callId: _callId,
            actions: _actions,
            allowFailureMap: _allowFailureMap,
            failureMap: failureMap,
            execResults: execResults
        });
    }
    /// @inheritdoc IDAO
    function deposit(
        address _token,
        uint256 _amount,
        string calldata _reference
    ) external payable override {
        if (_amount == 0) revert ZeroAmount();
        if (_token == address(0)) {
            if (msg.value != _amount)
                revert NativeTokenDepositAmountMismatch({expected: _amount, actual: msg.value});
        } else {
            if (msg.value != 0)
                revert NativeTokenDepositAmountMismatch({expected: 0, actual: msg.value});
            IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _amount);
        }
        emit Deposited(msg.sender, _token, _amount, _reference);
    }
    /// @inheritdoc IDAO
    function setSignatureValidator(address) external pure override {
        revert FunctionRemoved();
    }
    /// @inheritdoc IDAO
    /// @dev Relays the validation logic determining who is allowed to sign on behalf of the DAO to its permission manager.
    /// Caller specific bypassing can be set direct granting (i.e., `grant({_where: dao, _who: specificErc1271Caller, _permissionId: VALIDATE_SIGNATURE_PERMISSION_ID})`).
    /// Caller specific signature validation logic can be set by granting with a `PermissionCondition` (i.e., `grantWithCondition({_where: dao, _who: specificErc1271Caller, _permissionId: VALIDATE_SIGNATURE_PERMISSION_ID, _condition: yourConditionImplementation})`)
    /// Generic signature validation logic can be set for all calling contracts by granting with a `PermissionCondition` to `PermissionManager.ANY_ADDR()` (i.e., `grantWithCondition({_where: dao, _who: PermissionManager.ANY_ADDR(), _permissionId: VALIDATE_SIGNATURE_PERMISSION_ID, _condition: yourConditionImplementation})`).
    function isValidSignature(
        bytes32 _hash,
        bytes memory _signature
    ) external view override(IDAO, IERC1271) returns (bytes4) {
        if (
            isGranted({
                _where: address(this),
                _who: msg.sender,
                _permissionId: VALIDATE_SIGNATURE_PERMISSION_ID,
                _data: abi.encode(_hash, _signature)
            })
        ) {
            return 0x1626ba7e; // `type(IERC1271).interfaceId` = bytes4(keccak256("isValidSignature(bytes32,bytes)")`
        }
        return 0xffffffff; // `bytes4(uint32(type(uint32).max-1))`
    }
    /// @notice Emits the `NativeTokenDeposited` event to track native token deposits that weren't made via the deposit method.
    /// @dev This call is bound by the gas limitations for `send`/`transfer` calls introduced by [ERC-2929](https://eips.ethereum.org/EIPS/eip-2929).
    /// Gas cost increases in future hard forks might break this function. As an alternative, [ERC-2930](https://eips.ethereum.org/EIPS/eip-2930)-type transactions using access lists can be employed.
    receive() external payable {
        emit NativeTokenDeposited(msg.sender, msg.value);
    }
    /// @notice Fallback to handle future versions of the [ERC-165](https://eips.ethereum.org/EIPS/eip-165) standard.
    /// @param _input An alias being equivalent to `msg.data`. This feature of the fallback function was introduced with the [solidity compiler version 0.7.6](https://github.com/ethereum/solidity/releases/tag/v0.7.6)
    /// @return The magic number registered for the function selector triggering the fallback.
    fallback(bytes calldata _input) external returns (bytes memory) {
        bytes4 magicNumber = _handleCallback(msg.sig, _input);
        return abi.encode(magicNumber);
    }
    /// @notice Emits the MetadataSet event if new metadata is set.
    /// @param _metadata Hash of the IPFS metadata object.
    function _setMetadata(bytes calldata _metadata) internal {
        emit MetadataSet(_metadata);
    }
    /// @notice Sets the trusted forwarder on the DAO and emits the associated event.
    /// @param _trustedForwarder The trusted forwarder address.
    function _setTrustedForwarder(address _trustedForwarder) internal {
        trustedForwarder = _trustedForwarder;
        emit TrustedForwarderSet(_trustedForwarder);
    }
    /// @notice Registers the [ERC-721](https://eips.ethereum.org/EIPS/eip-721) and [ERC-1155](https://eips.ethereum.org/EIPS/eip-1155) interfaces and callbacks.
    function _registerTokenInterfaces() private {
        _registerInterface(type(IERC721ReceiverUpgradeable).interfaceId);
        _registerInterface(type(IERC1155ReceiverUpgradeable).interfaceId);
        _registerCallback(
            IERC721ReceiverUpgradeable.onERC721Received.selector,
            IERC721ReceiverUpgradeable.onERC721Received.selector
        );
        _registerCallback(
            IERC1155ReceiverUpgradeable.onERC1155Received.selector,
            IERC1155ReceiverUpgradeable.onERC1155Received.selector
        );
        _registerCallback(
            IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector,
            IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector
        );
    }
    /// @inheritdoc IDAO
    function registerStandardCallback(
        bytes4 _interfaceId,
        bytes4 _callbackSelector,
        bytes4 _magicNumber
    ) external override auth(REGISTER_STANDARD_CALLBACK_PERMISSION_ID) {
        _registerInterface(_interfaceId);
        _registerCallback(_callbackSelector, _magicNumber);
        emit StandardCallbackRegistered(_interfaceId, _callbackSelector, _magicNumber);
    }
    /// @inheritdoc IEIP4824
    function daoURI() external view returns (string memory) {
        return _daoURI;
    }
    /// @notice Updates the set DAO URI to a new value.
    /// @param newDaoURI The new DAO URI to be set.
    function setDaoURI(string calldata newDaoURI) external auth(SET_METADATA_PERMISSION_ID) {
        _setDaoURI(newDaoURI);
    }
    /// @notice Sets the new [ERC-4824](https://eips.ethereum.org/EIPS/eip-4824) DAO URI and emits the associated event.
    /// @param daoURI_ The new DAO URI.
    function _setDaoURI(string calldata daoURI_) internal {
        _daoURI = daoURI_;
        emit NewURI(daoURI_);
    }
    /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)).
    uint256[46] private __gap;
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/// @title ProxyLib
/// @author Aragon X - 2024
/// @notice A library containing methods for the deployment of proxies via the UUPS pattern (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)) and minimal proxy pattern (see [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167)).
/// @custom:security-contact [email protected]
library ProxyLib {
    using Address for address;
    using Clones for address;
    /// @notice Creates an [ERC-1967](https://eips.ethereum.org/EIPS/eip-1967) UUPS proxy contract pointing to a logic contract and allows to immediately initialize it.
    /// @param _logic The logic contract the proxy is pointing to.
    /// @param _initCalldata The initialization data for this contract.
    /// @return uupsProxy The address of the UUPS proxy contract created.
    /// @dev If `_initCalldata` is non-empty, it is used in a delegate call to the `_logic` contract. This will typically be an encoded function call initializing the storage of the proxy (see [OpenZeppelin ERC1967Proxy-constructor](https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Proxy-constructor-address-bytes-)).
    function deployUUPSProxy(
        address _logic,
        bytes memory _initCalldata
    ) internal returns (address uupsProxy) {
        uupsProxy = address(new ERC1967Proxy({_logic: _logic, _data: _initCalldata}));
    }
    /// @notice Creates an [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167) minimal proxy contract, also known as clones, pointing to a logic contract and allows to immediately initialize it.
    /// @param _logic The logic contract the proxy is pointing to.
    /// @param _initCalldata The initialization data for this contract.
    /// @return minimalProxy The address of the minimal proxy contract created.
    /// @dev If `_initCalldata` is non-empty, it is used in a call to the clone contract. This will typically be an encoded function call initializing the storage of the contract.
    function deployMinimalProxy(
        address _logic,
        bytes memory _initCalldata
    ) internal returns (address minimalProxy) {
        minimalProxy = _logic.clone();
        if (_initCalldata.length > 0) {
            minimalProxy.functionCall({data: _initCalldata});
        }
    }
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IERC20Upgradeable as IERC20 } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { ERC4626Upgradeable as ERC4626 } from
    "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ERC721HolderUpgradeable as ERC721Holder } from
    "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { PausableUpgradeable as Pausable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import { SafeERC20Upgradeable as SafeERC20 } from
    "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { VotingEscrow, Lock as LockNFT } from "@setup/GaugeVoterSetup_v1_4_0.sol";
import { DaoAuthorizableUpgradeable as DaoAuthorizable } from
    "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import { IDAO } from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import { IStrategyNFT as IStrategy } from "src/interfaces/IStrategyNFT.sol";
import { IVaultNFT } from "src/interfaces/IVaultNFT.sol";
contract AvKATVault is Initializable, IVaultNFT, ERC721Holder, Pausable, ERC4626, UUPSUpgradeable, DaoAuthorizable {
    using SafeERC20 for IERC20;
    /// @notice bytes32 identifier for admin role functions.
    bytes32 public constant VAULT_ADMIN_ROLE = keccak256("VAULT_ADMIN_ROLE");
    /// @notice bytes32 identifier of sweeper that can withdraw mistakenly depositted funds.
    bytes32 public constant SWEEPER_ROLE = keccak256("SWEEPER_ROLE");
    /// @notice The escrow contract address.
    VotingEscrow public escrow;
    /// @notice The nft contract that escrow mints in exchange of erc20 tokens.
    LockNFT public lockNft;
    /// @notice The strategy contract that holds the master token and handles escrow operations.
    IStrategy public strategy;
    /// @notice The address of default strategy that will handle deposit/withdrawals
    ///         in case custom strategy is set to zero.
    IStrategy public defaultStrategy;
    /// The single tokenId that this vault will hold and
    /// will contain all users' token ids accumulated.
    uint256 public masterTokenId;
    error MasterTokenNotSet();
    error SameStrategyNotAllowed();
    error MinMasterTokenInitAmountTooLow();
    error DefaultStrategyCannotBeZero();
    event StrategySet(address strategy);
    event AssetsDonated(uint256 assets);
    constructor() {
        _disableInitializers();
    }
    /// @param _dao The dao address.
    /// @param _escrow The escrow contract providing the asset and NFT tokens.
    /// @param _defaultStrategy The address of default strategy that handles deposit/withdraws
    ///        In case admin chooses to remove custom strategy.
    /// @param _name The name of the share token minted by this vault.
    /// @param _symbol The symbol of the share token minted by this vault.
    function initialize(
        address _dao,
        address _escrow,
        address _defaultStrategy,
        string memory _name,
        string memory _symbol
    )
        external
        initializer
    {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        __ERC20_init(_name, _symbol);
        // Always start with paused state to ensure that deposits/withdrawals can not occur.
        // Once `initializeMasterTokenAndStrategy` is called(which fills in vault), it's safer
        // to unpause at that point to avoid loses with inflation attack situations.
        _pause();
        escrow = VotingEscrow(_escrow);
        __ERC4626_init(IERC20(escrow.token()));
        lockNft = LockNFT(escrow.lockNFT());
        if (_defaultStrategy == address(0)) {
            revert DefaultStrategyCannotBeZero();
        }
        // Note: `strategy` is not set here since it should only be assigned
        // once the master token is initialized.
        // See `initializeMasterTokenAndStrategy` for details.
        defaultStrategy = IStrategy(_defaultStrategy);
    }
    /// @notice Pauses the contract, disallowing deposits/withdrawals.
    function pause() external auth(VAULT_ADMIN_ROLE) {
        _pause();
    }
    /// @notice Unpauses the contract, allowing deposits/withdrawals.
    function unpause() external auth(VAULT_ADMIN_ROLE) {
        _unpause();
    }
    /// @inheritdoc IVaultNFT
    /// @dev Initializes the vault with a master token and strategy. This function:
    ///      1. Transfers an existing NFT token from sender to become the vault's master token
    ///      2. Mints vault shares to sender proportional to the token's locked amount
    ///      3. Sets the strategy (uses defaultStrategy if _strategy is address(0))
    ///      4. Transfers the master token to the selected strategy for management
    ///
    ///      Requirements:
    ///      - Can only be called once (masterTokenId must be 0)
    ///      - Token must exist (_tokenId != 0) and be owned/approved by sender
    ///      - Token's locked amount must meet minimum threshold for security
    ///      - Caller must have VAULT_ADMIN_ROLE
    ///
    ///      After this call, the vault becomes operational and can accept deposits/withdrawals.
    ///      Until this is called, most vault operations will revert.
    function initializeMasterTokenAndStrategy(
        uint256 _tokenId,
        address _strategy
    )
        public
        virtual
        auth(VAULT_ADMIN_ROLE)
    {
        if (_tokenId == 0) revert TokenIdCannotBeZero();
        if (masterTokenId != 0) revert MasterTokenAlreadySet();
        // To start vault with non-trivial amount to avoid inflation attack,
        // require that `_tokenId` contains at least `minMasterTokenInitAmount()`.
        uint256 assetAmount = _getTokenIdAmount(_tokenId);
        if (assetAmount < minMasterTokenInitAmount()) {
            revert MinMasterTokenInitAmountTooLow();
        }
        uint256 shares = convertToShares(assetAmount);
        // Transfer `_tokenId` from sender and set it to masterTokenId
        lockNft.transferFrom(msg.sender, address(this), _tokenId);
        masterTokenId = _tokenId;
        // If _strategy is zero address, it will use default strategy.
        // This automatically will transfer masterTokenId either
        // to defaultStrategy or sender's passed strategy.
        _setStrategy(_strategy);
        // mint shares to the sender.
        _mint(msg.sender, shares);
    }
    /// @notice Allows to change a strategy contract.
    /// @param _strategy The new strategy contract.
    function setStrategy(address _strategy) public auth(VAULT_ADMIN_ROLE) {
        _setStrategy(_strategy);
    }
    /*//////////////////////////////////////////////////////////////
                        ERC4626 OVERRIDDEN LOGIC
    //////////////////////////////////////////////////////////////*/
    /// @dev Delegates to the active strategy which holds the master token
    ///      and tracks the actual asset amounts.
    /// @return Total amount of underlying assets managed by the vault.
    ///         Returns 0 if no strategy is set (vault not initialized),
    ///         otherwise returns the total locked amount from the strategy's master token.
    function totalAssets() public view virtual override returns (uint256) {
        if (address(strategy) == address(0)) {
            return 0;
        }
        return strategy.totalAssets();
    }
    /// @notice Transfer `assets` from caller to Vault, then to Strategy.
    ///      User must have approved `Vault` for this.
    function _deposit(
        address _caller,
        address _receiver,
        uint256 _assets,
        uint256 _shares
    )
        internal
        virtual
        override
        whenNotPaused
    {
        super._deposit(_caller, _receiver, _assets, _shares);
        // Approve strategy so it can transfer `_assets`.
        IERC20(asset()).approve(address(strategy), _assets);
        // Strategy handles createLock and merge to masterTokenId
        strategy.deposit(_assets);
    }
    /// @notice Overrides withdraw function from ERC4626 to allow
    ///         custom logic through strategy.
    function _withdraw(
        address _caller,
        address _receiver,
        address _owner,
        uint256 _assets,
        uint256 _shares
    )
        internal
        virtual
        override
        whenNotPaused
    {
        _withdrawWithTokenId(_caller, _receiver, _owner, _assets, _shares);
    }
    /*//////////////////////////////////////////////////////////////
                       AvKatVault Functions
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc IVaultNFT
    /// @dev Allows deposits even if `_tokenId` is already created in the escrow.
    ///      Shares are minted based on the amount locked for that tokenId in the escrow.
    function depositTokenId(uint256 _tokenId, address _receiver) public virtual whenNotPaused returns (uint256) {
        address sender = _msgSender();
        uint256 assets = _getTokenIdAmount(_tokenId);
        require(assets <= maxDeposit(_receiver), "ERC4626: deposit more than max");
        uint256 shares = previewDeposit(assets);
        // Transfer NFT directly to strategy (not vault)
        // Reverts if the caller does not own a veNFT.
        // If `amount` on tokenId is 0, either merge or withdrawal occurred in which case
        // `transferFrom` will anyways fail.
        lockNft.transferFrom(sender, address(strategy), _tokenId);
        // Strategy handles merge to masterTokenId
        strategy.depositTokenId(_tokenId);
        _mint(_receiver, shares);
        emit Deposit(sender, _receiver, assets, shares);
        emit TokenIdDepositted(_tokenId, sender);
        return shares;
    }
    /// @inheritdoc IVaultNFT
    function withdrawTokenId(
        uint256 _assets,
        address _receiver,
        address _owner
    )
        public
        virtual
        whenNotPaused
        returns (uint256 tokenId)
    {
        uint256 shares = previewWithdraw(_assets);
        return _withdrawWithTokenId(_msgSender(), _receiver, _owner, _assets, shares);
    }
    /// @dev Core withdraw logic that both `_withdraw` and `withdrawTokenId` rely on.
    function _withdrawWithTokenId(
        address _caller,
        address _receiver,
        address _owner,
        uint256 _assets,
        uint256 _shares
    )
        internal
        returns (uint256 tokenId)
    {
        if (_caller != _owner) {
            _spendAllowance(_owner, _caller, _shares);
        }
        _burn(_owner, _shares);
        // Strategy handles split and transfer to receiver
        tokenId = strategy.withdraw(_receiver, _assets);
        emit TokenIdWithdrawn(tokenId, _receiver);
        emit Withdraw(_caller, _receiver, _owner, _assets, _shares);
    }
    /// @notice Allows to donate the assets only without minting shares.
    ///         This increases assets causing each share to cost more.
    /// @param _assets How much to donate.
    function donate(uint256 _assets) public virtual whenNotPaused {
        SafeERC20.safeTransferFrom(IERC20(asset()), _msgSender(), address(this), _assets);
        // Approve strategy so it can transfer `_assets`.
        IERC20(asset()).approve(address(strategy), _assets);
        // Strategy handles createLock and merge to masterTokenId
        strategy.deposit(_assets);
        emit AssetsDonated(_assets);
    }
    /// @inheritdoc IVaultNFT
    function recoverNFT(uint256 _tokenId, address _receiver) external virtual auth(SWEEPER_ROLE) {
        if (_tokenId == masterTokenId) {
            revert CannotTransferMasterToken();
        }
        lockNft.safeTransferFrom(address(this), _receiver, _tokenId);
        emit Sweep(_tokenId, _receiver);
    }
    /// @inheritdoc IVaultNFT
    function minMasterTokenInitAmount() public view virtual returns (uint256) {
        return 10 ** decimals();
    }
    /// @dev Internal function to change the vault's active strategy.
    ///      1. Sets new strategy (uses defaultStrategy if _strategy is address(0))
    ///      2. Retrieves master token from old strategy via retireStrategy()
    ///      3. Transfers master token to new strategy via receiveMasterToken()
    ///      Requirements:
    ///      - Master token must be initialized (masterTokenId != 0)
    ///      - New strategy must be different from current strategy
    /// @param _strategy Address of the new strategy contract.
    function _setStrategy(address _strategy) internal virtual {
        address currentStrategy = address(strategy);
        if (currentStrategy == _strategy) {
            revert SameStrategyNotAllowed();
        }
        // If new strategy being set is zero, use the default one.
        strategy = _strategy != address(0) ? IStrategy(_strategy) : defaultStrategy;
        // If the strategy was set, retire it and get masterTokenId back.
        if (currentStrategy != address(0)) {
            IStrategy(currentStrategy).retireStrategy();
        }
        // strategy can only be set if master token was already initialized.
        if (masterTokenId == 0) revert MasterTokenNotSet();
        _sendMasterTokenToStrategy();
        emit StrategySet(address(strategy));
    }
    /// @notice Sends master token to strategy.
    /// @dev Caller's responsibility to ensure that `strategy` and masterTokenId are both set.
    function _sendMasterTokenToStrategy() internal virtual {
        // transfer masterTokenId to new strategy
        lockNft.transferFrom(address(this), address(strategy), masterTokenId);
        // let new strategy what the master token id is
        strategy.receiveMasterToken(masterTokenId);
    }
    /// @notice Returns the amount of ERC20 tokens locked in the escrow for a given token ID.
    /// @dev The current implementation fetches this information from `escrow`, but can be overridden if needed.
    /// @param _tokenId The token ID whose locked token balance is being retrieved.
    function _getTokenIdAmount(uint256 _tokenId) internal view virtual returns (uint256) {
        return escrow.locked(_tokenId).amount;
    }
    // =========== Upgrade Related Functions ===========
    function _authorizeUpgrade(address) internal virtual override auth(VAULT_ADMIN_ROLE) { }
    function implementation() external view returns (address) {
        return _getImplementation();
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[45] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { DaoAuthorizableUpgradeable as DaoAuthorizable } from
    "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import { IDAO } from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import { IVKatMetadata } from "src/interfaces/IVKatMetadata.sol";
contract VKatMetadata is IVKatMetadata, DaoAuthorizable, UUPSUpgradeable {
    using EnumerableSet for EnumerableSet.AddressSet;
    /// @notice The bytes32 identifier for admin role functions.
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
    /// @notice Expresses a preference to auto-compound rewards into vKat.
    address public constant AUTOCOMPOUND_RESERVED_ADDRESS = address(type(uint160).max);
    /// @notice The preferences per user.
    mapping(address => VKatMetaDataV1) private preferences;
    /// @notice The list of whitelisted tokens added by admin.
    EnumerableSet.AddressSet internal rewardTokens;
    /// @notice The default preferences that will be used if user hasn't set it.
    VKatMetaDataV1 private defaultPreferences;
    /// @notice The address of kat token.
    address public kat;
    constructor() {
        _disableInitializers();
    }
    function initialize(address _dao, address _kat, address[] calldata _rewardTokens) external initializer {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        kat = _kat;
        // whitelist reward tokens.
        for (uint256 i = 0; i < _rewardTokens.length; i++) {
            address token = _rewardTokens[i];
            rewardTokens.add(token);
            emit RewardTokenAdded(token);
        }
        // add KAT as a reward token.
        rewardTokens.add(kat);
        emit RewardTokenAdded(kat);
        // add the reserved address for auto-compounding.
        rewardTokens.add(AUTOCOMPOUND_RESERVED_ADDRESS);
        emit RewardTokenAdded(AUTOCOMPOUND_RESERVED_ADDRESS);
        // Set the default preferences to auto-compound into vKat.
        uint16[] memory _weights = new uint16[](1);
        address[] memory _tokens = new address[](1);
        VKatMetaDataV1 memory _defaultPreferences =
            VKatMetaDataV1({ rewardTokenWeights: _weights, rewardTokens: _tokens });
        _defaultPreferences.rewardTokens[0] = AUTOCOMPOUND_RESERVED_ADDRESS;
        _defaultPreferences.rewardTokenWeights[0] = 1;
        _setDefaultPreferences(_defaultPreferences);
    }
    // ============= Admin Functions ====================
    /// @inheritdoc IVKatMetadata
    function addRewardToken(address _token) external auth(ADMIN_ROLE) {
        if (_token == address(0)) {
            revert ZeroAddress();
        }
        bool added = rewardTokens.add(_token);
        if (!added) {
            revert TokenAlreadyInWhitelist(_token);
        }
        emit RewardTokenAdded(_token);
    }
    /// @inheritdoc IVKatMetadata
    function removeRewardToken(address _token) external auth(ADMIN_ROLE) {
        if (_token == AUTOCOMPOUND_RESERVED_ADDRESS || _token == kat) {
            revert ReservedAddressCannotBeRemoved();
        }
        bool removed = rewardTokens.remove(_token);
        if (!removed) {
            revert TokenNotInWhitelist(_token);
        }
        emit RewardTokenRemoved(_token);
    }
    /// @inheritdoc IVKatMetadata
    function setDefaultPreferences(VKatMetaDataV1 memory _preferences) external auth(ADMIN_ROLE) {
        _setDefaultPreferences(_preferences);
    }
    // ============ User Specific Functions =============
    /// @inheritdoc IVKatMetadata
    function setPreferences(VKatMetaDataV1 calldata _preferences) public virtual {
        _validatePreferences(_preferences);
        preferences[msg.sender] = _preferences;
        emit PreferencesSet(msg.sender, _preferences);
    }
    // =========== View Functions ==============
    /// @inheritdoc IVKatMetadata
    function isRewardToken(address _token) public view returns (bool) {
        return rewardTokens.contains(_token);
    }
    /// @inheritdoc IVKatMetadata
    function getPreferencesOrDefault(address _account) public view returns (VKatMetaDataV1 memory) {
        VKatMetaDataV1 memory preferences_ = preferences[_account];
        if (preferences_.rewardTokens.length == 0) {
            preferences_ = getDefaultPreferences();
        }
        return preferences_;
    }
    /// @inheritdoc IVKatMetadata
    function getDefaultPreferences() public view virtual returns (VKatMetaDataV1 memory) {
        return defaultPreferences;
    }
    /// @inheritdoc IVKatMetadata
    function allowedRewardTokens() external view returns (address[] memory) {
        return rewardTokens.values();
    }
    /// @dev Helper function to validate the new default preferences and set it.
    function _setDefaultPreferences(VKatMetaDataV1 memory _preferences) internal virtual {
        _validatePreferences(_preferences);
        defaultPreferences = _preferences;
        emit DefaultPreferencesSet(_preferences);
    }
    function _validatePreferences(VKatMetaDataV1 memory _preferences) internal virtual {
        if (_preferences.rewardTokens.length != _preferences.rewardTokenWeights.length) {
            revert LengthMismatch();
        }
        address[] memory tokens = _preferences.rewardTokens;
        for (uint256 i = 0; i < tokens.length; i++) {
            address token = tokens[i];
            // Validate that reward token is already
            // added by admin in a whitelist.
            if (!isRewardToken(token)) {
                revert TokenNotWhitelisted(token);
            }
            // Ensure for no duplicate addresses
            for (uint256 j = i + 1; j < tokens.length; j++) {
                if (tokens[j] == token) {
                    revert DuplicateRewardToken();
                }
            }
        }
    }
    // =========== Upgrade Related Functions ===========
    function _authorizeUpgrade(address) internal override auth(ADMIN_ROLE) { }
    function implementation() external view returns (address) {
        return _getImplementation();
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[44] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { IERC20Upgradeable as IERC20 } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { ERC721HolderUpgradeable as ERC721Holder } from
    "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import { SafeERC20Upgradeable as SafeERC20 } from
    "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { VotingEscrow, GaugeVoter, EscrowIVotesAdapter } from "@setup/GaugeVoterSetup_v1_4_0.sol";
import { DaoAuthorizableUpgradeable as DaoAuthorizable } from
    "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import { Action } from "@aragon/osx-commons-contracts/src/executors/IExecutor.sol";
import { IDAO } from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import { AvKATVault } from "src/AvKATVault.sol";
import { Swapper } from "src/Swapper.sol";
import { ISwapper } from "src/interfaces/ISwapper.sol";
import { IRewardsDistributor } from "src/interfaces/IRewardsDistributor.sol";
import { IStrategy } from "src/interfaces/IStrategy.sol";
import { NFTBaseStrategy } from "../abstracts/NFTBaseStrategy.sol";
contract AragonMerklAutoCompoundStrategy is
    Initializable,
    ERC721Holder,
    UUPSUpgradeable,
    DaoAuthorizable,
    NFTBaseStrategy
{
    using SafeERC20 for IERC20;
    ///@notice The bytes32 identifier for admin role functions.
    bytes32 public constant AUTOCOMPOUND_STRATEGY_ADMIN_ROLE = keccak256("AUTOCOMPOUND_STRATEGY_ADMIN_ROLE");
    ///@notice The bytes32 identifier for vote function.
    bytes32 public constant AUTOCOMPOUND_STRATEGY_VOTE_ROLE = keccak256("AUTOCOMPOUND_STRATEGY_VOTE_ROLE");
    ///@notice The bytes32 identifier for claimAndCompound function.
    bytes32 public constant AUTOCOMPOUND_STRATEGY_CLAIM_COMPOUND_ROLE =
        keccak256("AUTOCOMPOUND_STRATEGY_CLAIM_COMPOUND_ROLE");
    /// @notice The gauge voter where this contract votes for gauges.
    GaugeVoter public voter;
    /// @notice The vault address where this contract auto-compounds(deposits kat).
    AvKATVault public vault;
    /// @notice The swapper contract which this contract asks for claiming tokens.
    address public swapper;
    /// @notice The ivotes adapter for delegation
    EscrowIVotesAdapter public ivotesAdapter;
    /// @notice The address that this strategy delegates voting power to.
    address public delegatee;
    /// @notice The rewards distributor contract that this contract needs to approve.
    address public rewardsDistributor;
    /// @notice Emitted when the admin withdraws mistakenly withdraws token ids.
    event Sweep(uint256[] tokenIds, address receiver);
    /// @notice Thrown when the admin tries to withdraw master token id.
    error CannotTransferMasterToken();
    constructor() {
        _disableInitializers();
    }
    function initialize(
        address _dao,
        address _escrow,
        address _swapper,
        address _vault,
        address _rewardDistributor
    )
        external
        initializer
    {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        ivotesAdapter = EscrowIVotesAdapter(VotingEscrow(_escrow).ivotesAdapter());
        voter = GaugeVoter(VotingEscrow(_escrow).voter());
        vault = AvKATVault(_vault);
        swapper = _swapper;
        rewardsDistributor = _rewardDistributor;
        __NFTBaseStrategy_init(_escrow, VotingEscrow(_escrow).token(), VotingEscrow(_escrow).lockNFT(), _vault);
    }
    /// @notice Sets the delegatee address for voting power delegation.
    /// @param _delegatee The address to delegate voting power to.
    function delegate(address _delegatee) public virtual auth(AUTOCOMPOUND_STRATEGY_ADMIN_ROLE) {
        delegatee = _delegatee;
        if (_delegatee != address(0)) {
            ivotesAdapter.delegate(_delegatee);
        }
    }
    /// @notice Claims and swaps token. If claimed amount for `token` is > 0,
    ///         it donates(i.e increases totalAssets) without minting shares.
    /// @dev    Even if `_actions[i].value` > 0, this contract will never receive.
    /// @param _tokens Which tokens to claim.
    /// @param _amounts How much to claim for each token.
    /// @param _proofs The merkle proof that this contract holds `_amounts` on merkle distributor.
    /// @param _actions The actions that Swapper contract executes. Most times, it will be swap actions.
    /// @return Returns shares that were minted in exchange for depositting kat tokens.
    function claimAndCompound(
        address[] calldata _tokens,
        uint256[] calldata _amounts,
        bytes32[][] calldata _proofs,
        Action[] calldata _actions
    )
        public
        virtual
        returns (uint256)
    {
        // Grant swapper temporary permission to claim on behalf of this contract.
        _toggleSwapperOperator();
        // Set swapper as claim recipients for all `_tokens`.
        _setClaimRecipients(swapper, _tokens);
        // which tokens to claim for with their proofs and amounts.
        ISwapper.Claim memory claimTokens = ISwapper.Claim(_tokens, _amounts, _proofs);
        (uint256 claimedAmount,) = ISwapper(swapper).claimAndSwap(claimTokens, _actions, 0);
        // Revoke swapper's permission.
        _toggleSwapperOperator();
        return claimedAmount;
    }
    /// @notice Votes on gauge voter with `_votes`.
    /// @dev The caller must invoke `delegate` with this strategy’s address, effectively delegating to itself.
    /// @param _votes The gauges and their weights to vote for.
    function vote(GaugeVoter.GaugeVote[] calldata _votes) external virtual auth(AUTOCOMPOUND_STRATEGY_VOTE_ROLE) {
        voter.vote(_votes);
    }
    /// @notice Allows the admin to withdraw specified token IDs, provided none are the master token.
    /// @dev This allows to withdraw tokens that have been mistakenly transfered to strategy contract.
    /// @param _tokenIds The token IDs to withdraw. All IDs must currently be held by this strategy.
    /// @param _receiver The address that will receive the NFTs.
    function withdrawTokens(
        uint256[] memory _tokenIds,
        address _receiver
    )
        external
        virtual
        auth(AUTOCOMPOUND_STRATEGY_ADMIN_ROLE)
    {
        for (uint256 i = 0; i < _tokenIds.length; i++) {
            uint256 tokenId = _tokenIds[i];
            if (tokenId == masterTokenId) {
                revert CannotTransferMasterToken();
            }
            nft.safeTransferFrom(address(this), _receiver, tokenId);
        }
        emit Sweep(_tokenIds, _receiver);
    }
    /// @inheritdoc IStrategy
    function retireStrategy() public virtual override {
        // For safety reasons, revoke current delegatee
        ivotesAdapter.delegate(address(0));
        super.retireStrategy();
    }
    /// @dev Toggles the swapper's operator permission on the rewards distributor.
    /// First call enables the swapper to claim on behalf of this contract.
    /// Second call revokes that permission. Acts as a temporary authorization gate.
    function _toggleSwapperOperator() internal virtual {
        IRewardsDistributor(rewardsDistributor).toggleOperator(address(this), swapper);
    }
    /// @dev Sets recipient for each token in order for the claim reward
    ///      to be transferred to that recipient.
    function _setClaimRecipients(address _recipient, address[] calldata _tokens) internal virtual {
        for (uint256 i = 0; i < _tokens.length; i++) {
            IRewardsDistributor(rewardsDistributor).setClaimRecipient(_recipient, _tokens[i]);
        }
    }
    /*//////////////////////////////////////////////////////////////
                        Upgrade
    //////////////////////////////////////////////////////////////*/
    function _authorizeUpgrade(address) internal virtual override auth(AUTOCOMPOUND_STRATEGY_ADMIN_ROLE) { }
    function implementation() external view returns (address) {
        return _getImplementation();
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[44] private __gap;
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import { ProxyLib } from "@aragon/osx-commons-contracts/src/utils/deployment/ProxyLib.sol";
import { AccessControlManager } from "@merkl/AccessControlManager.sol";
import { Distributor as MerklDistributor } from "@merkl/Distributor.sol";
import { AvKATVault } from "src/AvKATVault.sol";
import { Swapper } from "src/Swapper.sol";
import { AragonMerklAutoCompoundStrategy as AutoCompoundStrategy } from
    "src/strategies/AragonMerklAutoCompoundStrategy.sol";
import { VKatMetadata } from "src/VKatMetadata.sol";
import { IVKatMetadata } from "src/interfaces/IVKatMetadata.sol";
function deployVault(
    address _dao,
    address _escrow,
    address _defaultStrategy,
    string memory _name,
    string memory _symbol
)
    returns (address, address)
{
    address vaultBase = address(new AvKATVault());
    address vault = ProxyLib.deployUUPSProxy(
        vaultBase, abi.encodeCall(AvKATVault.initialize, (_dao, _escrow, _defaultStrategy, _name, _symbol))
    );
    return (vaultBase, vault);
}
function deploySwapper(address _merkleDistributor, address _escrow) returns (address) {
    address swapper = address(new Swapper(_merkleDistributor, _escrow));
    return swapper;
}
function deployAutoCompoundStrategy(
    address _dao,
    address _escrow,
    address _swapper,
    address _vault,
    address _merklDistributor
)
    returns (address, address)
{
    address strategyBase = address(new AutoCompoundStrategy());
    address strategy = ProxyLib.deployUUPSProxy(
        strategyBase,
        abi.encodeCall(AutoCompoundStrategy.initialize, (_dao, _escrow, _swapper, _vault, _merklDistributor))
    );
    return (strategyBase, strategy);
}
function deployVKatMetadata(address _dao, address _token, address[] memory _rewardTokens) returns (address, address) {
    address metadataBase = address(new VKatMetadata());
    address vkatMetadata =
        ProxyLib.deployUUPSProxy(metadataBase, abi.encodeCall(VKatMetadata.initialize, (_dao, _token, _rewardTokens)));
    return (metadataBase, vkatMetadata);
}
function deployMerklDistributor(address _aclManager, address _guardian) returns (address, address) {
    address acm = ProxyLib.deployUUPSProxy(
        address(new AccessControlManager()), abi.encodeCall(AccessControlManager.initialize, (_aclManager, _guardian))
    );
    address merklDistributor = ProxyLib.deployUUPSProxy(
        address(new MerklDistributor()), abi.encodeCall(MerklDistributor.initialize, AccessControlManager(acm))
    );
    return (acm, merklDistributor);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { IERC20Upgradeable as IERC20 } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { SafeERC20Upgradeable as SafeERC20 } from
    "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { VotingEscrow } from "@setup/GaugeVoterSetup_v1_4_0.sol";
import { DaoAuthorizableUpgradeable as DaoAuthorizable } from
    "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import { IDAO } from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import { NFTBaseStrategy } from "../abstracts/NFTBaseStrategy.sol";
contract DefaultStrategy is Initializable, UUPSUpgradeable, DaoAuthorizable, NFTBaseStrategy {
    using SafeERC20 for IERC20;
    ///@notice The bytes32 identifier for admin role functions.
    bytes32 public constant DEFAULT_STRATEGY_ADMIN_ROLE = keccak256("DEFAULT_STRATEGY_ADMIN_ROLE");
    /// @notice Initializes the default strategy contract.
    /// @param _dao The DAO contract address for permission management.
    /// @param _escrow The VotingEscrow contract that manages locked tokens
    /// @param _owner The address that will own this strategy (typically the vault)
    function initialize(address _dao, address _escrow, address _owner) external reinitializer(1) {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        __NFTBaseStrategy_init(_escrow, VotingEscrow(_escrow).token(), VotingEscrow(_escrow).lockNFT(), _owner);
    }
    /// @notice Updates the owner of the strategy contract.
    /// @dev This function is used for ownership migration or corrections.
    ///      Uses reinitializer(2) to ensure it can only be called once after upgrade.
    /// @param _owner The new owner address (typically should be the vault contract)
    function initializeOwner(address _owner) external reinitializer(2) {
        _transferOwnership(_owner);
    }
    /*//////////////////////////////////////////////////////////////
                        Upgrade
    //////////////////////////////////////////////////////////////*/
    function _authorizeUpgrade(address) internal virtual override auth(DEFAULT_STRATEGY_ADMIN_ROLE) { }
    function implementation() external view returns (address) {
        return _getImplementation();
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;
    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;
    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);
    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }
    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }
    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }
    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }
    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }
    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.
        return account.code.length > 0;
    }
    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");
        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }
    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }
    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }
    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }
    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title IPermissionCondition /// @author Aragon X - 2021-2023 /// @notice An interface to be implemented to support custom permission logic. /// @dev To attach a condition to a permission, the `grantWithCondition` function must be used and refer to the implementing contract's address with the `condition` argument. /// @custom:security-contact [email protected] interface IPermissionCondition { /// @notice Checks if a call is permitted. /// @param _where The address of the target contract. /// @param _who The address (EOA or contract) for which the permissions are checked. /// @param _permissionId The permission identifier. /// @param _data Optional data passed to the `PermissionCondition` implementation. /// @return isPermitted Returns true if the call is permitted. function isGranted( address _where, address _who, bytes32 _permissionId, bytes calldata _data ) external view returns (bool isPermitted); }
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IProtocolVersion} from "../../utils/versioning/IProtocolVersion.sol";
import {ProtocolVersion} from "../../utils/versioning/ProtocolVersion.sol";
import {IPermissionCondition} from "./IPermissionCondition.sol";
/// @title PermissionCondition
/// @author Aragon X - 2023
/// @notice An abstract contract for non-upgradeable contracts instantiated via the `new` keyword  to inherit from to support customary permissions depending on arbitrary on-chain state.
/// @custom:security-contact [email protected]
abstract contract PermissionCondition is ERC165, IPermissionCondition, ProtocolVersion {
    /// @notice Checks if an interface is supported by this or its parent contract.
    /// @param _interfaceId The ID of the interface.
    /// @return Returns `true` if the interface is supported.
    function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
        return
            _interfaceId == type(IPermissionCondition).interfaceId ||
            _interfaceId == type(IProtocolVersion).interfaceId ||
            super.supportsInterface(_interfaceId);
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }
    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }
    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.
        return account.code.length > 0;
    }
    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");
        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }
    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }
    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }
    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }
    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }
    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }
    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
    /**
     * @dev Returns true if `account` supports the {IERC165} interface.
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
    }
    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }
    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(
        address account,
        bytes4[] memory interfaceIds
    ) internal view returns (bool[] memory) {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }
        return interfaceIdsSupported;
    }
    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }
        // query support of each interface in interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }
        // all interfaces supported
        return true;
    }
    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     *
     * Some precompiled contracts will falsely indicate support for a given interface, so caution
     * should be exercised when using this function.
     *
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }
        return success && returnSize >= 0x20 && returnValue > 0;
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title IDAO /// @author Aragon X - 2022-2024 /// @notice The interface required for DAOs within the Aragon App DAO framework. /// @custom:security-contact [email protected] interface IDAO { /// @notice Checks if an address has permission on a contract via a permission identifier and considers if `ANY_ADDRESS` was used in the granting process. /// @param _where The address of the contract. /// @param _who The address of a EOA or contract to give the permissions. /// @param _permissionId The permission identifier. /// @param _data The optional data passed to the `PermissionCondition` registered. /// @return Returns true if the address has permission, false if not. function hasPermission( address _where, address _who, bytes32 _permissionId, bytes memory _data ) external view returns (bool); /// @notice Updates the DAO metadata (e.g., an IPFS hash). /// @param _metadata The IPFS hash of the new metadata object. function setMetadata(bytes calldata _metadata) external; /// @notice Emitted when the DAO metadata is updated. /// @param metadata The IPFS hash of the new metadata object. event MetadataSet(bytes metadata); /// @notice Emitted when a standard callback is registered. /// @param interfaceId The ID of the interface. /// @param callbackSelector The selector of the callback function. /// @param magicNumber The magic number to be registered for the callback function selector. event StandardCallbackRegistered( bytes4 interfaceId, bytes4 callbackSelector, bytes4 magicNumber ); /// @notice Deposits (native) tokens to the DAO contract with a reference string. /// @param _token The address of the token or address(0) in case of the native token. /// @param _amount The amount of tokens to deposit. /// @param _reference The reference describing the deposit reason. function deposit(address _token, uint256 _amount, string calldata _reference) external payable; /// @notice Emitted when a token deposit has been made to the DAO. /// @param sender The address of the sender. /// @param token The address of the deposited token. /// @param amount The amount of tokens deposited. /// @param _reference The reference describing the deposit reason. event Deposited( address indexed sender, address indexed token, uint256 amount, string _reference ); /// @notice Emitted when a native token deposit has been made to the DAO. /// @dev This event is intended to be emitted in the `receive` function and is therefore bound by the gas limitations for `send`/`transfer` calls introduced by [ERC-2929](https://eips.ethereum.org/EIPS/eip-2929). /// @param sender The address of the sender. /// @param amount The amount of native tokens deposited. event NativeTokenDeposited(address sender, uint256 amount); /// @notice Setter for the trusted forwarder verifying the meta transaction. /// @param _trustedForwarder The trusted forwarder address. function setTrustedForwarder(address _trustedForwarder) external; /// @notice Getter for the trusted forwarder verifying the meta transaction. /// @return The trusted forwarder address. function getTrustedForwarder() external view returns (address); /// @notice Emitted when a new TrustedForwarder is set on the DAO. /// @param forwarder the new forwarder address. event TrustedForwarderSet(address forwarder); /// @notice Checks whether a signature is valid for a provided hash according to [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271). /// @param _hash The hash of the data to be signed. /// @param _signature The signature byte array associated with `_hash`. /// @return Returns the `bytes4` magic value `0x1626ba7e` if the signature is valid and `0xffffffff` if not. function isValidSignature(bytes32 _hash, bytes memory _signature) external returns (bytes4); /// @notice Registers an ERC standard having a callback by registering its [ERC-165](https://eips.ethereum.org/EIPS/eip-165) interface ID and callback function signature. /// @param _interfaceId The ID of the interface. /// @param _callbackSelector The selector of the callback function. /// @param _magicNumber The magic number to be registered for the function signature. function registerStandardCallback( bytes4 _interfaceId, bytes4 _callbackSelector, bytes4 _magicNumber ) external; /// @notice Removed function being left here to not corrupt the IDAO interface ID. Any call will revert. /// @dev Introduced in v1.0.0. Removed in v1.4.0. function setSignatureValidator(address) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {PermissionLib} from "../../permission/PermissionLib.sol";
// solhint-disable-next-line no-unused-import
import {IDAO} from "../../dao/IDAO.sol";
/// @title IPluginSetup
/// @author Aragon X - 2022-2023
/// @notice The interface required for a plugin setup contract to be consumed by the `PluginSetupProcessor` for plugin installations, updates, and uninstallations.
/// @custom:security-contact [email protected]
interface IPluginSetup {
    /// @notice The data associated with a prepared setup.
    /// @param helpers The address array of helpers (contracts or EOAs) associated with this plugin version after the installation or update.
    /// @param permissions The array of multi-targeted permission operations to be applied by the `PluginSetupProcessor` to the installing or updating DAO.
    struct PreparedSetupData {
        address[] helpers;
        PermissionLib.MultiTargetPermission[] permissions;
    }
    /// @notice The payload for plugin updates and uninstallations containing the existing contracts as well as optional data to be consumed by the plugin setup.
    /// @param plugin The address of the `Plugin`.
    /// @param currentHelpers The address array of all current helpers (contracts or EOAs) associated with the plugin to update from.
    /// @param data The bytes-encoded data containing the input parameters for the preparation of update/uninstall as specified in the corresponding ABI on the version's metadata.
    struct SetupPayload {
        address plugin;
        address[] currentHelpers;
        bytes data;
    }
    /// @notice Prepares the installation of a plugin.
    /// @param _dao The address of the installing DAO.
    /// @param _data The bytes-encoded data containing the input parameters for the installation as specified in the plugin's build metadata JSON file.
    /// @return plugin The address of the `Plugin` contract being prepared for installation.
    /// @return preparedSetupData The deployed plugin's relevant data which consists of helpers and permissions.
    function prepareInstallation(
        address _dao,
        bytes calldata _data
    ) external returns (address plugin, PreparedSetupData memory preparedSetupData);
    /// @notice Prepares the update of a plugin.
    /// @param _dao The address of the updating DAO.
    /// @param _fromBuild The build number of the plugin to update from.
    /// @param _payload The relevant data necessary for the `prepareUpdate`. See above.
    /// @return initData The initialization data to be passed to upgradeable contracts when the update is applied in the `PluginSetupProcessor`.
    /// @return preparedSetupData The deployed plugin's relevant data which consists of helpers and permissions.
    function prepareUpdate(
        address _dao,
        uint16 _fromBuild,
        SetupPayload calldata _payload
    ) external returns (bytes memory initData, PreparedSetupData memory preparedSetupData);
    /// @notice Prepares the uninstallation of a plugin.
    /// @param _dao The address of the uninstalling DAO.
    /// @param _payload The relevant data necessary for the `prepareUninstallation`. See above.
    /// @return permissions The array of multi-targeted permission operations to be applied by the `PluginSetupProcessor` to the uninstalling DAO.
    function prepareUninstallation(
        address _dao,
        SetupPayload calldata _payload
    ) external returns (PermissionLib.MultiTargetPermission[] memory permissions);
    /// @notice Returns the plugin implementation address.
    /// @return The address of the plugin implementation contract.
    /// @dev The implementation can be instantiated via the `new` keyword, cloned via the minimal proxy pattern (see [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167)), or proxied via the UUPS proxy pattern (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function implementation() external view returns (address);
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {Action} from "../../../executors/IExecutor.sol";
/// @title IProposal
/// @author Aragon X - 2022-2024
/// @notice An interface to be implemented by DAO plugins that create and execute proposals.
/// @custom:security-contact [email protected]
interface IProposal {
    /// @notice Emitted when a proposal is created.
    /// @param proposalId The ID of the proposal.
    /// @param creator  The creator of the proposal.
    /// @param startDate The start date of the proposal in seconds.
    /// @param endDate The end date of the proposal in seconds.
    /// @param metadata The metadata of the proposal.
    /// @param actions The actions that will be executed if the proposal passes.
    /// @param allowFailureMap A bitmap allowing the proposal to succeed, even if individual actions might revert.
    ///     If the bit at index `i` is 1, the proposal succeeds even if the `i`th action reverts.
    ///     A failure map value of 0 requires every action to not revert.
    event ProposalCreated(
        uint256 indexed proposalId,
        address indexed creator,
        uint64 startDate,
        uint64 endDate,
        bytes metadata,
        Action[] actions,
        uint256 allowFailureMap
    );
    /// @notice Emitted when a proposal is executed.
    /// @param proposalId The ID of the proposal.
    event ProposalExecuted(uint256 indexed proposalId);
    /// @notice Creates a new proposal.
    /// @param _metadata The metadata of the proposal.
    /// @param _actions The actions that will be executed after the proposal passes.
    /// @param _startDate The start date of the proposal.
    /// @param _endDate The end date of the proposal.
    /// @param _data The additional abi-encoded data to include more necessary fields.
    /// @return proposalId The id of the proposal.
    function createProposal(
        bytes memory _metadata,
        Action[] memory _actions,
        uint64 _startDate,
        uint64 _endDate,
        bytes memory _data
    ) external returns (uint256 proposalId);
    /// @notice Whether proposal succeeded or not.
    /// @dev Note that this must not include time window checks and only make a decision based on the thresholds.
    /// @param _proposalId The id of the proposal.
    /// @return Returns if proposal has been succeeded or not without including time window checks.
    function hasSucceeded(uint256 _proposalId) external view returns (bool);
    /// @notice Executes a proposal.
    /// @param _proposalId The ID of the proposal to be executed.
    function execute(uint256 _proposalId) external;
    /// @notice Checks if a proposal can be executed.
    /// @param _proposalId The ID of the proposal to be checked.
    /// @return True if the proposal can be executed, false otherwise.
    function canExecute(uint256 _proposalId) external view returns (bool);
    /// @notice The human-readable abi format for extra params included in `data` of `createProposal`.
    /// @dev Used for UI to easily detect what extra params the contract expects.
    /// @return ABI of params in `data` of `createProposal`.
    function customProposalParamsABI() external view returns (string memory);
    /// @notice Returns the proposal count which determines the next proposal ID.
    /// @dev This function is deprecated but remains in the interface for backward compatibility.
    ///      It now reverts to prevent ambiguity.
    /// @return The proposal count.
    function proposalCount() external view returns (uint256);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/// @title ProxyLib
/// @author Aragon X - 2024
/// @notice A library containing methods for the deployment of proxies via the UUPS pattern (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)) and minimal proxy pattern (see [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167)).
/// @custom:security-contact [email protected]
library ProxyLib {
    using Address for address;
    using Clones for address;
    /// @notice Creates an [ERC-1967](https://eips.ethereum.org/EIPS/eip-1967) UUPS proxy contract pointing to a logic contract and allows to immediately initialize it.
    /// @param _logic The logic contract the proxy is pointing to.
    /// @param _initCalldata The initialization data for this contract.
    /// @return uupsProxy The address of the UUPS proxy contract created.
    /// @dev If `_initCalldata` is non-empty, it is used in a delegate call to the `_logic` contract. This will typically be an encoded function call initializing the storage of the proxy (see [OpenZeppelin ERC1967Proxy-constructor](https://docs.openzeppelin.com/contracts/4.x/api/proxy#ERC1967Proxy-constructor-address-bytes-)).
    function deployUUPSProxy(
        address _logic,
        bytes memory _initCalldata
    ) internal returns (address uupsProxy) {
        uupsProxy = address(new ERC1967Proxy({_logic: _logic, _data: _initCalldata}));
    }
    /// @notice Creates an [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167) minimal proxy contract, also known as clones, pointing to a logic contract and allows to immediately initialize it.
    /// @param _logic The logic contract the proxy is pointing to.
    /// @param _initCalldata The initialization data for this contract.
    /// @return minimalProxy The address of the minimal proxy contract created.
    /// @dev If `_initCalldata` is non-empty, it is used in a call to the clone contract. This will typically be an encoded function call initializing the storage of the contract.
    function deployMinimalProxy(
        address _logic,
        bytes memory _initCalldata
    ) internal returns (address minimalProxy) {
        minimalProxy = _logic.clone();
        if (_initCalldata.length > 0) {
            minimalProxy.functionCall({data: _initCalldata});
        }
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IProtocolVersion} from "../../utils/versioning/IProtocolVersion.sol";
import {ProtocolVersion} from "../../utils/versioning/ProtocolVersion.sol";
import {IPluginSetup} from "./IPluginSetup.sol";
/// @title PluginSetup
/// @author Aragon X - 2022-2024
/// @notice An abstract contract to inherit from to implement the plugin setup for non-upgradeable plugins, i.e,
/// - `Plugin` being deployed via the `new` keyword
/// - `PluginCloneable` being deployed via the minimal proxy pattern (see [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167)).
/// @custom:security-contact [email protected]
abstract contract PluginSetup is ERC165, IPluginSetup, ProtocolVersion {
    /// @notice The address of the plugin implementation contract for initial block explorer verification and, in the case of `PluginClonable` implementations, to create [ERC-1167](https://eips.ethereum.org/EIPS/eip-1167) clones from.
    address internal immutable IMPLEMENTATION;
    /// @notice Thrown when attempting to prepare an update on a non-upgradeable plugin.
    error NonUpgradeablePlugin();
    /// @notice The contract constructor, that setting the plugin implementation contract.
    /// @param _implementation The address of the plugin implementation contract.
    constructor(address _implementation) {
        IMPLEMENTATION = _implementation;
    }
    /// @inheritdoc IPluginSetup
    /// @dev Since the underlying plugin is non-upgradeable, this non-virtual function must always revert.
    function prepareUpdate(
        address _dao,
        uint16 _fromBuild,
        SetupPayload calldata _payload
    ) external returns (bytes memory, PreparedSetupData memory) {
        (_dao, _fromBuild, _payload);
        revert NonUpgradeablePlugin();
    }
    /// @notice Checks if this or the parent contract supports an interface by its ID.
    /// @param _interfaceId The ID of the interface.
    /// @return Returns `true` if the interface is supported.
    function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
        return
            _interfaceId == type(IPluginSetup).interfaceId ||
            _interfaceId == type(IProtocolVersion).interfaceId ||
            super.supportsInterface(_interfaceId);
    }
    /// @inheritdoc IPluginSetup
    function implementation() public view returns (address) {
        return IMPLEMENTATION;
    }
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IClockUser, IClockV1_2_0 as IClock} from "@clock/IClock_v1_2_0.sol";
import {IAddressGaugeVoter} from "./IAddressGaugeVoter.sol";
import {ReentrancyGuardUpgradeable as ReentrancyGuard} from
    "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IVotesUpgradeable as IVotes} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
import {PluginUUPSUpgradeable} from "@aragon/osx-commons-contracts/src/plugin/PluginUUPSUpgradeable.sol";
contract AddressGaugeVoter is IAddressGaugeVoter, IClockUser, ReentrancyGuard, Pausable, PluginUUPSUpgradeable {
    /// @notice The Gauge admin can can create and manage voting gauges for token holders
    bytes32 public constant GAUGE_ADMIN_ROLE = keccak256("GAUGE_ADMIN");
    /// @notice Address of the voting escrow contract that will track voting power
    address public escrow;
    /// @notice Clock contract for epoch duration
    address public clock;
    /// @notice epoch => The total votes that have accumulated in this contract
    mapping(uint256 => uint256) public epochTotalVotingPowerCast;
    /// @notice enumerable list of all gauges that can be voted on
    address[] public gaugeList;
    /// @notice address => gauge data
    mapping(address => Gauge) public gauges;
    /// @notice epoch => gauge => total votes (global)
    mapping(uint256 => mapping(address => uint256)) public epochGaugeVotes;
    /// @dev epoch => address => AddressVoteData
    mapping(uint256 => mapping(address => AddressVoteData)) internal epochVoteData;
    /// @notice Delegation mapper contract
    address public ivotesAdapter;
    /// @notice Activate updateVotingPower hook
    /// @dev This is used to update the voting power of the sender and receiver
    ///      when the delegation mapper is set.
    ///      If the delegation mapper is not set, or the hook is not activated,
    ///      then the voting power will not be updated automatically.
    bool public enableUpdateVotingPowerHook;
    /*///////////////////////////////////////////////////////////////
                            Initialization
    //////////////////////////////////////////////////////////////*/
    constructor() {
        _disableInitializers();
    }
    function initialize(
        address _dao,
        address _escrow,
        bool _startPaused,
        address _clock,
        address _ivotesAdapter,
        bool _enableUpdateVotingPowerHook
    ) external initializer {
        __PluginUUPSUpgradeable_init(IDAO(_dao));
        __ReentrancyGuard_init();
        __Pausable_init();
        escrow = _escrow;
        clock = _clock;
        ivotesAdapter = _ivotesAdapter;
        enableUpdateVotingPowerHook = _enableUpdateVotingPowerHook;
        if (_startPaused) _pause();
    }
    /*///////////////////////////////////////////////////////////////
                            Modifiers
    //////////////////////////////////////////////////////////////*/
    function pause() external auth(GAUGE_ADMIN_ROLE) {
        _pause();
    }
    function unpause() external auth(GAUGE_ADMIN_ROLE) {
        _unpause();
    }
    modifier whenVotingActive() {
        if (!votingActive()) revert VotingInactive();
        _;
    }
    modifier onlyEscrow() {
        if (msg.sender != escrow) revert OnlyEscrow();
        _;
    }
    /*///////////////////////////////////////////////////////////////
                               Voting
    //////////////////////////////////////////////////////////////*/
    function vote(GaugeVote[] calldata _votes) public nonReentrant whenNotPaused whenVotingActive {
        address account = msg.sender;
        _vote(account, _votes);
    }
    /**
     * @dev If `enableUpdateVotingPowerHook` is false, It's assumed that token contract does/can NOT call
     * `updateVotingPower` during transfers This can happen if the token is already deployed and non-upgradeable,
     * or for other design limitations. In such cases, relying on `getVotes(_account)` (which reflects live balance)
     * instead of `getPastVotes(...)` (which snapshots voting power at a fixed time) can lead
     * to critical vulnerabilities, including double voting.
     *
     * Example of the issue:
     * - Ts 100: Epoch begins, voting window opens.
     * - Ts 110: Alice has 1000 votes.
     * - Ts 120: Alice votes for Gauge A with all 1000.
     * - Ts 130: Alice transfers tokens to Bob, but `updateVotingPower` is NOT triggered.
     * - Ts 140: Bob now votes for Gauge B using the same 1000 tokens.
     *
     * Result: The same 1000 tokens were used to vote for *two* gauges in the same epoch — a double spend.
     *
     * To prevent this, we use `getPastVotes(_account, currentEpochStart())`, which ensures voting power is fixed at epoch start.
     * Even if a transfer happens mid-epoch, the recipient (e.g., Bob) cannot vote in that epoch because their `getPastVotes(...)`
     * will return 0.
     *
     * Note: Once a new epoch starts, Bob *can* vote with the transferred tokens, but this is safe.
     * Since gauge vote tracking is scoped per-epoch, votes from Alice in epoch 11 and from Bob in epoch 12 are kept separate.
     * Querying Gauge A’s votes in epoch 12 will correctly return 1000, not 2000 — avoiding any vote inflation.
     */
    function _vote(address _account, GaugeVote[] memory _votes) internal {
        uint256 votingPower = enableUpdateVotingPowerHook
            ? IVotes(ivotesAdapter).getVotes(_account)
            : IVotes(ivotesAdapter).getPastVotes(_account, currentEpochStart());
        if (votingPower == 0) revert NoVotingPower();
        uint256 numVotes = _votes.length;
        if (numVotes == 0) revert NoVotes();
        // clear any existing votes
        if (isVoting(_account)) _reset(_account);
        uint256 epoch = getWriteEpochId();
        // voting power continues to increase over the voting epoch.
        // this means you can revote later in the epoch to increase votes.
        // while not a huge problem, it's worth noting that when rewards are fully
        // on chain, this could be a vector for gaming.
        AddressVoteData storage voteData = epochVoteData[epoch][_account];
        uint256 totalWeight = _getTotalWeight(_votes);
        // this is technically redundant as checks below will revert div by zero
        // but it's clearer to the caller if we revert here
        if (totalWeight == 0) revert NoVotes();
        // iterate over votes and distribute weight
        for (uint256 i = 0; i < numVotes; i++) {
            GaugeVote memory currentVote = _votes[i];
            _safeCastVote(currentVote, epoch, _account, votingPower, totalWeight, voteData);
        }
        voteData.usedVotingPower = votingPower;
        // setting the last voted also has the second-order effect of indicating the user has voted
        voteData.lastVoted = block.timestamp;
    }
    function _safeCastVote(
        GaugeVote memory _currentVote,
        uint256 _epoch,
        address _account,
        uint256 _votingPower,
        uint256 _totalWeights,
        AddressVoteData storage _voteData
    ) internal returns (uint256) {
        // the gauge must exist and be active,
        // it also can't have any votes or we haven't reset properly
        if (!gaugeExists(_currentVote.gauge)) revert GaugeDoesNotExist(_currentVote.gauge);
        if (!isActive(_currentVote.gauge)) revert GaugeInactive(_currentVote.gauge);
        // prevent double voting
        if (_voteData.voteWeights[_currentVote.gauge] != 0) revert DoubleVote();
        // calculate the weight for this gauge
        // No votes can happen with extreme weight discrepancies and/or small
        // voting power, in which case caller should adjust weights accordingly
        uint256 normWeight = _normalizedWeight(_currentVote.weight, _totalWeights);
        if (normWeight == 0) revert NoVotes();
        return _castVote(_currentVote.gauge, _epoch, _account, _votingPower, normWeight, _voteData);
    }
    /// @notice Cast the vote of an tokenId to a specific gauge
    /// @dev This function doesn't do any safety checks and it's up to caller to do validations.
    ///      If you wish to have validations, see `_safeCastVote`.
    /// @dev _voteWeight must be normalized to 1e36 precision.
    function _castVote(
        address _gauge,
        uint256 _epoch,
        address _account,
        uint256 _votingPower,
        uint256 _voteWeight,
        AddressVoteData storage _voteData
    ) internal returns (uint256) {
        uint256 _votes = _votesForGauge(_voteWeight, _votingPower);
        // record the vote for the token
        _voteData.gaugesVotedFor.push(_gauge);
        _voteData.voteWeights[_gauge] += _voteWeight;
        // update the total weights accruing to this gauge
        epochGaugeVotes[_epoch][_gauge] += _votes;
        epochTotalVotingPowerCast[_epoch] += _votes;
        emit Voted({
            voter: _account,
            gauge: _gauge,
            epoch: epochId(),
            votingPowerCastForGauge: _votes,
            totalVotingPowerInGauge: epochGaugeVotes[_epoch][_gauge],
            totalVotingPowerInContract: epochTotalVotingPowerCast[_epoch],
            timestamp: block.timestamp
        });
        return _votes;
    }
    function reset() external nonReentrant whenNotPaused whenVotingActive {
        if (!isVoting(msg.sender)) revert NotCurrentlyVoting();
        _reset(msg.sender);
    }
    function _reset(address _account) internal {
        uint256 epoch = getWriteEpochId();
        AddressVoteData storage voteData = epochVoteData[epoch][_account];
        address[] storage pastVotes = voteData.gaugesVotedFor;
        // iterate over all the gauges voted for and reset the votes
        for (uint256 i = 0; i < pastVotes.length; i++) {
            address gauge = pastVotes[i];
            uint256 _voteWeight = voteData.voteWeights[gauge];
            uint256 _votes = _votesForGauge(_voteWeight, voteData.usedVotingPower);
            // remove from the total globals
            epochGaugeVotes[epoch][gauge] -= _votes;
            epochTotalVotingPowerCast[epoch] -= _votes;
            delete voteData.voteWeights[gauge];
            emit Reset({
                voter: _account,
                gauge: gauge,
                epoch: epochId(),
                votingPowerRemovedFromGauge: _votes,
                totalVotingPowerInGauge: epochGaugeVotes[epoch][gauge],
                totalVotingPowerInContract: epochTotalVotingPowerCast[epoch],
                timestamp: block.timestamp
            });
        }
        // reset the global state variables we don't need
        voteData.usedVotingPower = 0;
        voteData.lastVoted = 0;
        voteData.gaugesVotedFor = new address[](0);
    }
    function _updateVotingPower(address _account) internal {
        if (!enableUpdateVotingPowerHook) revert UpdateVotingPowerHookNotEnabled();
        // Skip as `_account` hasn't voted so no need to update it.
        if (!isVoting(_account)) return;
        uint256 epoch = getWriteEpochId();
        AddressVoteData storage voteData = epochVoteData[epoch][_account];
        // In case no pastVotes exist for an account,
        // skip as there's nothing to update.
        address[] storage pastVotes = voteData.gaugesVotedFor;
        if (pastVotes.length == 0) return;
        uint256 votingPower = IVotes(ivotesAdapter).getVotes(_account);
        // After the voting window closes, votes shouldn't be auto-recast via _updateVotingPower.
        // But if a user loses voting power (e.g., had 100, now 0),
        // gauges must reflect this drop to avoid overstated voting power.
        // If a user's voting power increases (e.g., 100 → 150),
        // we *don't* auto-recast—doing so would inflate gauge power post-window.
        // So: decrease → auto-adjust gauges; increase → ignored
        // unless user manually votes when window reopens.
        if (voteData.usedVotingPower < votingPower) return;
        GaugeVote[] memory newVoteData = new GaugeVote[](pastVotes.length);
        // cast new votes again.
        for (uint256 i = 0; i < pastVotes.length; i++) {
            address gauge = pastVotes[i];
            uint256 _votes = voteData.voteWeights[gauge];
            newVoteData[i] = GaugeVote(_votes, gauge);
        }
        // Note that even if votingPower is 0, this still records.
        uint256 totalWeight = _getTotalWeight(newVoteData);
        // Reset all votes of `_account` to zero.
        _reset(_account);
        // Re-cast the votes with the new voting power.
        for (uint256 i = 0; i < newVoteData.length; i++) {
            _castVote(
                newVoteData[i].gauge,
                epoch,
                _account,
                votingPower,
                _normalizedWeight(newVoteData[i].weight, totalWeight),
                voteData
            );
        }
        voteData.usedVotingPower = votingPower;
        voteData.lastVoted = block.timestamp;
    }
    function updateVotingPower(address _from, address _to) external onlyEscrow {
        // update the voting power of the sender
        _updateVotingPower(_from);
        // This means that account's delegate is itself,
        // so it's enough to only update votes once.
        if (_from == _to) return;
        // update the voting power of the receiver
        _updateVotingPower(_to);
    }
    function _getTotalWeight(GaugeVote[] memory _votes) internal view virtual returns (uint256) {
        uint256 total = 0;
        for (uint256 i = 0; i < _votes.length; i++) {
            total += _votes[i].weight;
        }
        return total;
    }
    /// @dev Scales weights as percentage of total weight and then to 1e36 precision
    function _normalizedWeight(uint256 _weight, uint256 _totalWeight) internal view virtual returns (uint256) {
        return (_weight * 1e36) / _totalWeight;
    }
    /// @dev Calculates the votes for a gauge based on weight and voting power.
    ///      We assume the weight is already normalized to 1e36 precision.
    function _votesForGauge(uint256 _weight, uint256 _votingPower) internal view virtual returns (uint256) {
        return (_weight * _votingPower) / 1e36;
    }
    /// @notice This function is used to get the epoch id in the case of delegation mapper
    /// does not exist or the hook is not activated.
    function getWriteEpochId() public view returns (uint256) {
        return enableUpdateVotingPowerHook ? 0 : epochId();
    }
    /*///////////////////////////////////////////////////////////////
                            Gauge Management
    //////////////////////////////////////////////////////////////*/
    function gaugeExists(address _gauge) public view returns (bool) {
        // this doesn't revert if you create multiple gauges at genesis
        // but that's not a practical concern
        return gauges[_gauge].created > 0;
    }
    function isActive(address _gauge) public view returns (bool) {
        return gauges[_gauge].active;
    }
    function createGauge(address _gauge, string calldata _metadataURI) external nonReentrant returns (address gauge) {
        if (_gauge == address(0)) revert ZeroGauge();
        if (gaugeExists(_gauge)) revert GaugeExists();
        gauges[_gauge] = Gauge(true, block.timestamp, _metadataURI);
        gaugeList.push(_gauge);
        emit GaugeCreated(_gauge, msg.sender, _metadataURI);
        return _gauge;
    }
    function deactivateGauge(address _gauge) external auth(GAUGE_ADMIN_ROLE) {
        if (!gaugeExists(_gauge)) revert GaugeDoesNotExist(_gauge);
        if (!isActive(_gauge)) revert GaugeActivationUnchanged();
        gauges[_gauge].active = false;
        emit GaugeDeactivated(_gauge);
    }
    function activateGauge(address _gauge) external auth(GAUGE_ADMIN_ROLE) {
        if (!gaugeExists(_gauge)) revert GaugeDoesNotExist(_gauge);
        if (isActive(_gauge)) revert GaugeActivationUnchanged();
        gauges[_gauge].active = true;
        emit GaugeActivated(_gauge);
    }
    function updateGaugeMetadata(address _gauge, string calldata _metadataURI) external auth(GAUGE_ADMIN_ROLE) {
        if (!gaugeExists(_gauge)) revert GaugeDoesNotExist(_gauge);
        gauges[_gauge].metadataURI = _metadataURI;
        emit GaugeMetadataUpdated(_gauge, _metadataURI);
    }
    /*///////////////////////////////////////////////////////////////
                                Setters
    //////////////////////////////////////////////////////////////*/
    function setEnableUpdateVotingPowerHook(bool _enableUpdateVotingPowerHook) external auth(GAUGE_ADMIN_ROLE) {
        enableUpdateVotingPowerHook = _enableUpdateVotingPowerHook;
    }
    function setIVotesAdapter(address _ivotesAdapter) external {
        ivotesAdapter = _ivotesAdapter;
    }
    /*///////////////////////////////////////////////////////////////
                          Getters: Epochs & Time
    //////////////////////////////////////////////////////////////*/
    /// @notice autogenerated epoch id based on elapsed time
    function epochId() public view returns (uint256) {
        return IClock(clock).currentEpoch();
    }
    /// @notice whether voting is active in the current epoch
    function votingActive() public view returns (bool) {
        return IClock(clock).votingActive();
    }
    /// @notice timestamp of the start of the next epoch
    function currentEpochStart() public view returns (uint256) {
        return IClock(clock).epochStartTs() - IClock(clock).epochDuration();
    }
    /// @notice timestamp of the start of the next epoch
    function epochStart() external view returns (uint256) {
        return IClock(clock).epochStartTs();
    }
    /// @notice timestamp of the start of the next voting period
    function epochVoteStart() external view returns (uint256) {
        return IClock(clock).epochVoteStartTs();
    }
    /// @notice timestamp of the end of the current voting period
    function epochVoteEnd() external view returns (uint256) {
        return IClock(clock).epochVoteEndTs();
    }
    /*///////////////////////////////////////////////////////////////
                            Getters: Mappings
    //////////////////////////////////////////////////////////////*/
    function getGauge(address _gauge) external view returns (Gauge memory) {
        return gauges[_gauge];
    }
    function getAllGauges() external view returns (address[] memory) {
        return gaugeList;
    }
    function isVoting(address _address) public view returns (bool) {
        uint256 epoch = getWriteEpochId();
        return epochVoteData[epoch][_address].lastVoted > 0;
    }
    function votes(address _address, address _gauge) external view returns (uint256) {
        uint256 epoch = getWriteEpochId();
        return _votesForGauge(
            epochVoteData[epoch][_address].voteWeights[_gauge], epochVoteData[epoch][_address].usedVotingPower
        );
    }
    function gaugesVotedFor(address _address) external view returns (address[] memory) {
        uint256 epoch = getWriteEpochId();
        return epochVoteData[epoch][_address].gaugesVotedFor;
    }
    function usedVotingPower(address _address) external view returns (uint256) {
        uint256 epoch = getWriteEpochId();
        return epochVoteData[epoch][_address].usedVotingPower;
    }
    function totalVotingPowerCast() public view returns (uint256) {
        uint256 epoch = getWriteEpochId();
        return epochTotalVotingPowerCast[epoch];
    }
    function gaugeVotes(address _address) public view returns (uint256) {
        uint256 epoch = getWriteEpochId();
        return epochGaugeVotes[epoch][_address];
    }
    /// @dev Consumer's responsibility to ensure that `_epoch` exists.
    function gaugeVotes(uint256 _epoch, address _address) public view returns (uint256) {
        return epochGaugeVotes[_epoch][_address];
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[42] private __gap;
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
// token interfaces
import {
    IERC20Upgradeable as IERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
    IERC20MetadataUpgradeable as IERC20Metadata
} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {IERC721EnumerableMintableBurnable as IERC721EMB} from "@lock/IERC721EMB.sol";
// veGovernance
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IAddressGaugeVoter} from "@voting/IAddressGaugeVoter.sol";
import {
    IEscrowCurveIncreasingV1_2_0 as IEscrowCurve
} from "@curve/IEscrowCurveIncreasing_v1_2_0.sol";
import {IExitQueue} from "@queue/IExitQueue.sol";
import {
    IVotingEscrowIncreasingV1_2_0 as IVotingEscrow,
    IVotingEscrowExiting,
    IMerge,
    ISplit,
    IDelegateMoveVoteCaller
} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
import {IClockV1_2_0 as IClock} from "@clock/IClock_v1_2_0.sol";
// libraries
import {
    SafeERC20Upgradeable as SafeERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {
    SafeCastUpgradeable as SafeCast
} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
// parents
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
    ReentrancyGuardUpgradeable as ReentrancyGuard
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
    PausableUpgradeable as Pausable
} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {
    DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import {
    IDelegateUpdateVotingPower,
    IEscrowIVotesAdapter,
    IDelegateMoveVoteRecipient
} from "../delegation/IEscrowIVotesAdapter.sol";
contract VotingEscrowV1_2_0 is
    IVotingEscrow,
    ReentrancyGuard,
    Pausable,
    DaoAuthorizable,
    UUPSUpgradeable
{
    using SafeERC20 for IERC20;
    using SafeCast for uint256;
    /// @notice Role required to manage the Escrow curve, this typically will be the DAO
    bytes32 public constant ESCROW_ADMIN_ROLE = keccak256("ESCROW_ADMIN");
    /// @notice Role required to pause the contract - can be given to emergency contracts
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER");
    /// @notice Role required to withdraw underlying tokens from the contract
    bytes32 public constant SWEEPER_ROLE = keccak256("SWEEPER");
    /// @dev enables splits without whitelisting
    address public constant SPLIT_WHITELIST_ANY_ADDRESS =
        address(uint160(uint256(keccak256("SPLIT_WHITELIST_ANY_ADDRESS"))));
    /*//////////////////////////////////////////////////////////////
                              NFT Data
    //////////////////////////////////////////////////////////////*/
    /// @notice Decimals of the voting power
    uint8 public constant decimals = 18;
    /// @notice Minimum deposit amount
    uint256 public minDeposit;
    /// @notice Auto-incrementing ID for the most recently created lock, does not decrease on withdrawal
    uint256 public lastLockId;
    /// @notice Total supply of underlying tokens deposited in the contract
    uint256 public totalLocked;
    /// @dev tracks the locked balance of each NFT
    mapping(uint256 => LockedBalance) private _locked;
    /*//////////////////////////////////////////////////////////////
                              Helper Contracts
    //////////////////////////////////////////////////////////////*/
    /// @notice Address of the underying ERC20 token.
    /// @dev Only tokens with 18 decimals and no transfer fees are supported
    address public token;
    /// @notice Address of the gauge voting contract.
    /// @dev We need to ensure votes are not left in this contract before allowing positing changes
    address public voter;
    /// @notice Address of the voting Escrow Curve contract that will calculate the voting power
    address public curve;
    /// @notice Address of the contract that manages exit queue logic for withdrawals
    address public queue;
    /// @notice Address of the clock contract that manages epoch and voting periods
    address public clock;
    /// @notice Address of the NFT contract that is the lock
    address public lockNFT;
    bool private _lockNFTSet;
    /*//////////////////////////////////////////////////////////////
                            ADDED: in 1.2.0
    //////////////////////////////////////////////////////////////*/
    /// @notice Whitelisted contracts that are allowed to split
    mapping(address => bool) public splitWhitelisted;
    /// @notice Updates `to` token's timestamp if merge occurs from a token
    ///         whose creation lock occured in the same timestamp as current tx.
    mapping(uint256 => uint256) internal mergeWithdrawalLock;
    /// @notice Addess of the escrow ivotes adapter where delegations occur.
    address public ivotesAdapter;
    /*//////////////////////////////////////////////////////////////
                              Initialization
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }
    function initialize(
        address _token,
        address _dao,
        address _clock,
        uint256 _initialMinDeposit
    ) external initializer {
        __ReentrancyGuard_init();
        __Pausable_init();
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        if (IERC20Metadata(_token).decimals() != 18) revert MustBe18Decimals();
        token = _token;
        clock = _clock;
        minDeposit = _initialMinDeposit;
        emit MinDepositSet(_initialMinDeposit);
    }
    /// @notice Used to revert if admin tries to change the contract address 2nd time.
    modifier contractAlreadySet(address _contract) {
        if (_contract != address(0)) revert AddressAlreadySet();
        _;
    }
    /*//////////////////////////////////////////////////////////////
                              Admin Setters
    //////////////////////////////////////////////////////////////*/
    /// @notice Added in 1.2.0 to set the ivotes adapter
    function setIVotesAdapter(
        address _ivotesAdapter
    ) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(ivotesAdapter) {
        ivotesAdapter = _ivotesAdapter;
    }
    /// @notice Sets the curve contract that calculates the voting power
    function setCurve(address _curve) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(curve) {
        curve = _curve;
    }
    /// @notice Sets the voter contract that tracks votes
    function setVoter(address _voter) external auth(ESCROW_ADMIN_ROLE) {
        voter = _voter;
    }
    /// @notice Sets the exit queue contract that manages withdrawal eligibility
    function setQueue(address _queue) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(queue) {
        queue = _queue;
    }
    /// @notice Sets the clock contract that manages epoch and voting periods
    function setClock(address _clock) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(clock) {
        clock = _clock;
    }
    /// @notice Sets the NFT contract that is the lock
    /// @dev By default this can only be set once due to the high risk of changing the lock
    /// and having the ability to steal user funds.
    function setLockNFT(address _nft) external auth(ESCROW_ADMIN_ROLE) {
        if (_lockNFTSet) revert LockNFTAlreadySet();
        lockNFT = _nft;
        _lockNFTSet = true;
    }
    function pause() external auth(PAUSER_ROLE) {
        _pause();
    }
    function unpause() external auth(PAUSER_ROLE) {
        _unpause();
    }
    function setMinDeposit(uint256 _minDeposit) external auth(ESCROW_ADMIN_ROLE) {
        minDeposit = _minDeposit;
        emit MinDepositSet(_minDeposit);
    }
    /// @notice Split disabled by default, only whitelisted addresses can split.
    function setEnableSplit(
        address _account,
        bool _isWhitelisted
    ) external auth(ESCROW_ADMIN_ROLE) {
        splitWhitelisted[_account] = _isWhitelisted;
        emit SplitWhitelistSet(_account, _isWhitelisted);
    }
    /// @notice Enable split to any address without whitelisting
    function enableSplit() external auth(ESCROW_ADMIN_ROLE) {
        splitWhitelisted[SPLIT_WHITELIST_ANY_ADDRESS] = true;
        emit SplitWhitelistSet(SPLIT_WHITELIST_ANY_ADDRESS, true);
    }
    /// @notice Return true if any address is whitelisted or an `_account`.
    function canSplit(address _account) public view virtual returns (bool) {
        // Only allow split to whitelisted accounts.
        return splitWhitelisted[SPLIT_WHITELIST_ANY_ADDRESS] || splitWhitelisted[_account];
    }
    /*//////////////////////////////////////////////////////////////
                      Getters: ERC721 Functions
    //////////////////////////////////////////////////////////////*/
    function isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) {
        return IERC721EMB(lockNFT).isApprovedOrOwner(_spender, _tokenId);
    }
    /// @notice Fetch all NFTs owned by an address by leveraging the ERC721Enumerable interface
    /// @param _owner Address to query
    /// @return tokenIds Array of token IDs owned by the address
    function ownedTokens(address _owner) public view returns (uint256[] memory tokenIds) {
        IERC721EMB enumerable = IERC721EMB(lockNFT);
        uint256 balance = enumerable.balanceOf(_owner);
        uint256[] memory tokens = new uint256[](balance);
        for (uint256 i = 0; i < balance; i++) {
            tokens[i] = enumerable.tokenOfOwnerByIndex(_owner, i);
        }
        return tokens;
    }
    /*///////////////////////////////////////////////////////////////
                          Getters: Voting
    //////////////////////////////////////////////////////////////*/
    /// @return The voting power of the NFT at the current block
    function votingPower(uint256 _tokenId) public view returns (uint256) {
        return votingPowerAt(_tokenId, block.timestamp);
    }
    /// @return The voting power of the NFT at a specific timestamp
    function votingPowerAt(uint256 _tokenId, uint256 _t) public view returns (uint256) {
        return IEscrowCurve(curve).votingPowerAt(_tokenId, _t);
    }
    /// @return The total voting power at the current block
    function totalVotingPower() external view returns (uint256) {
        return totalVotingPowerAt(block.timestamp);
    }
    /// @return The total voting power at a specific timestamp
    function totalVotingPowerAt(uint256 _timestamp) public view returns (uint256) {
        return IEscrowCurve(curve).supplyAt(_timestamp);
    }
    /// @return The details of the underlying lock for a given veNFT
    function locked(uint256 _tokenId) public view returns (LockedBalance memory) {
        return _locked[_tokenId];
    }
    /// @return accountVotingPower The voting power of an account at the current block
    /// @dev We cannot do historic voting power at this time because we don't current track
    /// histories of token transfers.
    function votingPowerForAccount(
        address _account
    ) external view returns (uint256 accountVotingPower) {
        uint256[] memory tokens = ownedTokens(_account);
        for (uint256 i = 0; i < tokens.length; i++) {
            accountVotingPower += votingPowerAt(tokens[i], block.timestamp);
        }
    }
    /// @notice Checks if the NFT is currently voting. We require the user to reset their votes if so.
    function isVoting(uint256 _tokenId) public view returns (bool) {
        // If token doesn't exist, it reverts.
        address owner = IERC721EMB(lockNFT).ownerOf(_tokenId);
        // If token is not delegated, delegatee wouldn't exist, so we return false.
        bool isTokenDelegated = IEscrowIVotesAdapter(ivotesAdapter).tokenIsDelegated(_tokenId);
        if (!isTokenDelegated) return false;
        // If token is delegated, it will always have a delegatee.
        address delegatee = IEscrowIVotesAdapter(ivotesAdapter).delegates(owner);
        return IAddressGaugeVoter(voter).isVoting(delegatee);
    }
    /*//////////////////////////////////////////////////////////////
                              ESCROW LOGIC
    //////////////////////////////////////////////////////////////*/
    function createLock(uint256 _value) external nonReentrant whenNotPaused returns (uint256) {
        return _createLockFor(_value, _msgSender());
    }
    /// @notice Creates a lock on behalf of someone else. Restricted by default.
    function createLockFor(
        uint256 _value,
        address _to
    ) external nonReentrant whenNotPaused returns (uint256) {
        return _createLockFor(_value, _to);
    }
    /// @dev Deposit `_value` tokens for `_to` starting at next deposit interval
    /// @param _value Amount to deposit
    /// @param _to Address to deposit
    function _createLockFor(uint256 _value, address _to) internal returns (uint256) {
        if (_value == 0) revert ZeroAmount();
        if (_value < minDeposit) revert AmountTooSmall();
        // query the duration lib to get the next time we can deposit
        uint256 startTime = IClock(clock).epochPrevCheckpointTs();
        // increment the total locked supply and get the new tokenId
        totalLocked += _value;
        uint256 newTokenId = ++lastLockId;
        // write the lock and checkpoint the voting power
        LockedBalance memory lock = LockedBalance(_value.toUint208(), startTime.toUint48());
        _locked[newTokenId] = lock;
        // we don't allow edits in this implementation, so only the new lock is used
        _checkpoint(newTokenId, LockedBalance(0, 0), lock);
        uint256 balanceBefore = IERC20(token).balanceOf(address(this));
        // transfer the tokens into the contract
        IERC20(token).safeTransferFrom(_msgSender(), address(this), _value);
        // we currently don't support tokens that adjust balances on transfer
        if (IERC20(token).balanceOf(address(this)) != balanceBefore + _value)
            revert TransferBalanceIncorrect();
        // Update `_to`'s delegate power.
        _moveDelegateVotes(address(0), _to, newTokenId, lock);
        // mint the NFT before and emit the event to complete the lock
        IERC721EMB(lockNFT).mint(_to, newTokenId);
        emit Deposit(_to, newTokenId, startTime, _value, totalLocked);
        return newTokenId;
    }
    /// @inheritdoc IMerge
    function merge(uint256 _from, uint256 _to) public whenNotPaused {
        address sender = _msgSender();
        if (_from == _to) revert SameNFT();
        address ownerFrom = IERC721EMB(lockNFT).ownerOf(_from);
        address ownerTo = IERC721EMB(lockNFT).ownerOf(_to);
        // Both nfts must have the same owner.
        if (ownerFrom != ownerTo) revert NotSameOwner();
        // sender can either be approved or owner.
        if (!isApprovedOrOwner(sender, _from) || !isApprovedOrOwner(sender, _to)) {
            revert NotApprovedOrOwner();
        }
        LockedBalance memory oldLockedFrom = _locked[_from];
        LockedBalance memory oldLockedTo = _locked[_to];
        if (!canMerge(oldLockedFrom, oldLockedTo)) {
            revert CannotMerge(_from, _to);
        }
        // If `_from` was created in this block, or if another token was merged into `_from` in this block,
        // record the current timestamp for `_to` so that withdrawals for it are blocked in the same block.
        IEscrowCurve.TokenPoint memory point = IEscrowCurve(curve).tokenPointHistory(_from, 1);
        if (point.writtenTs == block.timestamp || mergeWithdrawalLock[_from] == block.timestamp) {
            mergeWithdrawalLock[_to] = block.timestamp;
        }
        // We only allow merge when both tokens have the same owner.
        // After the merge, owner still should have the same voting power
        // as one token gets merged into another. For this reason,
        // We call `_moveDelegateVotes` with empty locked, so it doesn't
        // reduce/increase the same voting power for gas efficiency.
        IEscrowIVotesAdapter(ivotesAdapter).mergeDelegateVotes(
            IDelegateMoveVoteRecipient.TokenLock(ownerFrom, _from, oldLockedFrom),
            IDelegateMoveVoteRecipient.TokenLock(ownerFrom, _to, oldLockedTo)
        );
        // Update for `_from`.
        // Note that on the checkpoint, we still don't
        // remove `start` for historical reasons.
        IERC721EMB(lockNFT).burn(_from);
        _locked[_from] = LockedBalance(0, 0);
        _checkpoint(_from, oldLockedFrom, LockedBalance(0, oldLockedFrom.start));
        // update for `_to`.
        uint208 newLockedAmount = oldLockedFrom.amount + oldLockedTo.amount;
        _checkpoint(_to, oldLockedTo, LockedBalance(newLockedAmount, oldLockedTo.start));
        _locked[_to] = LockedBalance(newLockedAmount, oldLockedTo.start);
        emit Merged(sender, _from, _to, oldLockedFrom.amount, oldLockedTo.amount, newLockedAmount);
    }
    /// @inheritdoc IMerge
    function canMerge(
        LockedBalance memory _fromLocked,
        LockedBalance memory _toLocked
    ) public view returns (bool) {
        uint256 maxTime = IEscrowCurve(curve).maxTime();
        uint256 fromLockedEnd = _fromLocked.start + maxTime;
        uint256 toLockedEnd = _toLocked.start + maxTime;
        // Tokens either must have the same start dates or both must be mature.
        if (
            (_toLocked.start != _fromLocked.start) &&
            (toLockedEnd >= block.timestamp || fromLockedEnd >= block.timestamp)
        ) {
            return false;
        }
        return true;
    }
    /// @inheritdoc ISplit
    function split(uint256 _from, uint256 _value) public whenNotPaused returns (uint256) {
        if (_value == 0) revert ZeroAmount();
        address sender = _msgSender();
        // For some erc721, `ownerOf` reverts and for some,
        // it returns address(0). For safety, if it doesn't revert,
        // we also check if it's not address(0).
        address owner = IERC721EMB(lockNFT).ownerOf(_from);
        if (owner == address(0)) revert NoOwner();
        if (!canSplit(owner)) revert SplitNotWhitelisted();
        // Sender must either be approved or the owner.
        if (!isApprovedOrOwner(sender, _from)) revert NotApprovedOrOwner();
        LockedBalance memory locked_ = _locked[_from];
        if (locked_.amount <= _value) revert SplitAmountTooBig();
        // Ensure that amounts of new tokens will be greater than `minDeposit`.
        uint208 amount1 = locked_.amount - _value.toUint208();
        uint208 amount2 = _value.toUint208();
        if (amount1 < minDeposit || amount2 < minDeposit) {
            revert AmountTooSmall();
        }
        // update for `_from`.
        _checkpoint(_from, locked_, LockedBalance(amount1, locked_.start));
        _locked[_from] = LockedBalance(amount1, locked_.start);
        uint256 newTokenId = ++lastLockId;
        // owner gets minted a new tokenId. Since `split` function
        // just splits the same amount into two tokenIds, there's no need
        // to update voting power on ivotesAdapter, as total doesn't change.
        // We still call `_moveDelegateVotes` with zero LockedBalance to
        // make sure we update delegatee's token count due to newtokenId.
        IEscrowIVotesAdapter(ivotesAdapter).splitDelegateVotes(
            IDelegateMoveVoteRecipient.TokenLock(owner, _from, LockedBalance(0, 0)),
            IDelegateMoveVoteRecipient.TokenLock(owner, newTokenId, LockedBalance(0, 0))
        );
        // update for `newTokenId`.
        locked_.amount = amount2;
        _createSplitNFT(owner, newTokenId, locked_);
        emit Split(_from, newTokenId, sender, amount1, amount2);
        return newTokenId;
    }
    /// @notice creates a new token in checkpoint and mint.
    /// @param _to The address to which new token id will be minted
    /// @param _tokenId The id of the token that will be minted.
    /// @param _newLocked New locked amount / start lock time for the new token
    function _createSplitNFT(
        address _to,
        uint256 _tokenId,
        LockedBalance memory _newLocked
    ) private {
        _locked[_tokenId] = _newLocked;
        _checkpoint(_tokenId, LockedBalance(0, 0), _newLocked);
        IERC721EMB(lockNFT).mint(_to, _tokenId);
    }
    /// @notice Record per-user data to checkpoints. Used by VotingEscrow system.
    /// @param _tokenId NFT token ID.
    /// @dev Old locked balance is unused in the increasing case, at least in this implementation.
    /// @param _fromLocked New locked amount / start lock time for the user
    /// @param _newLocked New locked amount / start lock time for the user
    function _checkpoint(
        uint256 _tokenId,
        LockedBalance memory _fromLocked,
        LockedBalance memory _newLocked
    ) private {
        IEscrowCurve(curve).checkpoint(_tokenId, _fromLocked, _newLocked);
    }
    /*//////////////////////////////////////////////////////////////
                        Exit and Withdraw Logic
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc IVotingEscrowExiting
    function currentExitingAmount() public view returns (uint256 total) {
        IERC721EMB enumerable = IERC721EMB(lockNFT);
        uint256 balance = enumerable.balanceOf(address(this));
        for (uint256 i = 0; i < balance; i++) {
            uint256 tokenId = enumerable.tokenOfOwnerByIndex(address(this), i);
            total += locked(tokenId).amount;
        }
    }
    /// @notice Resets the votes and begins the withdrawal process for a given tokenId
    /// @dev Convenience function, the user must have authorized this contract to act on their behalf.
    ///      For backwards compatibility, even though `reset` call to gauge voter has been removed,
    ///      we still keep the function with the same name.
    function resetVotesAndBeginWithdrawal(uint256 _tokenId) external whenNotPaused {
        beginWithdrawal(_tokenId);
    }
    /// @notice Enters a tokenId into the withdrawal queue by transferring to this contract and creating a ticket.
    /// @param _tokenId The tokenId to begin withdrawal for. Will be transferred to this contract before burning.
    /// @dev The user must not have active votes in the voter contract.
    function beginWithdrawal(uint256 _tokenId) public nonReentrant whenNotPaused {
        // in the event of an increasing curve, 0 voting power means voting isn't active
        if (votingPower(_tokenId) == 0) revert CannotExit();
        // Safety checks:
        // 1. Prevent creating a lock and starting withdrawal in the same block.
        // 2. Prevent withdrawals if another token created in the same block
        //    was merged into `_tokenId`. Even though `_tokenId` itself was
        //    created in a previous block, the merged portion is "fresh" and
        //    would still be withdrawable without restriction.
        IEscrowCurve.TokenPoint memory point = IEscrowCurve(curve).tokenPointHistory(_tokenId, 1);
        if (
            block.timestamp == point.writtenTs || block.timestamp == mergeWithdrawalLock[_tokenId]
        ) {
            revert CannotWithdrawInSameBlock();
        }
        address owner = IERC721EMB(lockNFT).ownerOf(_tokenId);
        // we can remove the user's voting power as it's no longer locked
        LockedBalance memory locked_ = _locked[_tokenId];
        _checkpoint(_tokenId, locked_, LockedBalance(0, locked_.start));
        // transfer NFT to this and queue the exit
        IERC721EMB(lockNFT).transferFrom(_msgSender(), address(this), _tokenId);
        IExitQueue(queue).queueExit(_tokenId, owner);
    }
    /// @notice Allows cancellation of a pending withdrawal request
    /// @dev The caller must be one that also called `beginWithdrawal`.
    /// @param _tokenId The tokenId to cancel the withdrawal request for.
    function cancelWithdrawalRequest(uint256 _tokenId) public nonReentrant whenNotPaused {
        address owner = IExitQueue(queue).ticketHolder(_tokenId);
        address sender = _msgSender();
        if (owner != sender) {
            revert NotTicketHolder();
        }
        _checkpoint(_tokenId, LockedBalance(0, _locked[_tokenId].start), _locked[_tokenId]);
        IExitQueue(queue).cancelExit(_tokenId);
        IERC721EMB(lockNFT).transferFrom(address(this), sender, _tokenId);
    }
    /// @notice Withdraws tokens from the contract
    function withdraw(uint256 _tokenId) external nonReentrant whenNotPaused {
        address sender = _msgSender();
        // we force the sender to be the ticket holder
        if (!(IExitQueue(queue).ticketHolder(_tokenId) == sender)) revert NotTicketHolder();
        // check that this ticket can exit
        if (!(IExitQueue(queue).canExit(_tokenId))) revert CannotExit();
        LockedBalance memory oldLocked = _locked[_tokenId];
        uint256 value = oldLocked.amount;
        // check for fees to be transferred
        // do this before clearing the lock or it will be incorrect
        uint256 fee = IExitQueue(queue).exit(_tokenId);
        if (fee > 0) {
            IERC20(token).safeTransfer(address(queue), fee);
        }
        // clear out the token data
        _locked[_tokenId] = LockedBalance(0, 0);
        totalLocked -= value;
        // Burn the NFT and transfer the tokens to the user
        IERC721EMB(lockNFT).burn(_tokenId);
        IERC20(token).safeTransfer(sender, value - fee);
        emit Withdraw(sender, _tokenId, value - fee, block.timestamp, totalLocked);
    }
    /// @notice withdraw excess tokens from the contract - possibly by accident
    function sweep() external nonReentrant auth(SWEEPER_ROLE) {
        // if there are extra tokens in the contract
        // balance will be greater than the total locked
        uint balance = IERC20(token).balanceOf(address(this));
        uint excess = balance - totalLocked;
        // if there isn't revert the tx
        if (excess == 0) revert NothingToSweep();
        // if there is, send them to the caller
        IERC20(token).safeTransfer(_msgSender(), excess);
        emit Sweep(_msgSender(), excess);
    }
    /// @notice the sweeper can send NFTs mistakenly sent to the contract to a designated address
    /// @param _tokenId the tokenId to sweep - must be currently in this contract
    /// @param _to the address to send the NFT to - must be a whitelisted address for transfers
    /// @dev Cannot sweep NFTs that are in the exit queue for obvious reasons
    function sweepNFT(uint256 _tokenId, address _to) external nonReentrant auth(SWEEPER_ROLE) {
        // if the token id is not in the contract, revert
        if (IERC721EMB(lockNFT).ownerOf(_tokenId) != address(this)) revert NothingToSweep();
        // if the token id is in the queue, we cannot sweep it
        if (IExitQueue(queue).ticketHolder(_tokenId) != address(0)) revert CannotExit();
        IERC721EMB(lockNFT).transferFrom(address(this), _to, _tokenId);
        emit SweepNFT(_to, _tokenId);
    }
    /*//////////////////////////////////////////////////////////////
                        Moving Delegation Votes Logic
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc IDelegateMoveVoteCaller
    function moveDelegateVotes(address _from, address _to, uint256 _tokenId) public whenNotPaused {
        if (msg.sender != lockNFT) revert OnlyLockNFT();
        LockedBalance memory locked_ = _locked[_tokenId];
        _moveDelegateVotes(_from, _to, _tokenId, locked_);
    }
    function _moveDelegateVotes(
        address _from,
        address _to,
        uint256 _tokenId,
        LockedBalance memory _lockedBalance
    ) private {
        IEscrowIVotesAdapter(ivotesAdapter).moveDelegateVotes(_from, _to, _tokenId, _lockedBalance);
    }
    function updateVotingPower(address _from, address _to) public whenNotPaused {
        if (msg.sender != ivotesAdapter) revert OnlyIVotesAdapter();
        IAddressGaugeVoter(voter).updateVotingPower(_from, _to);
    }
    /*///////////////////////////////////////////////////////////////
                            UUPS Upgrade
    //////////////////////////////////////////////////////////////*/
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function _authorizeUpgrade(address) internal virtual override auth(ESCROW_ADMIN_ROLE) {}
    /// @dev Reserved storage space to allow for layout changes in the future.
    ///      Please note that the reserved slot number in previous version(39) was set
    ///      incorrectly as 39 instead of 40. Changing it to 40 now would overwrite existing slot values,
    ///      resulting in the loss of state. Therefore, we will continue using 37 in this version.
    ///      For future versions, any new variables should be added by subtracting from 37.
    uint256[36] private __gap;
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IDynamicExitQueue, IDynamicExitQueueFee} from "./IDynamicExitQueue.sol";
import {
    IERC20Upgradeable as IERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IVotingEscrowIncreasing as IVotingEscrow} from "@escrow/IVotingEscrowIncreasing.sol";
import {IClockUser, IClock} from "@clock/IClock.sol";
import {
    SafeERC20Upgradeable as SafeERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
    DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
/// @title DynamicExitQueue
/// @notice Token IDs associated with an NFT are given a ticket when they are queued for exit.
/// After a cooldown period, the ticket holder can exit the NFT with dynamic fee calculations.
contract DynamicExitQueue is IDynamicExitQueue, IClockUser, DaoAuthorizable, UUPSUpgradeable {
    using SafeERC20 for IERC20;
    /// @notice role required to manage the exit queue
    bytes32 public constant QUEUE_ADMIN_ROLE = keccak256("QUEUE_ADMIN");
    /// @notice role required to withdraw tokens from the escrow contract
    bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE");
    /// @dev 10_000 = 100%
    uint16 private constant MAX_FEE_PERCENT = 10_000;
    /// @dev 1e18 is used for internal precision in fee calculations
    uint256 private constant INTERNAL_PRECISION = 1e18;
    /// @notice the highest fee someone will pay on exit
    uint256 public feePercent;
    /// @notice address of the escrow contract
    address public escrow;
    /// @notice clock contract for epoch duration
    address public clock;
    /// @notice time in seconds between entering queue and exiting on optimal terms
    uint48 public cooldown;
    /// @notice minimum time from the original lock date before one can enter the queue
    uint48 public minLock;
    /// @notice tokenId => TicketV2
    mapping(uint256 => TicketV2) internal _queue;
    /*//////////////////////////////////////////////////////////////
			  Dynamic Fee Params
    //////////////////////////////////////////////////////////////*/
    /// @notice Minimum fee percent charged after full cooldown period
    uint256 public minFeePercent;
    /// @notice Minimum wait time before any exit is possible
    uint48 public minCooldown;
    /// @notice Fee decrease per second (basis points/second) during decay period
    /// @dev Set to 0 when minCooldown == cooldown to prevent division by zero
    uint256 internal _slope;
    /*//////////////////////////////////////////////////////////////
                              Constructor
    //////////////////////////////////////////////////////////////*/
    constructor() {
        _disableInitializers();
    }
    /// @param _escrow address of the escrow contract where tokens are stored
    /// @param _cooldown time in seconds between exit and withdrawal
    /// @param _dao address of the DAO that will be able to set the queue
    function initialize(
        address _escrow,
        uint48 _cooldown,
        address _dao,
        uint256 _feePercent,
        address _clock,
        uint48 _minLock
    ) external initializer {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        escrow = _escrow;
        clock = _clock;
        _setMinLock(_minLock);
        // Initialize with fixed fee system, no early exits
        if (_feePercent > MAX_FEE_PERCENT) revert FeePercentTooHigh(MAX_FEE_PERCENT);
        _setFixedExitFeePercent(_feePercent, _cooldown, false);
    }
    /*//////////////////////////////////////////////////////////////
                              Modifiers
    //////////////////////////////////////////////////////////////*/
    modifier onlyEscrow() {
        if (msg.sender != escrow) revert OnlyEscrow();
        _;
    }
    /*//////////////////////////////////////////////////////////////
			      Admin Functions
    //////////////////////////////////////////////////////////////*/
    /// @notice The exit queue manager can set the minimum lock time
    function setMinLock(uint48 _minLock) external auth(QUEUE_ADMIN_ROLE) {
        _setMinLock(_minLock);
    }
    function _setMinLock(uint48 _minLock) internal {
        if (_minLock == 0) revert MinLockOutOfBounds();
        minLock = _minLock;
        emit MinLockSet(_minLock);
    }
    /// @inheritdoc IDynamicExitQueueFee
    function setDynamicExitFeePercent(
        uint256 _minFeePercent,
        uint256 _maxFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) external auth(QUEUE_ADMIN_ROLE) {
        if (_minFeePercent > MAX_FEE_PERCENT || _maxFeePercent > MAX_FEE_PERCENT) {
            revert FeePercentTooHigh(MAX_FEE_PERCENT);
        }
        if (_maxFeePercent <= _minFeePercent) revert InvalidFeeParameters();
        // setting cooldown == minCooldown would imply a vertical slope
        if (_cooldown <= _minCooldown) revert CooldownTooShort();
        _setDynamicExitFeePercent(_minFeePercent, _maxFeePercent, _cooldown, _minCooldown);
    }
    /// @inheritdoc IDynamicExitQueueFee
    function setTieredExitFeePercent(
        uint256 _baseFeePercent,
        uint256 _earlyFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) external auth(QUEUE_ADMIN_ROLE) {
        if (_baseFeePercent > MAX_FEE_PERCENT || _earlyFeePercent > MAX_FEE_PERCENT) {
            revert FeePercentTooHigh(MAX_FEE_PERCENT);
        }
        if (_earlyFeePercent <= _baseFeePercent) revert InvalidFeeParameters();
        if (_cooldown <= _minCooldown) revert CooldownTooShort();
        _setTieredExitFeePercent(_baseFeePercent, _earlyFeePercent, _cooldown, _minCooldown);
    }
    /// @inheritdoc IDynamicExitQueueFee
    function setFixedExitFeePercent(
        uint256 _feePercent,
        uint48 _cooldown,
        bool _allowEarlyExit
    ) external auth(QUEUE_ADMIN_ROLE) {
        if (_feePercent > MAX_FEE_PERCENT) revert FeePercentTooHigh(MAX_FEE_PERCENT);
        _setFixedExitFeePercent(_feePercent, _cooldown, _allowEarlyExit);
    }
    function _setDynamicExitFeePercent(
        uint256 _minFeePercent,
        uint256 _maxFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) internal {
        feePercent = _maxFeePercent;
        minFeePercent = _minFeePercent;
        cooldown = _cooldown;
        minCooldown = _minCooldown;
        _slope = _computeSlope(_minFeePercent, _maxFeePercent, _cooldown, _minCooldown);
        emit ExitFeePercentAdjusted(
            _maxFeePercent,
            _minFeePercent,
            _minCooldown,
            ExitFeeType.Dynamic
        );
    }
    function _setTieredExitFeePercent(
        uint256 _baseFeePercent,
        uint256 _earlyFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) internal {
        feePercent = _earlyFeePercent;
        minFeePercent = _baseFeePercent;
        cooldown = _cooldown;
        minCooldown = _minCooldown;
        _slope = 0; // No decay in tiered system
        emit ExitFeePercentAdjusted(
            _earlyFeePercent,
            _baseFeePercent,
            _minCooldown,
            ExitFeeType.Tiered
        );
    }
    function _setFixedExitFeePercent(
        uint256 _feePercent,
        uint48 _cooldown,
        bool _allowEarlyExit
    ) internal {
        feePercent = _feePercent;
        minFeePercent = _feePercent;
        cooldown = _cooldown;
        _slope = 0; // No decay in fixed system
        // immediate or none
        if (_allowEarlyExit) minCooldown = 0;
        else minCooldown = _cooldown;
        emit ExitFeePercentAdjusted(_feePercent, _feePercent, minCooldown, ExitFeeType.Fixed);
    }
    /*//////////////////////////////////////////////////////////////
                              SLOPE
    //////////////////////////////////////////////////////////////*/
    function _computeSlope(
        uint256 _minFeePercent,
        uint256 _maxFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) internal pure returns (uint256) {
        // Calculate slope in 1e18 scale for maximum precision
        uint256 scaledMaxFee = (_maxFeePercent * INTERNAL_PRECISION) / MAX_FEE_PERCENT;
        uint256 scaledMinFee = (_minFeePercent * INTERNAL_PRECISION) / MAX_FEE_PERCENT;
        uint256 scaledFeeRange = scaledMaxFee - scaledMinFee;
        uint256 timeRange = _cooldown - _minCooldown;
        return scaledFeeRange / timeRange;
    }
    /*//////////////////////////////////////////////////////////////
                              WITHDRAWER
    //////////////////////////////////////////////////////////////*/
    /// @notice withdraw staked tokens sent as part of fee collection to the caller
    /// @dev The caller must be authorized to withdraw by the DAO
    function withdraw(uint256 _amount) external auth(WITHDRAW_ROLE) {
        IERC20 underlying = IERC20(IVotingEscrow(escrow).token());
        underlying.safeTransfer(msg.sender, _amount);
    }
    /*//////////////////////////////////////////////////////////////
                              Exit Logic
    //////////////////////////////////////////////////////////////*/
    /// @notice queue an exit for a given tokenId, granting the ticket to the passed holder
    /// @param _tokenId the tokenId to queue an exit for
    /// @param _ticketHolder the address that will be granted the ticket
    /// @dev we don't check that the ticket holder is the caller
    /// this is because the escrow contract is the only one that can queue an exit
    /// and we leave that logic to the escrow contract
    function queueExit(uint256 _tokenId, address _ticketHolder) external onlyEscrow {
        if (_ticketHolder == address(0)) revert ZeroAddress();
        if (_queue[_tokenId].holder != address(0)) revert AlreadyQueued();
        // get time to min lock and revert if it hasn't been reached
        uint48 minLockTime = timeToMinLock(_tokenId);
        if (minLockTime > block.timestamp) {
            revert MinLockNotReached(_tokenId, minLock, minLockTime);
        }
        uint48 queuedAt = uint48(block.timestamp);
        _queue[_tokenId] = TicketV2(_ticketHolder, queuedAt);
        emit ExitQueuedV2(_tokenId, _ticketHolder, queuedAt);
    }
    /// @notice Exits the queue for that tokenID.
    /// @dev The holder is not checked. This is left up to the escrow contract to manage.
    function exit(uint256 _tokenId) external onlyEscrow returns (uint256 fee) {
        if (!canExit(_tokenId)) revert CannotExit();
        // calculate fee before resetting ticket
        fee = calculateFee(_tokenId);
        // reset the ticket for that tokenId
        _queue[_tokenId] = TicketV2(address(0), 0);
        emit Exit(_tokenId, fee);
    }
    /// @notice Cancels the exit.
    /// @dev The token must have a holder.
    function cancelExit(uint256 _tokenId) external onlyEscrow {
        TicketV2 memory ticket = _queue[_tokenId];
        // This should never occur as escrow already checks this
        // but for safety, still advisable to have this check.
        if (ticket.holder == address(0)) {
            revert CannotCancelExit();
        }
        _queue[_tokenId] = TicketV2(address(0), 0);
        emit ExitCancelled(_tokenId, ticket.holder);
    }
    /// @notice Calculate the absolute fee amount for exiting a specific token
    /// @param _tokenId The token ID to calculate fee for
    /// @return Fee amount in underlying token units
    function calculateFee(uint256 _tokenId) public view returns (uint256) {
        TicketV2 memory ticket = _queue[_tokenId];
        if (ticket.holder == address(0)) return 0;
        uint256 underlyingBalance = IVotingEscrow(escrow).locked(_tokenId).amount;
        if (underlyingBalance == 0) revert NoLockBalance();
        uint256 timeElapsed = block.timestamp - ticket.queuedAt;
        uint256 scaledFeePercent = _getScaledTimeBasedFee(timeElapsed);
        return (underlyingBalance * scaledFeePercent) / INTERNAL_PRECISION;
    }
    /// @notice Internal function to get time-based fee in 1e18 scale
    /// @param timeElapsed Time elapsed since ticket was queued
    /// @return Fee percent in 1e18 scale (0 = 0%, 1e18 = 100%)
    function _getScaledTimeBasedFee(uint256 timeElapsed) internal view returns (uint256) {
        uint256 scaledMaxFee = (feePercent * INTERNAL_PRECISION) / MAX_FEE_PERCENT;
        uint256 scaledMinFee = (minFeePercent * INTERNAL_PRECISION) / MAX_FEE_PERCENT;
        // Fixed fee system (no decay, no tiers)
        if (minFeePercent == feePercent) return scaledMaxFee;
        // Tiered system (no slope) or fixed system
        if (_slope == 0) {
            return timeElapsed <= cooldown ? scaledMaxFee : scaledMinFee;
        }
        // Dynamic system (linear decay using stored slope)
        if (timeElapsed <= minCooldown) return scaledMaxFee;
        if (timeElapsed >= cooldown) return scaledMinFee;
        // Calculate fee reduction using high-precision slope
        uint256 timeInDecay = timeElapsed - minCooldown;
        uint256 feeReduction = _slope * timeInDecay;
        // Ensure we don't go below minimum fee
        if (feeReduction >= (scaledMaxFee - scaledMinFee)) {
            return scaledMinFee;
        }
        return scaledMaxFee - feeReduction;
    }
    /// @notice Calculate the exit fee percent for a given time elapsed
    /// @param timeElapsed Time elapsed since ticket was queued
    /// @return Fee percent in basis points
    function getTimeBasedFee(uint256 timeElapsed) public view returns (uint256) {
        uint256 scaledFee = _getScaledTimeBasedFee(timeElapsed);
        return (scaledFee * MAX_FEE_PERCENT) / INTERNAL_PRECISION;
    }
    /*//////////////////////////////////////////////////////////////
                              View Functions
    //////////////////////////////////////////////////////////////*/
    /// @notice Check if a token has completed its full cooldown period (minimum fee applies)
    /// @param _tokenId The token ID to check
    /// @return True if full cooldown elapsed, false otherwise
    function isCool(uint256 _tokenId) public view returns (bool) {
        TicketV2 memory ticket = _queue[_tokenId];
        if (ticket.holder == address(0)) return false;
        return block.timestamp - ticket.queuedAt >= cooldown;
    }
    /// @return true if the tokenId corresponds to a valid ticket and the minimum cooldown period has passed
    function canExit(uint256 _tokenId) public view returns (bool) {
        TicketV2 memory ticket = _queue[_tokenId];
        if (ticket.holder == address(0)) return false;
        return block.timestamp - ticket.queuedAt >= minCooldown;
    }
    /// @return holder of a ticket for a given tokenId
    function ticketHolder(uint256 _tokenId) external view returns (address) {
        return _queue[_tokenId].holder;
    }
    function queue(uint256 _tokenId) external view override returns (TicketV2 memory) {
        return _queue[_tokenId];
    }
    function timeToMinLock(uint256 _tokenId) public view returns (uint48) {
        uint48 lockStart = IVotingEscrow(escrow).locked(_tokenId).start;
        return lockStart + minLock;
    }
    /*///////////////////////////////////////////////////////////////
                            UUPS Upgrade
    //////////////////////////////////////////////////////////////*/
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function _authorizeUpgrade(address) internal virtual override auth(QUEUE_ADMIN_ROLE) {}
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[42] private __gap; // Reduced to account for new state variables
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
// interfaces
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IVotingEscrowIncreasingV1_2_0 as IVotingEscrow} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
import {
    IEscrowCurveIncreasingV1_2_0 as IEscrowCurve,
    IEscrowCurveGlobal,
    IEscrowCurveCore,
    IEscrowCurveTokenV1_2_0 as IEscrowCurveToken
} from "@curve/IEscrowCurveIncreasing_v1_2_0.sol";
import {IClockUser, IClockV1_2_0 as IClock} from "@clock/IClock_v1_2_0.sol";
// libraries
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SignedFixedPointMath} from "@libs/SignedFixedPointMathLib.sol";
import {CurveConstantLib} from "@libs/CurveConstantLib.sol";
// contracts
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable as ReentrancyGuard} from
    "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {DaoAuthorizableUpgradeable as DaoAuthorizable} from
    "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
/// @title Linear Increasing Escrow Curve
contract LinearIncreasingCurve is IEscrowCurve, IClockUser, ReentrancyGuard, DaoAuthorizable, UUPSUpgradeable {
    using SafeERC20 for IERC20;
    using SafeCast for int256;
    using SafeCast for uint256;
    using SignedFixedPointMath for int256;
    /// @notice Administrator role for the contract
    bytes32 public constant CURVE_ADMIN_ROLE = keccak256("CURVE_ADMIN_ROLE");
    /// @notice The VotingEscrow contract address
    address public escrow;
    /// @notice The Clock contract address
    address public clock;
    /// @notice tokenId => latest index: incremented on a per-tokenId basis
    /// @custom:oz-renamed-from tokenPointIntervals
    mapping(uint256 => uint256) public tokenPointLatestIndex;
    /// @notice The warmup period for the curve
    /// @dev Deprecated in this version, but kept for backwards compatibility.
    uint48 public warmupPeriod;
    /// @dev tokenId => tokenPointIntervals => TokenPoint
    /// @dev The Array is fixed so we can write to it in the future
    /// This implementation means that very short intervals may be challenging
    mapping(uint256 => TokenPoint[1_000_000_000]) internal _tokenPointHistory;
    /*//////////////////////////////////////////////////////////////
                                MATH
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 private immutable SHARED_QUADRATIC_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 private immutable SHARED_LINEAR_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 private immutable SHARED_CONSTANT_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    uint256 private immutable MAX_EPOCHS;
    /*//////////////////////////////////////////////////////////////
                            ADDED: TOTAL SUPPLY(1.2.0)
    //////////////////////////////////////////////////////////////*/
    /// @dev The latest global point index.
    uint256 public globalPointLatestIndex;
    // endTime => summed up slopes at that endTime
    mapping(uint256 => int256) public slopeChanges;
    /// @dev The global point history
    mapping(uint256 => GlobalPoint) internal _globalPointHistory;
    /*//////////////////////////////////////////////////////////////
                              INITIALIZATION
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(int256[3] memory _coefficients, uint256 _maxEpochs) {
        SHARED_CONSTANT_COEFFICIENT = _coefficients[0];
        SHARED_LINEAR_COEFFICIENT = _coefficients[1];
        SHARED_QUADRATIC_COEFFICIENT = _coefficients[2];
        MAX_EPOCHS = _maxEpochs;
        _disableInitializers();
    }
    /// @param _escrow VotingEscrow contract address
    function initialize(address _escrow, address _dao, address _clock) external initializer {
        escrow = _escrow;
        clock = _clock;
        __ReentrancyGuard_init();
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        // other initializers are empty
    }
    /*//////////////////////////////////////////////////////////////
                              CURVE COEFFICIENTS
    //////////////////////////////////////////////////////////////*/
    /// @return The coefficient for the curve's linear term, for the given amount
    function _getLinearCoeff(uint256 amount) internal view virtual returns (int256) {
        return amount.toInt256() * SHARED_LINEAR_COEFFICIENT;
    }
    /// @return The constant coefficient of the increasing curve, for the given amount
    /// @dev In this case, the constant term is 1 so we just case the amount
    function _getConstantCoeff(uint256 amount) internal view virtual returns (int256) {
        return amount.toInt256() * SHARED_CONSTANT_COEFFICIENT;
    }
    /// @return The coefficients of the quadratic curve, for the given amount
    /// @dev The coefficients are returned in the order [constant, linear, quadratic]
    function _getCoefficients(uint256 amount) internal view virtual returns (int256[3] memory) {
        return [_getConstantCoeff(amount), _getLinearCoeff(amount), 0];
    }
    /// @return The coefficients of the quadratic curve, for the given amount
    /// @dev The coefficients are returned in the order [constant, linear, quadratic]
    /// and are converted to regular 256-bit signed integers instead of their fixed-point representation
    function getCoefficients(uint256 amount) public view virtual returns (int256[3] memory) {
        int256[3] memory coefficients = _getCoefficients(amount);
        return [
            coefficients[0] / 1e18, // amount
            coefficients[1] / 1e18, // slope
            0
        ];
    }
    /*//////////////////////////////////////////////////////////////
                              CURVE BIAS
    //////////////////////////////////////////////////////////////*/
    /// @notice Rounds `_elapsed` to maxTime if it's greater, otherwise returns `_elapsed`.
    function boundElapsedMaxTime(uint256 _elapsed) private view returns (uint256) {
        uint256 MAX_TIME = maxTime();
        return _elapsed > MAX_TIME ? MAX_TIME : _elapsed;
    }
    /// @notice Returns the bias for the given time elapsed and amount, up to the maximum time
    function getBias(uint256 timeElapsed, uint256 amount) public view returns (uint256) {
        int256[3] memory coefficients = _getCoefficients(amount);
        uint256 bias = _getBias(boundElapsedMaxTime(timeElapsed), coefficients[0], coefficients[1]);
        return bias / 1e18;
    }
    /// @notice Returns the bias for the given time elapsed and amount, up to the maximum time
    /// @dev Returned values from these functions are in fixed point representation
    ///    which is not the case in `getBias`.
    function _getBias(uint256 _timeElapsed, int256 _constantCoeff, int256 _linearCoeff)
        internal
        pure
        returns (uint256)
    {
        int256 bias = _linearCoeff * int256(_timeElapsed) + _constantCoeff;
        if (bias < 0) bias = 0;
        return bias.toUint256();
    }
    function _getBiasAndSlope(uint256 _timeElapsed, uint256 _amount) public view returns (int256, int256) {
        int256 slope = _getLinearCoeff(_amount);
        uint256 bias = _getBias(boundElapsedMaxTime(_timeElapsed), _getConstantCoeff(_amount), slope);
        return (int256(bias), slope);
    }
    function maxTime() public view virtual returns (uint256) {
        return IClock(clock).epochDuration() * MAX_EPOCHS;
    }
    function previewMaxBias(uint256 amount) external view returns (uint256) {
        return getBias(maxTime(), amount);
    }
    /*//////////////////////////////////////////////////////////////
                              BALANCE
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc IEscrowCurveToken
    function tokenPointHistory(uint256 _tokenId, uint256 _index) external view returns (TokenPoint memory point) {
        point = _tokenPointHistory[_tokenId][_index];
        /// bind for backwards compatibility
        point.bias = uint256(point.coefficients[0]) / 1e18;
    }
    /// @inheritdoc IEscrowCurveGlobal
    function globalPointHistory(uint256 _index) public view returns (GlobalPoint memory) {
        return _globalPointHistory[_index];
    }
    /// @inheritdoc IEscrowCurveToken
    function tokenPointIntervals(uint256 _tokenId) external view returns (uint256) {
        return tokenPointLatestIndex[_tokenId];
    }
    /// @inheritdoc IEscrowCurveCore
    function votingPowerAt(uint256 _tokenId, uint256 _t) external view returns (uint256) {
        uint256 interval = _getPastTokenPointInterval(_tokenId, _t);
        // epoch 0 is an empty point
        if (interval == 0) return 0;
        // Note that very first point is saved at index 1.
        // Grab original point(the very first point for `_tokenId`).
        TokenPoint memory originalPoint = _tokenPointHistory[_tokenId][1];
        // Grab last point before `_t`.
        TokenPoint memory lastPoint = _tokenPointHistory[_tokenId][interval];
        int256 bias = lastPoint.coefficients[0];
        int256 slope = lastPoint.coefficients[1];
        uint256 end = originalPoint.checkpointTs + maxTime();
        // If the point was created before the upgrade:
        //    it will have `checkpointTs` greater than `writtenTs`.
        //    bias would have been stored as just the amount(without bonus).
        // In such case, we make writtenTs equal to avoid checkpointTs greater.
        // This ensures that behaviour after and before upgrade are same.
        if (lastPoint.checkpointTs > lastPoint.writtenTs) {
            lastPoint.writtenTs = lastPoint.checkpointTs;
            if (_t < lastPoint.writtenTs) return 0;
        }
        uint256 elapsed = _t - lastPoint.writtenTs;
        uint256 timeTillMaxTime = 0;
        if (end > lastPoint.writtenTs) {
            timeTillMaxTime = end - lastPoint.writtenTs;
        }
        if (elapsed >= timeTillMaxTime) {
            elapsed = timeTillMaxTime;
        }
        return _getBias(elapsed, bias, slope) / 1e18;
    }
    /// @inheritdoc IEscrowCurveCore
    function supplyAt(uint256 _timestamp) external view returns (uint256) {
        return _supplyAt(_timestamp);
    }
    /*//////////////////////////////////////////////////////////////
                              CHECKPOINT
    //////////////////////////////////////////////////////////////*/
    /// @notice A checkpoint can be called by the VotingEscrow contract to snapshot the user's voting power
    function checkpoint(
        uint256 _tokenId,
        IVotingEscrow.LockedBalance memory _oldLocked,
        IVotingEscrow.LockedBalance memory _newLocked
    ) external nonReentrant {
        if (msg.sender != escrow) revert OnlyEscrow();
        _checkpoint(_tokenId, _oldLocked, _newLocked);
    }
    /// @notice Record user data to checkpoints. Used by VotingEscrow system.
    /// @param _tokenId NFT token ID.
    /// @param _fromLocked The locked from which we're moving.
    /// @param _newLocked New locked amount / end lock time for the user
    function _checkpoint(
        uint256 _tokenId,
        IVotingEscrow.LockedBalance memory _fromLocked,
        IVotingEscrow.LockedBalance memory _newLocked
    ) internal {
        // this implementation doesn't yet support manual checkpointing
        if (_tokenId == 0) revert InvalidTokenId();
        if (_newLocked.start < _fromLocked.start) {
            revert InvalidCheckpoint();
        }
        uint256 _globalPointLatestIndex = globalPointLatestIndex;
        // Get the slope and bias for `_newLocked`...
        (int256 newLockBias, int256 newLockSlope) =
            _getBiasAndSlope(block.timestamp - _newLocked.start, _newLocked.amount);
        GlobalPoint memory lastPoint = GlobalPoint({bias: 0, slope: 0, writtenTs: uint48(block.timestamp)});
        if (_globalPointLatestIndex > 0) {
            lastPoint = _globalPointHistory[_globalPointLatestIndex];
        }
        {
            uint256 checkpointInterval = IClock(clock).checkpointInterval();
            // For safety reasons, we don't allow checkpoints
            // on the exact checkpointInterval.
            if (block.timestamp % checkpointInterval == 0) {
                revert CheckpointOnDepositIntervalNotAllowed();
            }
            uint256 lastPointCheckpoint = lastPoint.writtenTs;
            uint256 t_i = (lastPointCheckpoint / checkpointInterval) * checkpointInterval;
            for (uint256 i = 0; i < 255; ++i) {
                t_i += checkpointInterval;
                int256 dSlope;
                if (t_i > block.timestamp) {
                    t_i = block.timestamp;
                } else {
                    dSlope = slopeChanges[t_i];
                }
                lastPoint.bias += lastPoint.slope * int256(t_i - lastPointCheckpoint);
                lastPoint.slope -= dSlope;
                if (lastPoint.slope < 0) lastPoint.slope = 0;
                if (lastPoint.bias < 0) lastPoint.bias = 0;
                lastPointCheckpoint = t_i;
                lastPoint.writtenTs = uint48(t_i);
                _globalPointLatestIndex += 1;
                if (t_i == block.timestamp) {
                    break;
                } else {
                    _globalPointHistory[_globalPointLatestIndex] = lastPoint;
                }
            }
        }
        uint256 _maxTime = maxTime();
        uint256 newLockedEnd = _newLocked.start + _maxTime;
        uint256 fromLockedEnd = _fromLocked.start + _maxTime;
        // The following condition is true if merging non-mature locks with different start dates.
        // current version of ve-governance is built around the assumption that merge can only
        // occur if tokens are either mature or have the same start dates. Even though `escrow`
        // does this check before calling `checkpoint` on curve, it's still a safety measure to repeat
        // the check in case the code of checkpoint might be called by another contract in the future.
        if (
            _fromLocked.start != 0 && _newLocked.start != 0 && _fromLocked.start != _newLocked.start
                && (newLockedEnd >= block.timestamp || fromLockedEnd >= block.timestamp)
        ) {
            revert InvalidLocks(_tokenId, _fromLocked, _newLocked);
        }
        // newLocked could be ended in case of merge, when
        // a token is already mature.
        if (newLockedEnd <= block.timestamp) {
            newLockSlope = 0;
        }
        (int256 oldLockBias, int256 oldLockSlope) = (0, 0);
        if (_fromLocked.amount > 0) {
            (oldLockBias, oldLockSlope) = _getBiasAndSlope(block.timestamp - _fromLocked.start, _fromLocked.amount);
            // In case fromLocked already ended, its slope would already
            // be subtracted from `lastPoint.slope` in the above for loop.
            // So we make this 0 to not subtract double times.
            if (fromLockedEnd <= block.timestamp) {
                oldLockSlope = 0;
            }
        }
        lastPoint.bias += (newLockBias - oldLockBias);
        lastPoint.slope += (newLockSlope - oldLockSlope);
        if (lastPoint.slope < 0) lastPoint.slope = 0;
        if (lastPoint.bias < 0) lastPoint.bias = 0;
        uint256 tokenLatestIndex = tokenPointLatestIndex[_tokenId];
        // The token point already exists..
        if (tokenLatestIndex > 0) {
            if (fromLockedEnd > block.timestamp) {
                slopeChanges[fromLockedEnd] -= oldLockSlope;
            }
        }
        // store new slope change
        slopeChanges[newLockedEnd] += newLockSlope;
        // Record the latest global point.
        _storeLatestGlobalPoint(lastPoint, _globalPointLatestIndex);
        // Create new token point and store.
        TokenPoint memory tNew;
        tNew.writtenTs = uint128(block.timestamp);
        tNew.checkpointTs = _newLocked.start;
        tNew.coefficients = [newLockBias, newLockSlope, 0];
        // Record the latest token point.
        _storeLatestTokenPoint(tNew, _tokenId, tokenLatestIndex);
    }
    /// @dev The private helper function to either store latest global point on a new index or overwrite it.
    ///      In case of overwriting, the latest global point index is not incremented.
    function _storeLatestGlobalPoint(GlobalPoint memory _p, uint256 _index) private {
        // If the timestamp of last stored global point is the same as
        // current timestamp, overwrite it, otherwise store a new one
        // to reduce unnecessary global points in the history for
        // gas costs and binary search efficiency.
        if (_index != 1 && _globalPointHistory[_index - 1].writtenTs == block.timestamp) {
            _globalPointHistory[_index - 1] = _p;
        } else {
            globalPointLatestIndex = _index;
            _globalPointHistory[_index] = _p;
        }
    }
    /// @dev The private helper function to either store latest token point on a new index or overwrite it.
    ///      In case of overwriting, the latest token point index is not incremented.
    function _storeLatestTokenPoint(TokenPoint memory _p, uint256 _tokenId, uint256 _index) private {
        // If the timestamp of last stored token point is the same as
        // current timestamp, overwrite it, otherwise store a new one
        // to reduce unnecessary global points in the history for
        // gas costs and binary search efficiency.
        if (_index != 0 && _tokenPointHistory[_tokenId][_index].writtenTs == block.timestamp) {
            _tokenPointHistory[_tokenId][_index] = _p;
        } else {
            tokenPointLatestIndex[_tokenId] = ++_index;
            _tokenPointHistory[_tokenId][_index] = _p;
        }
    }
    /*///////////////////////////////////////////////////////////////
            Total Supply and Voting Power Calculations
    //////////////////////////////////////////////////////////////*/
    /// @notice Binary search to get the token point interval for a token id at or prior to a given timestamp
    /// Once we have the point , we can apply the bias calculation to get the voting power.
    /// @dev If a token point does not exist prior to the timestamp, this will return 0.
    function _getPastTokenPointInterval(uint256 _tokenId, uint256 _timestamp) internal view returns (uint256) {
        uint256 tokenInterval = tokenPointLatestIndex[_tokenId];
        if (tokenInterval == 0) return 0;
        // if the most recent point is before the timestamp, return it
        if (_tokenPointHistory[_tokenId][tokenInterval].writtenTs <= _timestamp) {
            return (tokenInterval);
        }
        // Check if the first balance is after the timestamp
        // this means that the first epoch has yet to start
        if (_tokenPointHistory[_tokenId][1].writtenTs > _timestamp) return 0;
        uint256 lower = 0;
        uint256 upper = tokenInterval;
        while (upper > lower) {
            uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            TokenPoint storage tokenPoint = _tokenPointHistory[_tokenId][center];
            if (tokenPoint.writtenTs == _timestamp) {
                return center;
            } else if (tokenPoint.writtenTs < _timestamp) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return lower;
    }
    /// @notice Binary search to get the global point index at or prior to a given timestamp
    /// @dev If a checkpoint does not exist prior to the timestamp, this will return 0.
    /// @param _timestamp The timestamp to get a checkpoint at.
    /// @return Global point index
    function getPastGlobalPointIndex(uint256 _timestamp) internal view returns (uint256) {
        if (globalPointLatestIndex == 0) return 0;
        // First check most recent balance
        if (_globalPointHistory[globalPointLatestIndex].writtenTs <= _timestamp) {
            return (globalPointLatestIndex);
        }
        // Next check implicit zero balance
        if (_globalPointHistory[1].writtenTs > _timestamp) return 0;
        uint256 lower = 0;
        uint256 upper = globalPointLatestIndex;
        while (upper > lower) {
            uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            GlobalPoint storage globalPoint = _globalPointHistory[center];
            if (globalPoint.writtenTs == _timestamp) {
                return center;
            } else if (globalPoint.writtenTs < _timestamp) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return lower;
    }
    /// @notice Calculate total voting power at some point in the past
    /// @param _timestamp Time to calculate the total voting power at
    /// @return Total voting power at that time
    function _supplyAt(uint256 _timestamp) internal view returns (uint256) {
        uint256 epoch_ = getPastGlobalPointIndex(_timestamp);
        // epoch 0 is an empty point
        if (epoch_ == 0) return 0;
        GlobalPoint memory _point = _globalPointHistory[epoch_];
        int256 bias = _point.bias;
        int256 slope = _point.slope;
        uint256 ts = _point.writtenTs; // changes in for loop.
        uint256 checkpointInterval = IClock(clock).checkpointInterval();
        uint256 t_i = (ts / checkpointInterval) * checkpointInterval;
        for (uint256 i = 0; i < 255; ++i) {
            t_i += checkpointInterval;
            int256 dSlope = 0;
            if (t_i > _timestamp) {
                t_i = _timestamp;
            } else {
                dSlope = slopeChanges[t_i];
            }
            bias += slope * int256(t_i - ts);
            if (t_i == _timestamp) {
                break;
            }
            slope -= dSlope;
            ts = t_i;
        }
        if (bias < 0) bias = 0;
        return uint256(bias / 1e18);
    }
    /*///////////////////////////////////////////////////////////////
                            UUPS Upgrade
    //////////////////////////////////////////////////////////////*/
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function _authorizeUpgrade(address) internal virtual override auth(CURVE_ADMIN_ROLE) {}
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[42] private __gap;
    /*//////////////////////////////////////////////////////////////
                          DEPRECATED: Warmup
    //////////////////////////////////////////////////////////////*/
    function setWarmupPeriod(uint48) external pure {
        revert Deprecated();
    }
    /// @notice Returns whether the NFT is warm
    /// @dev In this version, warm functionality has been deprecated.
    ///      For backwards compatibility, always return true.
    function isWarm(uint256) public pure virtual returns (bool) {
        return true;
    }
    /// @notice Returns whether the NFT is warm at the specified timestamp(`_ts`)
    /// @dev In this version, warm functionality has been deprecated.
    ///      For backwards compatibility, always return true.
    function isWarm(uint256, uint48) public pure virtual returns (bool) {
        return true;
    }
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
// interfaces
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IClock} from "./IClock.sol";
import {IClockV1_2_0} from "./IClock_v1_2_0.sol";
// contracts
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
    DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
/// @title Clock
contract ClockV1_2_0 is IClockV1_2_0, DaoAuthorizable, UUPSUpgradeable {
    bytes32 public constant CLOCK_ADMIN_ROLE = keccak256("CLOCK_ADMIN_ROLE");
    /// @dev Epoch encompasses a voting and non-voting period
    uint256 internal constant EPOCH_DURATION = 2 weeks;
    /// @dev Checkpoint interval is the time between each voting checkpoint
    uint256 internal constant CHECKPOINT_INTERVAL = 1 weeks;
    /// @dev Voting duration is the time during which votes can be cast
    uint256 internal constant VOTE_DURATION = 1 weeks;
    /// @dev Opens and closes the voting window slightly early to avoid timing attacks
    uint256 internal constant VOTE_WINDOW_BUFFER = 1 hours;
    /*///////////////////////////////////////////////////////////////
                            Initialization
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }
    function initialize(address _dao) external initializer {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        // uups not needed
    }
    /*///////////////////////////////////////////////////////////////
                            Getters
    //////////////////////////////////////////////////////////////*/
    function epochDuration() external pure returns (uint256) {
        return EPOCH_DURATION;
    }
    function checkpointInterval() external pure returns (uint256) {
        return CHECKPOINT_INTERVAL;
    }
    function voteDuration() external pure returns (uint256) {
        return VOTE_DURATION;
    }
    function voteWindowBuffer() external pure returns (uint256) {
        return VOTE_WINDOW_BUFFER;
    }
    /*///////////////////////////////////////////////////////////////
                            Epochs
    //////////////////////////////////////////////////////////////*/
    function currentEpoch() external view returns (uint256) {
        return resolveEpoch(block.timestamp);
    }
    function resolveEpoch(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp / EPOCH_DURATION;
        }
    }
    function elapsedInEpoch() external view returns (uint256) {
        return resolveElapsedInEpoch(block.timestamp);
    }
    function resolveElapsedInEpoch(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp % EPOCH_DURATION;
        }
    }
    function epochStartsIn() external view returns (uint256) {
        return resolveEpochStartsIn(block.timestamp);
    }
    /// @notice Number of seconds until the start of the next epoch (relative)
    /// @dev If exactly at the start of the epoch, returns 0
    function resolveEpochStartsIn(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            uint256 elapsed = resolveElapsedInEpoch(timestamp);
            return (elapsed == 0) ? 0 : EPOCH_DURATION - elapsed;
        }
    }
    function epochStartTs() external view returns (uint256) {
        return resolveEpochStartTs(block.timestamp);
    }
    /// @notice Timestamp of the start of the next epoch (absolute)
    function resolveEpochStartTs(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp + resolveEpochStartsIn(timestamp);
        }
    }
    /*///////////////////////////////////////////////////////////////
                              Voting
    //////////////////////////////////////////////////////////////*/
    function votingActive() external view returns (bool) {
        return resolveVotingActive(block.timestamp);
    }
    function resolveVotingActive(uint256 timestamp) public pure returns (bool) {
        bool afterVoteStart = timestamp >= resolveEpochVoteStartTs(timestamp);
        bool beforeVoteEnd = timestamp < resolveEpochVoteEndTs(timestamp);
        return afterVoteStart && beforeVoteEnd;
    }
    function epochVoteStartsIn() external view returns (uint256) {
        return resolveEpochVoteStartsIn(block.timestamp);
    }
    /// @notice Number of seconds until voting starts.
    /// @dev If voting is active, returns 0.
    function resolveEpochVoteStartsIn(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            uint256 elapsed = resolveElapsedInEpoch(timestamp);
            // if less than the offset has past, return the time until the offset
            if (elapsed < VOTE_WINDOW_BUFFER) {
                return VOTE_WINDOW_BUFFER - elapsed;
            }
            // if voting is active (we are in the voting period) return 0
            else if (elapsed < VOTE_DURATION - VOTE_WINDOW_BUFFER) {
                return 0;
            }
            // else return the time until the next epoch + the offset
            else return resolveEpochStartsIn(timestamp) + VOTE_WINDOW_BUFFER;
        }
    }
    function epochVoteStartTs() external view returns (uint256) {
        return resolveEpochVoteStartTs(block.timestamp);
    }
    /// @notice Timestamp of the start of the next voting period (absolute)
    function resolveEpochVoteStartTs(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp + resolveEpochVoteStartsIn(timestamp);
        }
    }
    function epochVoteEndsIn() external view returns (uint256) {
        return resolveEpochVoteEndsIn(block.timestamp);
    }
    /// @notice Number of seconds until the end of the current voting period (relative)
    /// @dev If we are outside the voting period, returns 0
    function resolveEpochVoteEndsIn(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            uint256 elapsed = resolveElapsedInEpoch(timestamp);
            uint VOTING_WINDOW = VOTE_DURATION - VOTE_WINDOW_BUFFER;
            // if we are outside the voting period, return 0
            if (elapsed >= VOTING_WINDOW) return 0;
            // if we are in the voting period, return the remaining time
            else return VOTING_WINDOW - elapsed;
        }
    }
    function epochVoteEndTs() external view returns (uint256) {
        return resolveEpochVoteEndTs(block.timestamp);
    }
    /// @notice Timestamp of the end of the current voting period (absolute)
    function resolveEpochVoteEndTs(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp + resolveEpochVoteEndsIn(timestamp);
        }
    }
    /*///////////////////////////////////////////////////////////////
                            Checkpointing
    //////////////////////////////////////////////////////////////*/
    function epochNextCheckpointIn() external view returns (uint256) {
        return resolveEpochNextCheckpointIn(block.timestamp);
    }
    /// @notice Number of seconds until the next checkpoint interval (relative)
    /// @dev If exactly at the start of the checkpoint interval, returns the interval
    function resolveEpochNextCheckpointIn(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            uint256 elapsed = resolveElapsedInEpoch(timestamp);
            if (elapsed >= CHECKPOINT_INTERVAL) elapsed -= CHECKPOINT_INTERVAL;
            return CHECKPOINT_INTERVAL - elapsed;
        }
    }
    function epochNextCheckpointTs() external view returns (uint256) {
        return resolveEpochNextCheckpointTs(block.timestamp);
    }
    /// @notice Timestamp of the next deposit interval (absolute)
    function resolveEpochNextCheckpointTs(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp + resolveEpochNextCheckpointIn(timestamp);
        }
    }
    function epochPrevCheckpointElapsed() external view returns (uint256) {
        return resolveEpochPrevCheckpointElapsed(block.timestamp);
    }
    /// @notice Number of seconds since the prev checkpoint interval (relative)
    /// @dev If exactly at the start of the checkpoint interval, returns 0
    function resolveEpochPrevCheckpointElapsed(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            uint256 elapsed = resolveElapsedInEpoch(timestamp);
            if (elapsed >= CHECKPOINT_INTERVAL) elapsed -= CHECKPOINT_INTERVAL;
            return elapsed;
        }
    }
    function epochPrevCheckpointTs() external view returns (uint256) {
        return resolveEpochPrevCheckpointTs(block.timestamp);
    }
    /// @notice Timestamp of the prev deposit interval (absolute)
    function resolveEpochPrevCheckpointTs(uint256 timestamp) public pure returns (uint256) {
        unchecked {
            return timestamp - resolveEpochPrevCheckpointElapsed(timestamp);
        }
    }
    /*///////////////////////////////////////////////////////////////
                            UUPS Getters
    //////////////////////////////////////////////////////////////*/
    function _authorizeUpgrade(address) internal override auth(CLOCK_ADMIN_ROLE) {}
    function implementation() external view returns (address) {
        return _getImplementation();
    }
    uint256[50] private __gap;
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {ILock} from "./ILock.sol";
import {
    ERC721EnumerableUpgradeable as ERC721Enumerable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import {
    ReentrancyGuardUpgradeable as ReentrancyGuard
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
    DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {
    IVotingEscrowIncreasingV1_2_0 as IVotingEscrow
} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
/// @title NFT representation of an escrow locking mechanism
contract LockV1_2_0 is ILock, ERC721Enumerable, UUPSUpgradeable, DaoAuthorizable, ReentrancyGuard {
    /// @dev enables transfers without whitelisting
    address public constant WHITELIST_ANY_ADDRESS =
        address(uint160(uint256(keccak256("WHITELIST_ANY_ADDRESS"))));
    /// @notice role to upgrade this contract
    bytes32 public constant LOCK_ADMIN_ROLE = keccak256("LOCK_ADMIN");
    /// @notice Address of the escrow contract that holds underyling assets
    address public escrow;
    /// @notice Whitelisted contracts that are allowed to transfer
    mapping(address => bool) public whitelisted;
    /*//////////////////////////////////////////////////////////////
                              Modifiers
    //////////////////////////////////////////////////////////////*/
    modifier onlyEscrow() {
        if (msg.sender != escrow) revert OnlyEscrow();
        _;
    }
    /*//////////////////////////////////////////////////////////////
                                ERC165
    //////////////////////////////////////////////////////////////*/
    function supportsInterface(
        bytes4 _interfaceId
    ) public view override(ERC721Enumerable) returns (bool) {
        return super.supportsInterface(_interfaceId) || _interfaceId == type(ILock).interfaceId;
    }
    /*//////////////////////////////////////////////////////////////
                              Initializer
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }
    function initialize(
        address _escrow,
        string memory _name,
        string memory _symbol,
        address _dao
    ) external initializer {
        __ERC721_init(_name, _symbol);
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        __ReentrancyGuard_init();
        escrow = _escrow;
        // allow sending nfts to the escrow
        whitelisted[escrow] = true;
        emit WhitelistSet(address(escrow), true);
    }
    /*//////////////////////////////////////////////////////////////
                              Transfers
    //////////////////////////////////////////////////////////////*/
    /// @notice Transfers disabled by default, whitelisted addresses are allowed to be involved in transfers
    function setWhitelisted(address _account, bool _isWhitelisted) external auth(LOCK_ADMIN_ROLE) {
        if (_account == escrow) revert ForbiddenWhitelistAddress();
        whitelisted[_account] = _isWhitelisted;
        emit WhitelistSet(_account, _isWhitelisted);
    }
    /// @notice Enable transfers to any address without whitelisting
    function enableTransfers() external auth(LOCK_ADMIN_ROLE) {
        whitelisted[WHITELIST_ANY_ADDRESS] = true;
        emit WhitelistSet(WHITELIST_ANY_ADDRESS, true);
    }
    /// @dev Override the transfer to check if the recipient is whitelisted
    /// This avoids needing to check for mint/burn but is less idomatic than beforeTokenTransfer
    function _transfer(address _from, address _to, uint256 _tokenId) internal override {
        if (whitelisted[WHITELIST_ANY_ADDRESS] || whitelisted[_to] || whitelisted[_from]) {
            super._transfer(_from, _to, _tokenId);
        } else {
            revert NotWhitelisted();
        }
        
        if(_from != _to) {
            IVotingEscrow(escrow).moveDelegateVotes(_from, _to, _tokenId);
        }
    }
    /*//////////////////////////////////////////////////////////////
                              NFT Functions
    //////////////////////////////////////////////////////////////*/
    function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
        return _isApprovedOrOwner(_spender, _tokenId);
    }
    /// @notice Minting and burning functions that can only be called by the escrow contract
    /// @dev Safe mint ensures contract addresses are ERC721 Receiver contracts
    function mint(address _to, uint256 _tokenId) external onlyEscrow nonReentrant {
        _safeMint(_to, _tokenId);
    }
    /// @notice Minting and burning functions that can only be called by the escrow contract
    function burn(uint256 _tokenId) external onlyEscrow nonReentrant {
        _burn(_tokenId);
    }
    /*//////////////////////////////////////////////////////////////
                              UUPS Upgrade
    //////////////////////////////////////////////////////////////*/
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function _authorizeUpgrade(address) internal virtual override auth(LOCK_ADMIN_ROLE) {}
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[48] private __gap;
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {
    IVotesUpgradeable
} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
import {
    SafeCastUpgradeable
} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import {
    ReentrancyGuardUpgradeable as ReentrancyGuard
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
    PausableUpgradeable as Pausable
} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IERC721EnumerableMintableBurnable as IERC721EMB} from "@lock/IERC721EMB.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {IERC6372} from "@openzeppelin/contracts/interfaces/IERC6372.sol";
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {
    DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import {
    IVotingEscrowIncreasingV1_2_0 as IVotingEscrow
} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
import {VotingEscrowV1_2_0 as VotingEscrow} from "@escrow/VotingEscrowIncreasing_v1_2_0.sol";
import {IClockV1_2_0 as IClock} from "@clock/IClock_v1_2_0.sol";
import {IEscrowIVotesAdapter, IDelegateMoveVoteRecipient} from "./IEscrowIVotesAdapter.sol";
import {CurveConstantLib} from "@libs/CurveConstantLib.sol";
import {SignedFixedPointMath} from "@libs/SignedFixedPointMathLib.sol";
import {DelegationHelper} from "./DelegationHelper.sol";
contract EscrowIVotesAdapter is
    IERC6372,
    ReentrancyGuard,
    Pausable,
    DaoAuthorizable,
    UUPSUpgradeable,
    DelegationHelper
{
    using SafeCastUpgradeable for uint256;
    /// @notice The Gauge admin can can create and manage voting gauges for token holders
    bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256("DELEGATION_ADMIN");
    /// @notice The role used to call `setDelegateAddress` and delegate/undelegate for specific tokens.
    bytes32 public constant DELEGATION_TOKEN_ROLE = keccak256("DELEGATION_TOKEN_ROLE");
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 public immutable SHARED_QUADRATIC_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 public immutable SHARED_LINEAR_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    int256 public immutable SHARED_CONSTANT_COEFFICIENT;
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    uint256 public immutable MAX_EPOCHS;
    
    /// @notice Clock contract for epoch duration
    address public escrowClock;
    mapping(address => mapping(uint256 => int256)) internal slopeChanges;
    mapping(address => mapping(uint256 => GlobalPoint)) public pointHistory;
    mapping(address => address) private delegatees_;
    mapping(address => uint256) public latestPointIndex;
    mapping(address => bool) private autoDelegationDisabled_;
    uint256 private maxTime;
    /*///////////////////////////////////////////////////////////////
                            Initialization
    //////////////////////////////////////////////////////////////*/
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(int256[3] memory _coefficients, uint256 _maxEpochs) {
        SHARED_CONSTANT_COEFFICIENT = _coefficients[0];
        SHARED_LINEAR_COEFFICIENT = _coefficients[1];
        SHARED_QUADRATIC_COEFFICIENT = _coefficients[2];
        MAX_EPOCHS = _maxEpochs;
        _disableInitializers();
    }
    function initialize(
        address _dao,
        address _escrow,
        address _clock,
        bool _startPaused
    ) external initializer {
        __DaoAuthorizableUpgradeable_init(IDAO(_dao));
        __ReentrancyGuard_init();
        __DelegationHelper_init(_escrow);
        escrowClock = _clock;
        if (_startPaused) _pause();
        maxTime = IClock(escrowClock).epochDuration() * MAX_EPOCHS;
    }
    function pause() external auth(DELEGATION_ADMIN_ROLE) {
        _pause();
    }
    function unpause() external auth(DELEGATION_ADMIN_ROLE) {
        _unpause();
    }
    /// @dev Note that by default, auto delegation of tokenIds is turned on.
    function setAutoDelegationDisabled(bool _disabled) external {
        address sender = _msgSender();
        autoDelegationDisabled_[sender] = _disabled;
        emit AutoDelegationDisabledSet(sender, _disabled);
    }
    /*//////////////////////////////////////////////////////////////
                        Delegate Functions
    //////////////////////////////////////////////////////////////*/
    /// @param _delegatee The new delegatee address.
    /// @dev Allows to change a delegatee address. This is useful
    ///      for cases when delegator has huge number of tokens in
    ///      which case  `delegate(address)` would go out of gas.
    ///      In rare cases, Caller first has to undelegate all tokens,
    ///      then call this function and then call `delegate(tokenIds)`.
    function setDelegateAddress(
        address _delegatee
    ) public whenNotPaused auth(DELEGATION_TOKEN_ROLE) {
        address sender = _msgSender();
        if (numberOfDelegatedTokens[sender] != 0) {
            revert DelegationNotAllowed();
        }
        address currentDelegatee = delegates(sender);
        delegatees_[sender] = _delegatee;
        emit DelegateChanged(sender, currentDelegatee, _delegatee);
    }
    /// @dev Note that `_tokenIds` must be either owned or approved to sender and tokens must not be delegated yet.
    /// @param _tokenIds The array of token ids that will be delegated to the current delegatee of `sender`.
    function delegate(
        uint256[] memory _tokenIds
    ) public virtual whenNotPaused auth(DELEGATION_TOKEN_ROLE) {
        address sender = _msgSender();
        address delegatee = delegates(sender);
        if (delegatee == address(0)) {
            revert DelegateeNotSet();
        }
        if (_tokenIds.length == 0) {
            revert TokenListEmpty();
        }
        _delegate(sender, delegatee, _tokenIds, true);
    }
    /// @dev Undelegates currently delegated tokens from the current delegatee
    ///      and delegates all owned tokens by the sender to the new delegatee.
    /// @param _delegatee The new delegatee address.
    function delegate(address _delegatee) public virtual whenNotPaused {
        address sender = _msgSender();
        address currentDelegatee = delegates(sender);
        uint256[] memory tokenIds = VotingEscrow(escrow).ownedTokens(sender);
        uint256 ownedTokenLength = tokenIds.length;
        if (currentDelegatee != address(0) && ownedTokenLength != 0) {
            uint256[] memory delegatedTokenIds = getDelegatedTokens(tokenIds);
            if (delegatedTokenIds.length != 0) {
                _undelegate(sender, currentDelegatee, delegatedTokenIds, false);
            }
        }
        delegatees_[sender] = _delegatee;
        if (!autoDelegationDisabled(sender) && _delegatee != address(0) && ownedTokenLength != 0) {
            _delegate(sender, _delegatee, tokenIds, false);
        }
        emit DelegateChanged(sender, currentDelegatee, _delegatee);
    }
    /// @dev Note that the token ids must be currently delegated and must be owned/approved to the sender.
    /// @param _tokenIds The array of token ids that will be undelegated from the current delegatee.
    function undelegate(
        uint256[] memory _tokenIds
    ) public virtual whenNotPaused auth(DELEGATION_TOKEN_ROLE) {
        address sender = _msgSender();
        address delegatee = delegates(sender);
        if (delegatee == address(0)) {
            revert DelegateeNotSet();
        }
        if (_tokenIds.length == 0) {
            revert TokenListEmpty();
        }
        _undelegate(sender, delegatee, _tokenIds, true);
    }
    /// @notice private helper function to delegate token ids to the `_delegatee`.
    /// @dev It updates checkpoints, sets token delegation to true and
    ///      updates voting power on the address gauge voter.
    /// @param _sender The address that owns `_tokenIds` and delegates.
    /// @param _delegatee The new delegatee address to which `_tokenIds` will be delegated.
    /// @param _tokenIds The array of token ids. Note that it's caller's responsibility to not
    ///                  call this function for empty list of `_tokenIds`.
    /// @param _validate The boolean flag of whether to validate that token ids are owned by the `_sender` or not.
    ///                  In some cases, validation is not needed as caller already knows that there's no need.
    function _delegate(
        address _sender,
        address _delegatee,
        uint256[] memory _tokenIds,
        bool _validate
    ) internal virtual {
        (int256 totalBias, int256 totalSlope) = (0, 0);
        for (uint256 i = 0; i < _tokenIds.length; i++) {
            uint256 tokenId = _tokenIds[i];
            if (_validate) {
                if (!IVotingEscrow(escrow).isApprovedOrOwner(_sender, tokenId)) {
                    revert NotApprovedOrOwner();
                }
                if (tokenIsDelegated(tokenId)) {
                    revert TokenAlreadyDelegated(tokenId);
                }
            }
            // Ensure that voting power is greater than 0.
            // This can not be figured out with only `locked` data, as
            // token might exist, but might not be warm.
            if (IVotingEscrow(escrow).votingPower(tokenId) == 0) {
                revert VotingPowerZero(tokenId);
            }
            _setDelegated(tokenId, true);
            IVotingEscrow.LockedBalance memory locked = IVotingEscrow(escrow).locked(tokenId);
            (int256 bias, int256 slope) = _getBiasAndSlope(_delegatee, locked, _positive);
            totalBias += bias;
            totalSlope += slope;
        }
        numberOfDelegatedTokens[_sender] += _tokenIds.length;
        _checkpoint(totalBias, totalSlope, _delegatee);
        IVotingEscrow(escrow).updateVotingPower(_sender, _delegatee);
        emit TokensDelegated(_sender, _delegatee, _tokenIds);
    }
    /// @notice private helper function to undelegate token ids to the `_delegatee`.
    /// @dev It updates checkpoints, sets token delegation to false and
    ///      updates voting power on the address gauge voter.
    /// @param _sender The address that owns `_tokenIds` and undelegates.
    /// @param _delegatee The delegatee address from which `_tokenIds` will be undelegated.
    /// @param _tokenIds The array of token ids. Note that it's caller's responsibility to not
    ///                  call this function for empty list of `_tokenIds`.
    /// @param _validate The boolean flag of whether to validate that token ids are owned by the `_sender` or not.
    ///                  In some cases, validation is not needed as caller already knows that there's no need.
    function _undelegate(
        address _sender,
        address _delegatee,
        uint256[] memory _tokenIds,
        bool _validate
    ) internal virtual {
        (int256 totalBias, int256 totalSlope) = (0, 0);
        for (uint256 i = 0; i < _tokenIds.length; i++) {
            uint256 tokenId = _tokenIds[i];
            if (_validate) {
                if (!IVotingEscrow(escrow).isApprovedOrOwner(_sender, tokenId)) {
                    revert NotApprovedOrOwner();
                }
                if (!tokenIsDelegated(tokenId)) {
                    revert TokenNotDelegated(tokenId);
                }
            }
            _setDelegated(tokenId, false);
            IVotingEscrow.LockedBalance memory locked = IVotingEscrow(escrow).locked(tokenId);
            (int256 bias, int256 slope) = _getBiasAndSlope(_delegatee, locked, _negative);
            totalBias += bias;
            totalSlope += slope;
        }
        numberOfDelegatedTokens[_sender] -= _tokenIds.length;
        _checkpoint(totalBias, totalSlope, _delegatee);
        IVotingEscrow(escrow).updateVotingPower(_sender, _delegatee);
        emit TokensUndelegated(_sender, _delegatee, _tokenIds);
    }
    /// @notice It returns which tokens are currently delegated from the list of `_tokenIds`.
    function getDelegatedTokens(
        uint256[] memory _tokenIds
    ) public view virtual returns (uint256[] memory) {
        uint256[] memory delegatedTokenIds = new uint256[](_tokenIds.length);
        uint256 count;
        for (uint256 i = 0; i < _tokenIds.length; ++i) {
            if (tokenIsDelegated(_tokenIds[i])) {
                delegatedTokenIds[count++] = _tokenIds[i];
            }
        }
        // Trim to size
        assembly {
            mstore(delegatedTokenIds, count)
        }
        return delegatedTokenIds;
    }
    /// @notice Whether an `account` has disabled auto delegation or not.
    /// @param _account The address on which auto delegation is checked for.
    /// @return True if auto delegation is disabled, otherwise false.
    function autoDelegationDisabled(address _account) public view virtual returns (bool) {
        return autoDelegationDisabled_[_account];
    }
    /*//////////////////////////////////////////////////////////////
                        IERC6372 Functions
    //////////////////////////////////////////////////////////////*/
    /// @inheritdoc IERC6372
    function clock() external view returns (uint48) {
        return uint48(block.timestamp);
    }
    /// @inheritdoc IERC6372
    function CLOCK_MODE() external pure returns (string memory) {
        return "mode=timestamp";
    }
    /*//////////////////////////////////////////////////////////////
                        Checkpoint Functions
    //////////////////////////////////////////////////////////////*/
    function checkpointTransition(
        address _delegatee,
        uint256 _transitionCount
    ) external whenNotPaused {
        _checkpoint(0, 0, _delegatee, _transitionCount);
    }
    function _checkpoint(
        int256 _totalBias,
        int256 _totalSlope,
        address _delegatee
    ) internal override {
        _checkpoint(_totalBias, _totalSlope, _delegatee, 255);
    }
    function _checkpoint(
        int256 _totalBias,
        int256 _totalSlope,
        address _delegatee,
        uint256 _transitionCount
    ) internal override {
        if(_transitionCount == 0) revert ZeroTransition();
        
        GlobalPoint memory lastPoint = GlobalPoint({
            bias: 0,
            slope: 0,
            writtenTs: uint48(block.timestamp)
        });
        uint256 latestPointIndex_ = latestPointIndex[_delegatee];
        if (latestPointIndex_ > 0) {
            lastPoint = pointHistory[_delegatee][latestPointIndex_];
        }
        // Get slope changes for the delegatee
        mapping(uint256 => int256) storage slopeChanges_ = slopeChanges[_delegatee];
        uint256 expectedWrittenTs;
        {
            uint256 checkpointInterval = IClock(escrowClock).checkpointInterval();
            uint256 lastPointCheckpoint = lastPoint.writtenTs;
            uint256 t_i = (lastPointCheckpoint / checkpointInterval) * checkpointInterval;
            // Since `_checkpoint` can be called manually due to transition,
            // the global point's writtenTs shouldn't be block.timestamp
            // by default, but whatever the transition's max week is.
            expectedWrittenTs = t_i + _transitionCount * checkpointInterval;
            if (expectedWrittenTs > block.timestamp) {
                expectedWrittenTs = block.timestamp;
            }
            for (uint256 i = 0; i < _transitionCount; ++i) {
                t_i += checkpointInterval;
                int256 dSlope;
                if (t_i > expectedWrittenTs) {
                    t_i = expectedWrittenTs;
                } else {
                    dSlope = slopeChanges_[t_i];
                }
                lastPoint.bias += lastPoint.slope * int256(t_i - lastPointCheckpoint);
                lastPoint.slope -= dSlope;
                if (lastPoint.slope < 0) lastPoint.slope = 0;
                if (lastPoint.bias < 0) lastPoint.bias = 0;
                lastPointCheckpoint = t_i;
                if (t_i == expectedWrittenTs) {
                    break;
                }
            }
        }
        // totalBias and totalSlope can be negative, in which case
        // it will subtract instead of adding.
        lastPoint.bias += _totalBias;
        lastPoint.slope += _totalSlope;
        lastPoint.writtenTs = uint48(expectedWrittenTs);
        if (lastPoint.slope < 0) lastPoint.slope = 0;
        if (lastPoint.bias < 0) lastPoint.bias = 0;
        latestPointIndex[_delegatee] = ++latestPointIndex_;
        pointHistory[_delegatee][latestPointIndex_] = lastPoint;
    }
    /// @notice Proxies a call to the ERC721 contract
    /// @dev Useful for calling contracts looking to validate if the contract is token-like
    function balanceOf(address _account) public view virtual returns (uint256) {
        address lockNFT = IVotingEscrow(escrow).lockNFT();
        if (lockNFT == address(0)) return 0;
        return IERC721EMB(lockNFT).balanceOf(_account);
    }
    /*//////////////////////////////////////////////////////////////
                      IVotes Function
    //////////////////////////////////////////////////////////////*/
    /// @notice Returns the current amount of votes that `account` has.
    function getVotes(address _account) external view returns (uint256) {
        return _delegateBalanceAt(_account, block.timestamp);
    }
    /// @notice Returns the amount of votes that `account` had at a specific moment in the past.
    function getPastVotes(address _account, uint256 _timestamp) public view returns (uint256) {
        return _delegateBalanceAt(_account, _timestamp);
    }
    /// @notice Returns the total supply of votes available at a specific moment in the past.
    /// @dev This value is the sum of all available votes, which is not necessarily the sum
    ///      of all delegated votes. Votes that have not been delegated are still part of
    ///      total supply, even though they would not participate in a vote.
    function getPastTotalSupply(uint256 _timestamp) external view returns (uint256) {
        return IVotingEscrow(escrow).totalVotingPowerAt(_timestamp);
    }
    /// @inheritdoc IEscrowIVotesAdapter
    function delegates(address _account) public view virtual override returns (address) {
        return delegatees_[_account];
    }
    /// @dev Not implemented.
    function delegateBySig(address, uint256, uint256, uint8, bytes32, bytes32) public virtual {
        revert DelegateBySigNotSupported();
    }
    /*//////////////////////////////////////////////////////////////
                      Binary Search Functions
    //////////////////////////////////////////////////////////////*/
    function getPastDelegatePointIndex(
        address _delegatee,
        uint256 _timestamp
    ) internal view returns (uint256) {
        uint256 latestPointIndex_ = latestPointIndex[_delegatee];
        if (latestPointIndex_ == 0) return 0;
        mapping(uint256 => GlobalPoint) storage pointHistory_ = pointHistory[_delegatee];
        // First check most recent balance
        if (pointHistory_[latestPointIndex_].writtenTs <= _timestamp) return (latestPointIndex_);
        // Next check implicit zero balance
        if (pointHistory_[1].writtenTs > _timestamp) return 0;
        uint256 lower = 0;
        uint256 upper = latestPointIndex_;
        while (upper > lower) {
            uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            GlobalPoint storage delegatePoint = pointHistory_[center];
            if (delegatePoint.writtenTs == _timestamp) {
                return center;
            } else if (delegatePoint.writtenTs < _timestamp) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return lower;
    }
    /// @notice Calculate total voting power at some point in the past
    /// @param _timestamp Time to calculate the total voting power at
    /// @return Total voting power at that time
    function _delegateBalanceAt(
        address _delegatee,
        uint256 _timestamp
    ) internal view returns (uint256) {
        uint256 index = getPastDelegatePointIndex(_delegatee, _timestamp);
        // epoch 0 is an empty point
        if (index == 0) return 0;
        GlobalPoint memory point = pointHistory[_delegatee][index];
        int256 bias = point.bias;
        int256 slope = point.slope;
        uint256 ts = point.writtenTs;
        mapping(uint256 => int256) storage slopeChanges_ = slopeChanges[_delegatee];
        uint256 checkpointInterval = IClock(escrowClock).checkpointInterval();
        uint256 t_i = (ts / checkpointInterval) * checkpointInterval;
        for (uint256 i = 0; i < 255; ++i) {
            t_i += checkpointInterval;
            int256 dSlope = 0;
            if (t_i > _timestamp) {
                t_i = _timestamp;
            } else {
                dSlope = slopeChanges_[t_i];
            }
            bias += slope * int256(t_i - ts);
            if (t_i == _timestamp) {
                break;
            }
            slope -= dSlope;
            ts = t_i;
        }
        if (bias < 0) bias = 0;
        return uint256(SignedFixedPointMath.fromFP(bias));
    }
    /*//////////////////////////////////////////////////////////////
                        Private Helper Functions
    //////////////////////////////////////////////////////////////*/
    /// @dev Note that this function also updates slopeChanges.
    function _getBiasAndSlope(
        address _delegatee,
        IVotingEscrow.LockedBalance memory _locked,
        function(int256) view returns (int256) op
    ) internal override returns (int256, int256) {
        uint256 elapsed = block.timestamp - _locked.start;
        elapsed = elapsed > maxTime ? maxTime : elapsed;
        int256 amount = uint256(_locked.amount).toInt256();
        int256 slope = amount * SHARED_LINEAR_COEFFICIENT;
        int256 bias = slope *
            int256(elapsed) +
            amount *
            SHARED_CONSTANT_COEFFICIENT;
        if (bias < 0) bias = 0;
        if (elapsed < maxTime) {
            slope = op(slope);
            slopeChanges[_delegatee][_locked.start + maxTime] += slope;
        } else {
            slope = 0;
        }
        return (op(bias), slope);
    }
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    function _authorizeUpgrade(address) internal virtual override auth(DELEGATION_ADMIN_ROLE) {}
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[43] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol)
pragma solidity ^0.8.0;
import "./ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
 * @dev Storage based implementation of the {IERC165} interface.
 *
 * Contracts may inherit from this and call {_registerInterface} to declare
 * their support of an interface.
 */
abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable {
    function __ERC165Storage_init() internal onlyInitializing {
    }
    function __ERC165Storage_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Mapping of interface ids to whether or not it's supported.
     */
    mapping(bytes4 => bool) private _supportedInterfaces;
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId];
    }
    /**
     * @dev Registers the contract as an implementer of the interface defined by
     * `interfaceId`. Support of the actual ERC165 interface is automatic and
     * registering its interface id is not required.
     *
     * See {IERC165-supportsInterface}.
     *
     * Requirements:
     *
     * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
     */
    function _registerInterface(bytes4 interfaceId) internal virtual {
        require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
        _supportedInterfaces[interfaceId] = true;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    function __UUPSUpgradeable_init() internal onlyInitializing {
    }
    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);
    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }
    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }
    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
        return _IMPLEMENTATION_SLOT;
    }
    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }
    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data, true);
    }
    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeTo} and {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal override onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20Upgradeable {
    using AddressUpgradeable for address;
    /**
     * @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(IERC20Upgradeable token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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(IERC20Upgradeable token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }
    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }
    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }
    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }
    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }
    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20PermitUpgradeable token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }
    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.
        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }
    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.
        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);
    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);
    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);
    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);
    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);
    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);
    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721ReceiverUpgradeable {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );
    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);
    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);
    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);
    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);
    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;
    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);
    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
 * @dev _Available since v3.1._
 */
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);
    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 *
 * _Available since v4.1._
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title IProtocolVersion /// @author Aragon X - 2022-2023 /// @notice An interface defining the semantic Aragon OSx protocol version number. /// @custom:security-contact [email protected] interface IProtocolVersion { /// @notice Returns the semantic Aragon OSx protocol version number that the implementing contract is associated with. /// @return _version Returns the semantic Aragon OSx protocol version number. /// @dev This version number is not to be confused with the `release` and `build` numbers found in the `Version.Tag` struct inside the `PluginRepo` contract being used to version plugin setup and associated plugin implementation contracts. function protocolVersion() external view returns (uint8[3] memory _version); }
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {IProtocolVersion} from "./IProtocolVersion.sol";
/// @title ProtocolVersion
/// @author Aragon X - 2023
/// @notice An abstract, stateless, non-upgradeable contract providing the current Aragon OSx protocol version number.
/// @dev Do not add any new variables to this contract that would shift down storage in the inheritance chain.
/// @custom:security-contact [email protected]
abstract contract ProtocolVersion is IProtocolVersion {
    // IMPORTANT: Do not add any storage variable, see the above notice.
    /// @inheritdoc IProtocolVersion
    function protocolVersion() public pure returns (uint8[3] memory) {
        return [1, 4, 0];
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title VersionComparisonLib /// @author Aragon X - 2023 /// @notice A library containing methods for [semantic version number](https://semver.org/spec/v2.0.0.html) comparison. /// @custom:security-contact [email protected] library VersionComparisonLib { /// @notice Equality comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the two numbers are equal or not. function eq(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] != rhs[0]) return false; if (lhs[1] != rhs[1]) return false; if (lhs[2] != rhs[2]) return false; return true; } /// @notice Inequality comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the two numbers are inequal or not. function neq(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] != rhs[0]) return true; if (lhs[1] != rhs[1]) return true; if (lhs[2] != rhs[2]) return true; return false; } /// @notice Less than comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the first number is less than the second number or not. function lt(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] < rhs[0]) return true; if (lhs[0] > rhs[0]) return false; if (lhs[1] < rhs[1]) return true; if (lhs[1] > rhs[1]) return false; if (lhs[2] < rhs[2]) return true; return false; } /// @notice Less than or equal to comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the first number is less than or equal to the second number or not. function lte(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] < rhs[0]) return true; if (lhs[0] > rhs[0]) return false; if (lhs[1] < rhs[1]) return true; if (lhs[1] > rhs[1]) return false; if (lhs[2] <= rhs[2]) return true; return false; } /// @notice Greater than comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the first number is greater than the second number or not. function gt(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] > rhs[0]) return true; if (lhs[0] < rhs[0]) return false; if (lhs[1] > rhs[1]) return true; if (lhs[1] < rhs[1]) return false; if (lhs[2] > rhs[2]) return true; return false; } /// @notice Greater than or equal to comparator for two semantic version numbers. /// @param lhs The left-hand side semantic version number. /// @param rhs The right-hand side semantic version number. /// @return Whether the first number is greater than or equal to the second number or not. function gte(uint8[3] memory lhs, uint8[3] memory rhs) internal pure returns (bool) { if (lhs[0] > rhs[0]) return true; if (lhs[0] < rhs[0]) return false; if (lhs[1] > rhs[1]) return true; if (lhs[1] < rhs[1]) return false; if (lhs[2] >= rhs[2]) return true; return false; } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @param bitmap The `uint256` representation of bits. /// @param index The index number to check whether 1 or 0 is set. /// @return Returns `true` if the bit is set at `index` on `bitmap`. /// @custom:security-contact [email protected] function hasBit(uint256 bitmap, uint8 index) pure returns (bool) { uint256 bitValue = bitmap & (1 << index); return bitValue > 0; } /// @param bitmap The `uint256` representation of bits. /// @param index The index number to set the bit. /// @return Returns a new number in which the bit is set at `index`. /// @custom:security-contact [email protected] function flipBit(uint256 bitmap, uint8 index) pure returns (uint256) { return bitmap ^ (1 << index); }
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IExecutor, Action} from "./IExecutor.sol";
import {flipBit, hasBit} from "../utils/math/BitMap.sol";
/// @title IDAO
/// @author Aragon X - 2024
/// @notice Simple Executor that loops through the actions and executes them.
/// @dev This doesn't use any type of permission for execution and can be called by anyone.
///      Most useful use-case is to deploy it as non-upgradeable and call from another contract via delegatecall.
///      If used with delegatecall, DO NOT add state variables in sequential slots, otherwise this will overwrite
///      the storage of the calling contract.
/// @custom:security-contact [email protected]
contract Executor is IExecutor, ERC165 {
    /// @notice The internal constant storing the maximal action array length.
    uint256 internal constant MAX_ACTIONS = 256;
    // keccak256("osx-commons.storage.Executor")
    bytes32 private constant REENTRANCY_GUARD_STORAGE_LOCATION =
        0x4d6542319dfb3f7c8adbb488d7b4d7cf849381f14faf4b64de3ac05d08c0bdec;
    /// @notice The first out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set indicating that a function was not entered.
    uint256 private constant _NOT_ENTERED = 1;
    /// @notice The second out of two values to which the `_reentrancyStatus` state variable (used by the `nonReentrant` modifier) can be set indicating that a function was entered.
    uint256 private constant _ENTERED = 2;
    /// @notice Thrown if the action array length is larger than `MAX_ACTIONS`.
    error TooManyActions();
    /// @notice Thrown if an action has insufficient gas left.
    error InsufficientGas();
    /// @notice Thrown if action execution has failed.
    /// @param index The index of the action in the action array that failed.
    error ActionFailed(uint256 index);
    /// @notice Thrown if a call is reentrant.
    error ReentrantCall();
    /// @notice Initializes the contract with a non-entered reentrancy status.
    /// @dev Sets the reentrancy guard status to `_NOT_ENTERED` to prevent reentrant calls from the start.
    constructor() {
        _storeReentrancyStatus(_NOT_ENTERED);
    }
    /// @notice Prevents reentrant calls to a function.
    /// @dev This modifier checks the reentrancy status before function execution. If already entered, it reverts with
    ///      `ReentrantCall()`. Sets the status to `_ENTERED` during execution and resets it to `_NOT_ENTERED` afterward.
    modifier nonReentrant() {
        if (_getReentrancyStatus() == _ENTERED) {
            revert ReentrantCall();
        }
        _storeReentrancyStatus(_ENTERED);
        _;
        _storeReentrancyStatus(_NOT_ENTERED);
    }
    /// @notice Checks if this or the parent contract supports an interface by its ID.
    /// @param _interfaceId The ID of the interface.
    /// @return Returns `true` if the interface is supported.
    function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
        return _interfaceId == type(IExecutor).interfaceId || super.supportsInterface(_interfaceId);
    }
    /// @inheritdoc IExecutor
    function execute(
        bytes32 _callId,
        Action[] memory _actions,
        uint256 _allowFailureMap
    )
        public
        virtual
        override
        nonReentrant
        returns (bytes[] memory execResults, uint256 failureMap)
    {
        // Check that the action array length is within bounds.
        if (_actions.length > MAX_ACTIONS) {
            revert TooManyActions();
        }
        execResults = new bytes[](_actions.length);
        uint256 gasBefore;
        uint256 gasAfter;
        for (uint256 i = 0; i < _actions.length; ) {
            gasBefore = gasleft();
            (bool success, bytes memory data) = _actions[i].to.call{value: _actions[i].value}(
                _actions[i].data
            );
            gasAfter = gasleft();
            // Check if failure is allowed
            if (!success) {
                if (!hasBit(_allowFailureMap, uint8(i))) {
                    revert ActionFailed(i);
                }
                // Make sure that the action call did not fail because 63/64 of `gasleft()` was insufficient to execute the external call `.to.call` (see [ERC-150](https://eips.ethereum.org/EIPS/eip-150)).
                // In specific scenarios, i.e. proposal execution where the last action in the action array is allowed to fail, the account calling `execute` could force-fail this action by setting a gas limit
                // where 63/64 is insufficient causing the `.to.call` to fail, but where the remaining 1/64 gas are sufficient to successfully finish the `execute` call.
                if (gasAfter < gasBefore / 64) {
                    revert InsufficientGas();
                }
                // Store that this action failed.
                failureMap = flipBit(failureMap, uint8(i));
            }
            execResults[i] = data;
            unchecked {
                ++i;
            }
        }
        emit Executed({
            actor: msg.sender,
            callId: _callId,
            actions: _actions,
            allowFailureMap: _allowFailureMap,
            failureMap: failureMap,
            execResults: execResults
        });
    }
    /// @notice Gets the current reentrancy status.
    /// @return status This returns the current reentrancy status.
    function _getReentrancyStatus() private view returns (uint256 status) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            status := sload(REENTRANCY_GUARD_STORAGE_LOCATION)
        }
    }
    /// @notice Stores the reentrancy status at a specific storage slot.
    /// @param _status The reentrancy status to be stored, typically `_ENTERED` or `_NOT_ENTERED`.
    /// @dev Uses inline assembly to store the `_status` value at `REENTRANCY_GUARD_STORAGE_LOCATION` to manage
    ///      reentrancy status efficiently.
    function _storeReentrancyStatus(uint256 _status) private {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(REENTRANCY_GUARD_STORAGE_LOCATION, _status)
        }
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title CallbackHandler /// @author Aragon X - 2022-2023 /// @notice This contract handles callbacks by registering a magic number together with the callback function's selector. It provides the `_handleCallback` function that inheriting contracts have to call inside their `fallback()` function (`_handleCallback(msg.callbackSelector, msg.data)`). This allows to adaptively register ERC standards (e.g., [ERC-721](https://eips.ethereum.org/EIPS/eip-721), [ERC-1115](https://eips.ethereum.org/EIPS/eip-1155), or future versions of [ERC-165](https://eips.ethereum.org/EIPS/eip-165)) and returning the required magic numbers for the associated callback functions for the inheriting contract so that it doesn't need to be upgraded. /// @dev This callback handling functionality is intended to be used by executor contracts (i.e., `DAO.sol`). /// @custom:security-contact [email protected] abstract contract CallbackHandler { /// @notice A mapping between callback function selectors and magic return numbers. mapping(bytes4 => bytes4) internal callbackMagicNumbers; /// @notice The magic number refering to unregistered callbacks. bytes4 internal constant UNREGISTERED_CALLBACK = bytes4(0); /// @notice Thrown if the callback function is not registered. /// @param callbackSelector The selector of the callback function. /// @param magicNumber The magic number to be registered for the callback function selector. error UnknownCallback(bytes4 callbackSelector, bytes4 magicNumber); /// @notice Emitted when `_handleCallback` is called. /// @param sender Who called the callback. /// @param sig The function signature. /// @param data The calldata. event CallbackReceived(address sender, bytes4 indexed sig, bytes data); /// @notice Handles callbacks to adaptively support ERC standards. /// @dev This function is supposed to be called via `_handleCallback(msg.sig, msg.data)` in the `fallback()` function of the inheriting contract. /// @param _callbackSelector The function selector of the callback function. /// @param _data The calldata. /// @return The magic number registered for the function selector triggering the fallback. function _handleCallback( bytes4 _callbackSelector, bytes memory _data ) internal virtual returns (bytes4) { bytes4 magicNumber = callbackMagicNumbers[_callbackSelector]; if (magicNumber == UNREGISTERED_CALLBACK) { revert UnknownCallback({callbackSelector: _callbackSelector, magicNumber: magicNumber}); } emit CallbackReceived({sender: msg.sender, sig: _callbackSelector, data: _data}); return magicNumber; } /// @notice Registers a magic number for a callback function selector. /// @param _callbackSelector The selector of the callback function. /// @param _magicNumber The magic number to be registered for the callback function selector. function _registerCallback(bytes4 _callbackSelector, bytes4 _magicNumber) internal virtual { callbackMagicNumbers[_callbackSelector] = _magicNumber; } /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)). uint256[49] private __gap; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title EIP-4824 Common Interfaces for DAOs /// @dev See https://eips.ethereum.org/EIPS/eip-4824 /// @author Aragon X - 2021-2023 /// @custom:security-contact [email protected] interface IEIP4824 { /// @notice A distinct Uniform Resource Identifier (URI) pointing to a JSON object following the "EIP-4824 DAO JSON-LD Schema". This JSON file splits into four URIs: membersURI, proposalsURI, activityLogURI, and governanceURI. The membersURI should point to a JSON file that conforms to the "EIP-4824 Members JSON-LD Schema". The proposalsURI should point to a JSON file that conforms to the "EIP-4824 Proposals JSON-LD Schema". The activityLogURI should point to a JSON file that conforms to the "EIP-4824 Activity Log JSON-LD Schema". The governanceURI should point to a flatfile, normatively a .md file. Each of the JSON files named above can be statically hosted or dynamically-generated. /// @return _daoURI The DAO URI. function daoURI() external view returns (string memory _daoURI); }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
     * function call, and allows initializing the storage of the proxy like a Solidity constructor.
     */
    constructor(address _logic, bytes memory _data) payable {
        _upgradeToAndCall(_logic, _data, false);
    }
    /**
     * @dev Returns the current implementation address.
     */
    function _implementation() internal view virtual override returns (address impl) {
        return ERC1967Upgrade._getImplementation();
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.0;
import "../ERC20Upgradeable.sol";
import "../utils/SafeERC20Upgradeable.sol";
import "../../../interfaces/IERC4626Upgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
 * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * [CAUTION]
 * ====
 * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
 * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
 * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
 * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
 * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
 * verifying the amount received is as expected, using a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
 * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
 * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
 * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
 * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
 * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
 * expensive than it is profitable. More details about the underlying math can be found
 * xref:erc4626.adoc#inflation-attack[here].
 *
 * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
 * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
 * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
 * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
 * `_convertToShares` and `_convertToAssets` functions.
 *
 * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
 * ====
 *
 * _Available since v4.7._
 */
abstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {
    using MathUpgradeable for uint256;
    IERC20Upgradeable private _asset;
    uint8 private _underlyingDecimals;
    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
     */
    function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {
        __ERC4626_init_unchained(asset_);
    }
    function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        _underlyingDecimals = success ? assetDecimals : 18;
        _asset = asset_;
    }
    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20Upgradeable asset_) private view returns (bool, uint8) {
        (bool success, bytes memory encodedDecimals) =
            address(asset_).staticcall(abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector));
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }
    /**
     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
     * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
     *
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {
        return _underlyingDecimals + _decimalsOffset();
    }
    /**
     * @dev See {IERC4626-asset}.
     */
    function asset() public view virtual override returns (address) {
        return address(_asset);
    }
    /**
     * @dev See {IERC4626-totalAssets}.
     */
    function totalAssets() public view virtual override returns (uint256) {
        return _asset.balanceOf(address(this));
    }
    /**
     * @dev See {IERC4626-convertToShares}.
     */
    function convertToShares(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, MathUpgradeable.Rounding.Down);
    }
    /**
     * @dev See {IERC4626-convertToAssets}.
     */
    function convertToAssets(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, MathUpgradeable.Rounding.Down);
    }
    /**
     * @dev See {IERC4626-maxDeposit}.
     */
    function maxDeposit(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }
    /**
     * @dev See {IERC4626-maxMint}.
     */
    function maxMint(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }
    /**
     * @dev See {IERC4626-maxWithdraw}.
     */
    function maxWithdraw(address owner) public view virtual override returns (uint256) {
        return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);
    }
    /**
     * @dev See {IERC4626-maxRedeem}.
     */
    function maxRedeem(address owner) public view virtual override returns (uint256) {
        return balanceOf(owner);
    }
    /**
     * @dev See {IERC4626-previewDeposit}.
     */
    function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, MathUpgradeable.Rounding.Down);
    }
    /**
     * @dev See {IERC4626-previewMint}.
     */
    function previewMint(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, MathUpgradeable.Rounding.Up);
    }
    /**
     * @dev See {IERC4626-previewWithdraw}.
     */
    function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, MathUpgradeable.Rounding.Up);
    }
    /**
     * @dev See {IERC4626-previewRedeem}.
     */
    function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, MathUpgradeable.Rounding.Down);
    }
    /**
     * @dev See {IERC4626-deposit}.
     */
    function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
        require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");
        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);
        return shares;
    }
    /**
     * @dev See {IERC4626-mint}.
     *
     * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
     * In this case, the shares will be minted without requiring any assets to be deposited.
     */
    function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
        require(shares <= maxMint(receiver), "ERC4626: mint more than max");
        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);
        return assets;
    }
    /**
     * @dev See {IERC4626-withdraw}.
     */
    function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) {
        require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");
        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);
        return shares;
    }
    /**
     * @dev See {IERC4626-redeem}.
     */
    function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) {
        require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");
        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);
        return assets;
    }
    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     */
    function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding)
        internal
        view
        virtual
        returns (uint256)
    {
        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
    }
    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding)
        internal
        view
        virtual
        returns (uint256)
    {
        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
    }
    // for 1e18 initial vault:
    // (1e18 * (101000000000000000000 + 1)) / (1000000000000000000 + 1) = 101,000,000,000,000,000,001,000,000,000,000,000,000 / 1,000,000,000,000,000,001 = 100,999,999,999,999,999,900.00000000000000009999
    // (1e18 * (151000000000000000000 + 1)) / (1495049504950495049 + 1) = 151,000,000,000,000,000,001,000,000,000,000,000,000 / 1,495,049,504,950,495,050 = 100,999,999,999,999,999,967.22516556291390729562
    // for 100e18
    // (1e18 * (200000000000000000000 + 1)) / (100000000000000000000 + 1) =
    // (1e18 * (250000000000000000000 + 1)) / (125000000000000000000 + 1) =
    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
        // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);
        _mint(receiver, shares);
        emit Deposit(caller, receiver, assets, shares);
    }
    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
        internal
        virtual
    {
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }
        // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);
        emit Withdraw(caller, receiver, owner, assets, shares);
    }
    function _decimalsOffset() internal view virtual returns (uint8) {
        return 0;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
    function __ERC721Holder_init() internal onlyInitializing {
    }
    function __ERC721Holder_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);
    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);
    bool private _paused;
    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }
    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }
    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }
    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }
    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }
    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }
    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }
    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }
    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {ContextUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import {IDAO} from "../../dao/IDAO.sol";
import {_auth} from "./auth.sol";
/// @title DaoAuthorizableUpgradeable
/// @author Aragon X - 2022-2023
/// @notice An abstract contract providing a meta-transaction compatible modifier for upgradeable or cloneable contracts to authorize function calls through an associated DAO.
/// @dev Make sure to call `__DaoAuthorizableUpgradeable_init` during initialization of the inheriting contract.
/// @custom:security-contact [email protected]
abstract contract DaoAuthorizableUpgradeable is ContextUpgradeable {
    /// @notice The associated DAO managing the permissions of inheriting contracts.
    IDAO private dao_;
    /// @notice Initializes the contract by setting the associated DAO.
    /// @param _dao The associated DAO address.
    // solhint-disable-next-line func-name-mixedcase
    function __DaoAuthorizableUpgradeable_init(IDAO _dao) internal onlyInitializing {
        dao_ = _dao;
    }
    /// @notice Returns the DAO contract.
    /// @return The DAO contract.
    function dao() public view returns (IDAO) {
        return dao_;
    }
    /// @notice A modifier to make functions on inheriting contracts authorized. Permissions to call the function are checked through the associated DAO's permission manager.
    /// @param _permissionId The permission identifier required to call the method this modifier is applied to.
    modifier auth(bytes32 _permissionId) {
        _auth(dao_, address(this), _msgSender(), _permissionId, _msgData());
        _;
    }
    /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)).
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IStrategy } from "./IStrategy.sol";
interface IStrategyNFT is IStrategy {
    error MasterTokenAlreadySet();
    error MasterTokenNotSet();
    /// @notice Emitted when an existing token is deposited by merging to master token
    /// @param tokenId The token ID that was merged into the master token
    /// @param masterTokenId The master token that received the merge
    event TokenIdDeposited(uint256 indexed tokenId, uint256 indexed masterTokenId);
    /// @notice Emitted when the strategy receives and sets its master token
    /// @param masterTokenId The master token ID that was set
    event MasterTokenReceived(uint256 indexed masterTokenId);
    /// @notice Handles deposit of existing token by merging to master token
    /// @param _tokenId The token ID to merge
    function depositTokenId(uint256 _tokenId) external;
    /// @notice Receives master token id from vault. Must be called
    ///         in the same tx after tokenId is transferred to strategy.
    function receiveMasterToken(uint256 _tokenId) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IVaultNFT {
    event Sweep(uint256 tokenId, address receiver);
    event TokenIdWithdrawn(uint256 indexed tokenId, address indexed receiver);
    event TokenIdDepositted(uint256 indexed tokenId, address indexed sender);
    error CannotTransferMasterToken();
    error MasterTokenAlreadySet();
    error TokenIdCannotBeZero();
    /// @notice Allows to set up masterTokenId and strategy initially.
    function initializeMasterTokenAndStrategy(uint256 _tokenId, address _strategy) external;
    /// @notice deposit tokenId into the vault.
    /// @dev The assets amount derivation is up to the implementation.
    function depositTokenId(uint256 _tokenId, address _receiver) external returns (uint256 shares);
    /// @notice Withdraws shares through custom logic of strategy
    ///         and returns the new tokenId that holds `_assets`.
    function withdrawTokenId(uint256 _assets, address _receiver, address _owner) external returns (uint256 tokenId);
    /// @notice send veNFT mistakenly transferred to vault to `_receiver`.
    function recoverNFT(uint256 _tokenId, address _receiver) external;
    /// @notice Defines the minimum amount needed to initialize the master token.
    ///         Ensures the vault is not empty at start and protects against inflation attacks.
    function minMasterTokenInitAmount() external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.
    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];
        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.
            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;
            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];
                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }
            // Delete the slot where the moved value was stored
            set._values.pop();
            // Delete the index for the deleted slot
            delete set._indexes[value];
            return true;
        } else {
            return false;
        }
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }
    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }
    // Bytes32Set
    struct Bytes32Set {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
    // AddressSet
    struct AddressSet {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
    // UintSet
    struct UintSet {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
/**
 * @title IVKatMetadata Interface
 * @author Aragon
 * @notice Interface for the VKatMetadata sidecar contract that stores user preferences for vKAT NFTs
 * @dev This contract is designed to be UUPS-upgradable and decouples application-specific metadata from the core
 * locking contract
 */
interface IVKatMetadata {
    struct VKatMetaDataV1 {
        uint16[] rewardTokenWeights; // Relative weights, to be normalized by the consumer
        address[] rewardTokens;
    }
    /// @notice Emitted when a user sets or updates their preferences
    event PreferencesSet(address indexed account, VKatMetaDataV1 preferences);
    /// @notice Emitted when admin sets/updates the default preferences.
    event DefaultPreferencesSet(VKatMetaDataV1 preferences);
    /// @notice Emitted when a new reward token is added by the owner
    event RewardTokenAdded(address indexed token);
    /// @notice Emitted when a reward token is removed by the owner
    event RewardTokenRemoved(address indexed token);
    error NotOwner();
    error TokenNotWhitelisted(address token);
    error TokenAlreadyInWhitelist(address token);
    error TokenNotInWhitelist(address token);
    error LengthMismatch();
    error ZeroAddress();
    error DuplicateRewardToken();
    error ReservedAddressCannotBeRemoved();
    // ======= Administrative Functions ======
    /**
     * @notice Adds a new token to the list of allowed reward tokens
     * @dev Can only be called by authorised caller
     * @param _rewardToken The address of the ERC20 token to add
     */
    function addRewardToken(address _rewardToken) external;
    /**
     * @notice Removes a token from the list of allowed reward tokens
     * @dev Can only be called by authorised caller. Off-chain consumers are responsible for ignoring user preferences
     * for removed tokens
     * @param _rewardToken The address of the ERC20 token to remove
     */
    function removeRewardToken(address _rewardToken) external;
    /**
     * @notice Sets a default preference. This is what is returned for
     * a tokenId that doesn't have custom preferences set.
     * @param _defaultPreferences The new default preferences.
     */
    function setDefaultPreferences(VKatMetaDataV1 calldata _defaultPreferences) external;
    // ======= User-Facing Functions =======
    /**
     * @notice Sets the preferences for a given vKAT NFT
     * @dev The caller must be the owner or approved caller of the _tokenId. Reward token weights are relative and do
     * not need to sum to a specific value
     * @param _prefs The preference struct containing the desired settings
     */
    function setPreferences(VKatMetaDataV1 calldata _prefs) external;
    // --- View Functions ---
    /**
     * @notice Retrieves the preferences for a given token, returning defaults if none are set
     * @dev Checks for token existence. If token no longer exists, reverts If custom preferences exist, returns them.
     * Otherwise, returns the system default
     * @param _account The address for which to return preferences.
     * @return A VKatMetaDataV1 struct with the account's preferences
     */
    function getPreferencesOrDefault(address _account) external view returns (VKatMetaDataV1 memory);
    /**
     * @notice Checks if a token is on the allowed reward tokens list
     * @param _token The address of the token to check
     * @return True if the token is allowed, false otherwise
     */
    function isRewardToken(address _token) external view returns (bool);
    /**
     * @notice Returns the address of the kat token
     * @return The address of the kat token
     */
    function kat() external view returns (address);
    /**
     * @notice Returns the default preferences applied to vKAT NFTs without custom settings
     * @return The default VKatMetaDataV1 struct
     */
    function getDefaultPreferences() external view returns (VKatMetaDataV1 memory);
    /**
     * @notice Returns the list of all allowed reward tokens.
     */
    function allowedRewardTokens() external view returns (address[] memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { VotingEscrowV1_2_0 as Escrow } from "@escrow/VotingEscrowIncreasing_v1_2_0.sol";
import { Action } from "@aragon/osx-commons-contracts/src/executors/IExecutor.sol";
import { ISwapper } from "src/interfaces/ISwapper.sol";
import { IRewardsDistributor } from "src/interfaces/IRewardsDistributor.sol";
contract Swapper is ISwapper, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using Address for address;
    /// @notice Basis points for percentage calculations (100% = 10000 basis points)
    uint256 private constant BASIS_POINTS = 10_000;
    /// @notice The address of the rewards distributor where swapper can claim tokens.
    address public immutable rewardDistributor;
    /// @notice The escrow contract address
    Escrow public immutable escrow;
    /// @notice The ERC20 token address escrow uses
    IERC20 public immutable escrowToken;
    constructor(address _rewardDistributor, address _escrow) {
        rewardDistributor = _rewardDistributor;
        escrow = Escrow(_escrow);
        escrowToken = IERC20(escrow.token());
    }
    receive() external payable { }
    /// @inheritdoc ISwapper
    function claimAndSwap(
        Claim calldata _claim,
        Action[] calldata _actions,
        uint256 _pct
    )
        public
        payable
        virtual
        nonReentrant
        returns (uint256 tokenAmountGained, uint256 tokenId)
    {
        // make sure percentage is never more than 100% (10000 basis points).
        if (_pct > BASIS_POINTS) {
            revert PctTooBig();
        }
        address[] memory users = new address[](_claim.tokens.length);
        for (uint256 i = 0; i < _claim.tokens.length; i++) {
            users[i] = msg.sender;
        }
        // If `_tokens`, `_amounts` and `_proofs` have incorrect size, below reverts.
        // The `user` must have set this contract as a recipient
        // for the `token` prior to calling this.
        // At this point, this contract holds balances on `_tokens`.
        IRewardsDistributor(rewardDistributor).claim(users, _claim.tokens, _claim.amounts, _claim.proofs);
        bytes[] memory execResults = _executeActions(_actions);
        // Actions may swap claimed tokens to KAT. Only KAT balance on this contract
        // determines compounding amount; other tokens are handled by actions directly.
        tokenAmountGained = escrowToken.balanceOf(address(this));
        Locked memory lock;
        if (tokenAmountGained > 0) {
            lock = _compoundEscrowToken(_pct, tokenAmountGained);
        }
        // send any remaining eth to the sender.
        _withdrawNative();
        emit ClaimAndSwapped(msg.sender, _claim.tokens, _claim.amounts, _pct, lock, _actions, execResults);
        return (tokenAmountGained, lock.tokenId);
    }
    function _compoundEscrowToken(
        uint256 _pct,
        uint256 _tokenAmountGained
    )
        internal
        virtual
        returns (Locked memory lock)
    {
        // If tokenAmountGained > 0, then kat token balance was increased on this contract.
        // If pct > 0, create a lock with percentage and send rest to sender.
        // If pct = 0, send whole amount to sender.
        uint256 remaining = _tokenAmountGained;
        if (_pct > 0) {
            // If _tokenAmountGained or _pct is too small, lock.amount may fall
            // below escrow’s minDeposit and fail. Failing early avoids confusion.
            // otherwise, the user might expect a partial lock while all funds return.
            // User can retry with a higher _pct for a valid lock.
            lock.amount = (_tokenAmountGained * _pct) / BASIS_POINTS;
            remaining = _tokenAmountGained - lock.amount;
            // approve should not revert even for non-compliant ERC20s as
            // it only approves the exact amount that will be transfered
            // from this contract, automatically setting allowance back to 0.
            // we trust that escrow's createLockFor will transfer the whole lock.amount.
            escrowToken.approve(address(escrow), lock.amount);
            lock.tokenId = escrow.createLockFor(lock.amount, msg.sender);
        }
        if (remaining > 0) {
            escrowToken.safeTransfer(msg.sender, remaining);
        }
    }
    /// @notice Internal helper function to execute user actions and return execution results.
    function _executeActions(Action[] memory _actions) internal virtual returns (bytes[] memory execResults) {
        uint256 len = _actions.length;
        if (len == 0) return execResults;
        // If there're actions, execute them and record
        // the execution result data for each.
        execResults = new bytes[](len);
        for (uint256 i = 0; i < len; i++) {
            address target = _actions[i].to;
            // For extra safety measures, don't allow actions to call rewardsDistributor
            // Prior this, claim is already called on it which should be enough.
            if (target == rewardDistributor) {
                revert RewardDistributorCallForbidden();
            }
            (bool success, bytes memory returnData) = target.call{ value: _actions[i].value }(_actions[i].data);
            execResults[i] = returnData;
            target.verifyCallResultFromTarget(success, returnData, "ActionFailed");
        }
    }
    /// @notice If there is any eth, transfer to the sender.
    /// @dev If sender is a contract and doesn't have receive/fallback,
    ///      eth stays in swapper and next user can withdraw.
    function _withdrawNative() internal virtual {
        msg.sender.call{ value: address(this).balance }("");
    }
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Action } from "@aragon/osx-commons-contracts/src/executors/IExecutor.sol";
interface ISwapper {
    error ActionsFailed();
    error NoBalanceChange();
    error ZeroAddress();
    error LengthMismatch();
    error PctTooBig();
    error RewardDistributorCallForbidden();
    /// @notice Emitted when `claimAndSwap` is executed.
    /// @param user The account that initiated the function.
    /// @param tokens The token addresses that will be claimed.
    /// @param claimAmounts The amounts that will be claimed.
    /// @param pct The percentage of total amount that goes to escrow.
    /// @param locked The tokenId that will be created on escrow with an amount.
    /// @param actions The array of actions executed.
    /// @param execResults The array with the results of the executed actions.
    event ClaimAndSwapped(
        address indexed user,
        address[] tokens,
        uint256[] claimAmounts,
        uint256 pct,
        Locked locked,
        Action[] actions,
        bytes[] execResults
    );
    struct Claim {
        address[] tokens;
        uint256[] amounts;
        bytes32[][] proofs;
    }
    struct Locked {
        uint256 tokenId;
        uint256 amount;
    }
    /// @notice Claims reward tokens and optionally swaps some/all to KAT, then locks a percentage.
    /// @dev Claims tokens from Merkle distributor, executes optional swaps to KAT, and locks % of
    ///      resulting KAT in escrow. Not all claimed tokens need to be swapped.
    /// @param _claim Tokens to claim with amounts and Merkle proofs
    /// @param _actions Swap actions to execute (optional, can be partial)
    /// @param _pct Percentage (0-100) of KAT to lock in escrow
    /// @return tokenAmountGained Total KAT gained from claims and swaps
    /// @return tokenId Escrow lock NFT ID if _pct > 0, else 0
    function claimAndSwap(
        Claim calldata _claim,
        Action[] calldata _actions,
        uint256 _pct
    )
        external
        payable
        returns (uint256 tokenAmountGained, uint256 tokenId);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IRewardsDistributor {
    function claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs
    )
        external;
    function toggleOperator(address user, address operator) external;
    function setClaimRecipient(address user, address token) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface IStrategy {
    /// @notice Emitted when assets are deposited by creating a lock and merging to master token
    /// @param depositor The address that deposited the assets
    /// @param tokenId The temporary token ID created before merging
    /// @param amount The amount of assets deposited
    event Deposited(address indexed depositor, uint256 tokenId, uint256 amount);
    /// @notice Emitted when assets are withdrawn by splitting the master token
    /// @param receiver The address that received the split token
    /// @param tokenId The new token ID created from the split
    /// @param amount The amount of assets withdrawn
    event Withdrawn(address indexed receiver, uint256 tokenId, uint256 amount);
    /// @notice Emitted when the strategy is retired and master token transferred back to vault
    /// @param vault The vault address that received the master token
    /// @param masterTokenId The master token ID that was transferred
    event StrategyRetired(address indexed vault, uint256 masterTokenId);
    /// @notice Handles deposit by creating lock and merging to master token
    /// @param _assets Amount of assets to deposit
    function deposit(uint256 _assets) external;
    /// @notice Handles withdrawal by splitting master token and transferring to receiver
    /// @param _receiver The address to receive the split token
    /// @param _assets Amount of assets to withdraw
    function withdraw(address _receiver, uint256 _assets) external returns (uint256);
    /// @notice When vault decides to change strategy, it needs to
    ///         retire old strategy(i.e get masterTokenId back).
    function retireStrategy() external;
    /// @notice Returns the total assets managed by the strategy
    /// @return The total amount of assets locked in the master token
    function totalAssets() external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { IERC20Upgradeable as IERC20 } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { ERC721Upgradeable as ERC721 } from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import { ERC721HolderUpgradeable as ERC721Holder } from
    "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import { OwnableUpgradeable as Ownable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { SafeERC20Upgradeable as SafeERC20 } from
    "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import { VotingEscrow } from "@setup/GaugeVoterSetup_v1_4_0.sol";
import { IStrategyNFT } from "src/interfaces/IStrategyNFT.sol";
import { IStrategy } from "src/interfaces/IStrategy.sol";
abstract contract NFTBaseStrategy is Initializable, ERC721Holder, Ownable, IStrategyNFT {
    using SafeERC20 for IERC20;
    /// @notice The ERC20 asset token.
    address internal asset;
    /// @notice The single tokenId that this strategy holds and manages
    uint256 public masterTokenId;
    /// @notice The escrow contract
    VotingEscrow public escrow;
    /// @notice The ERC721 contract for transfering tokenIds from and out of this contract.
    ERC721 public nft;
    modifier masterTokenSet() {
        if (masterTokenId == 0) revert MasterTokenNotSet();
        _;
    }
    /// @dev Initializes the NFT base strategy contract.
    ///      IMPORTANT: It is the caller's responsibility to ensure that _asset and _nft parameters
    ///      match exactly what the _escrow contract uses internally:
    ///      - _asset MUST be the token that _escrow locks (typically obtained via escrow.token())
    ///      - _nft MUST be the NFT contract that _escrow mints (typically obtained via escrow.lockNFT())
    ///
    ///      This explicit parameter passing (rather than reading from escrow) is needed because:
    ///      It Allows initialization flexibility for different escrow implementations.
    function __NFTBaseStrategy_init(
        address _escrow,
        address _asset,
        address _nft,
        address _owner
    )
        internal
        onlyInitializing
    {
        __ERC721Holder_init();
        asset = _asset;
        escrow = VotingEscrow(_escrow);
        nft = ERC721(_nft);
        // `_owner` is the address that will have permission for
        // critical functions related to masterTokenId in this
        // base contract. This `_owner` most times must be vault.
        _transferOwnership(_owner);
    }
    /// @inheritdoc IStrategy
    function deposit(uint256 _amount) public virtual {
        IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount);
        uint256 tokenId = _deposit(_amount);
        emit Deposited(msg.sender, tokenId, _amount);
    }
    /// @inheritdoc IStrategyNFT
    function depositTokenId(uint256 _tokenId) public virtual onlyOwner masterTokenSet {
        // Merge the received token to master token
        escrow.merge(_tokenId, masterTokenId);
        emit TokenIdDeposited(_tokenId, masterTokenId);
    }
    /// @inheritdoc IStrategy
    function withdraw(address _receiver, uint256 _assets) public virtual onlyOwner masterTokenSet returns (uint256) {
        // Split the master token
        uint256 newTokenId = escrow.split(masterTokenId, _assets);
        // Transfer the new token to receiver
        nft.safeTransferFrom(address(this), _receiver, newTokenId);
        emit Withdrawn(_receiver, newTokenId, _assets);
        return newTokenId;
    }
    /// @inheritdoc IStrategyNFT
    function receiveMasterToken(uint256 _masterTokenId) public virtual onlyOwner {
        if (masterTokenId == 0) {
            masterTokenId = _masterTokenId;
            emit MasterTokenReceived(_masterTokenId);
            return;
        }
        if (masterTokenId != _masterTokenId) {
            revert MasterTokenAlreadySet();
        }
    }
    /// @inheritdoc IStrategy
    function retireStrategy() public virtual onlyOwner {
        uint256 tokenId = masterTokenId;
        nft.safeTransferFrom(address(this), msg.sender, tokenId);
        emit StrategyRetired(msg.sender, tokenId);
    }
    /// @notice Returns the total assets managed by the strategy.
    /// @return The total amount of assets locked in the master token.
    function totalAssets() public view virtual returns (uint256) {
        if (masterTokenId == 0) {
            return 0;
        }
        return escrow.locked(masterTokenId).amount;
    }
    /*//////////////////////////////////////////////////////////////
                        Internal/Private
    //////////////////////////////////////////////////////////////*/
    /// @notice Creates a lock and merges it into master.
    function _deposit(uint256 _amount) internal virtual returns (uint256 tokenId) {
        IERC20(asset).approve(address(escrow), _amount);
        tokenId = escrow.createLock(_amount);
        escrow.merge(tokenId, masterTokenId);
    }
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[46] private __gap;
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { IAccessControlManager } from "./interfaces/IAccessControlManager.sol";
/// @title AccessControlManager
/// @author Angle Labs, Inc.
/// @notice This contract handles the access control across all contracts
contract AccessControlManager is IAccessControlManager, Initializable, AccessControlEnumerableUpgradeable {
    /// @notice Role for guardians
    bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
    /// @notice Role for governors
    bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
    // =============================== Events ======================================
    event AccessControlManagerUpdated(address indexed _accessControlManager);
    // =============================== Errors ======================================
    error InvalidAccessControlManager();
    error IncompatibleGovernorAndGuardian();
    error NotEnoughGovernorsLeft();
    error ZeroAddress();
    /// @notice Initializes the `AccessControlManager` contract
    /// @param governor Address of the governor of the Angle Protocol
    /// @param guardian Guardian address of the protocol
    function initialize(address governor, address guardian) public initializer {
        if (governor == address(0) || guardian == address(0)) revert ZeroAddress();
        if (governor == guardian) revert IncompatibleGovernorAndGuardian();
        _setupRole(GOVERNOR_ROLE, governor);
        _setupRole(GUARDIAN_ROLE, guardian);
        _setupRole(GUARDIAN_ROLE, governor);
        _setRoleAdmin(GUARDIAN_ROLE, GOVERNOR_ROLE);
        _setRoleAdmin(GOVERNOR_ROLE, GOVERNOR_ROLE);
    }
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() initializer {}
    // =========================== View Functions ==================================
    /// @inheritdoc IAccessControlManager
    function isGovernor(address admin) external view virtual returns (bool) {
        return hasRole(GOVERNOR_ROLE, admin);
    }
    /// @inheritdoc IAccessControlManager
    function isGovernorOrGuardian(address admin) external view returns (bool) {
        return hasRole(GUARDIAN_ROLE, admin);
    }
    // =========================== Governor Functions ==============================
    /// @notice Adds a governor in the protocol
    /// @param governor Address to grant the role to
    /// @dev It is necessary to call this function to grant a governor role to make sure
    /// all governors also have the guardian role
    function addGovernor(address governor) external {
        grantRole(GOVERNOR_ROLE, governor);
        grantRole(GUARDIAN_ROLE, governor);
    }
    /// @notice Revokes a governor from the protocol
    /// @param governor Address to remove the role to
    /// @dev It is necessary to call this function to remove a governor role to make sure
    /// the address also loses its guardian role
    function removeGovernor(address governor) external {
        if (getRoleMemberCount(GOVERNOR_ROLE) <= 1) revert NotEnoughGovernorsLeft();
        revokeRole(GUARDIAN_ROLE, governor);
        revokeRole(GOVERNOR_ROLE, governor);
    }
    /// @notice Changes the accessControlManager contract of the protocol
    /// @param _accessControlManager New accessControlManager contract
    /// @dev This function verifies that all governors of the current accessControlManager contract are also governors
    /// of the new accessControlManager contract.
    /// @dev Governance wishing to change the accessControlManager contract should also make sure to call `setAccessControlManager`
    function setAccessControlManager(IAccessControlManager _accessControlManager) external onlyRole(GOVERNOR_ROLE) {
        uint256 count = getRoleMemberCount(GOVERNOR_ROLE);
        bool success;
        for (uint256 i; i < count; ++i) {
            success = _accessControlManager.isGovernor(getRoleMember(GOVERNOR_ROLE, i));
            if (!success) break;
        }
        if (!success) revert InvalidAccessControlManager();
        emit AccessControlManagerUpdated(address(_accessControlManager));
    }
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {UUPSHelper} from "./utils/UUPSHelper.sol";
import {IAccessControlManager} from "./interfaces/IAccessControlManager.sol";
import {Errors} from "./utils/Errors.sol";
import {console2 as console} from "forge-std/console2.sol";
struct MerkleTree {
    // Root of a Merkle tree which leaves are `(address user, address token, uint amount)`
    // representing an amount of tokens accumulated by `user`.
    // The Merkle tree is assumed to have only increasing amounts: that is to say if a user can claim 1,
    // then after the amount associated in the Merkle tree for this token should be x > 1
    bytes32 merkleRoot;
    // Ipfs hash of the tree data
    bytes32 ipfsHash;
}
struct Claim {
    uint208 amount;
    uint48 timestamp;
    bytes32 merkleRoot;
}
interface IClaimRecipient {
    /// @notice Hook to call within contracts receiving token rewards on behalf of users
    function onClaim(address user, address token, uint256 amount, bytes memory data) external returns (bytes32);
}
/// @title Distributor
/// @notice Allows to claim rewards distributed to them through Merkl
/// @author Angle Labs. Inc
contract Distributor is UUPSHelper {
    using SafeERC20 for IERC20;
    /// @notice Default epoch duration
    uint32 internal constant _EPOCH_DURATION = 3600;
    /// @notice Success message received when calling a `ClaimRecipient` contract
    bytes32 public constant CALLBACK_SUCCESS = keccak256("IClaimRecipient.onClaim");
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                       VARIABLES                                                    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Tree of claimable tokens through this contract
    MerkleTree public tree;
    /// @notice Tree that was in place in the contract before the last `tree` update
    MerkleTree public lastTree;
    /// @notice Token to deposit to freeze the roots update
    IERC20 public disputeToken;
    /// @notice `AccessControlManager` contract handling access control
    IAccessControlManager public accessControlManager;
    /// @notice Address which created the last dispute
    /// @dev Used to store if there is an ongoing dispute
    address public disputer;
    /// @notice When the current tree becomes valid
    uint48 public endOfDisputePeriod;
    /// @notice Time after which a change in a tree becomes effective, in EPOCH_DURATION
    uint48 public disputePeriod;
    /// @notice Amount to deposit to freeze the roots update
    uint256 public disputeAmount;
    /// @notice Mapping user -> token -> amount to track claimed amounts
    mapping(address => mapping(address => Claim)) public claimed;
    /// @notice Trusted EOAs to update the Merkle root
    mapping(address => uint256) public canUpdateMerkleRoot;
    /// @notice Deprecated mapping
    mapping(address => uint256) public onlyOperatorCanClaim;
    /// @notice User -> Operator -> authorisation to claim on behalf of the user
    mapping(address => mapping(address => uint256)) public operators;
    /// @notice Whether the contract has been made non upgradeable or not
    uint128 public upgradeabilityDeactivated;
    /// @notice Reentrancy status
    uint96 private _status;
    /// @notice Epoch duration for dispute periods (in seconds)
    uint32 internal _epochDuration;
    /// @notice user -> token -> recipient address for when user claims `token`
    /// @dev If the mapping is empty, by default rewards will accrue on the user address
    mapping(address => mapping(address => address)) public claimRecipient;
    uint256[36] private __gap;
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                        EVENTS                                                      
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    event Claimed(address indexed user, address indexed token, uint256 amount);
    event ClaimRecipientUpdated(address indexed user, address indexed token, address indexed recipient);
    event DisputeAmountUpdated(uint256 _disputeAmount);
    event Disputed(string reason);
    event DisputePeriodUpdated(uint48 _disputePeriod);
    event DisputeResolved(bool valid);
    event DisputeTokenUpdated(address indexed _disputeToken);
    event EpochDurationUpdated(uint32 newEpochDuration);
    event OperatorClaimingToggled(address indexed user, bool isEnabled);
    event OperatorToggled(address indexed user, address indexed operator, bool isWhitelisted);
    event Recovered(address indexed token, address indexed to, uint256 amount);
    event Revoked(); // With this event an indexer could maintain a table (timestamp, merkleRootUpdate)
    event TreeUpdated(bytes32 merkleRoot, bytes32 ipfsHash, uint48 endOfDisputePeriod);
    event TrustedToggled(address indexed eoa, bool trust);
    event UpgradeabilityRevoked();
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                       MODIFIERS                                                    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Checks whether the `msg.sender` has the governor role
    modifier onlyGovernor() {
        if (!accessControlManager.isGovernor(msg.sender)) revert Errors.NotGovernor();
        _;
    }
    /// @notice Checks whether the `msg.sender` is the `user` address or is a trusted address
    modifier onlyTrustedOrUser(address user) {
        if (
            user != msg.sender && canUpdateMerkleRoot[msg.sender] != 1
                && !accessControlManager.isGovernorOrGuardian(msg.sender)
        ) revert Errors.NotTrusted();
        _;
    }
    /// @notice Checks whether the contract is upgradeable or whether the caller is allowed to upgrade the contract
    modifier onlyUpgradeableInstance() {
        if (upgradeabilityDeactivated == 1) revert Errors.NotUpgradeable();
        else if (!accessControlManager.isGovernor(msg.sender)) revert Errors.NotGovernor();
        _;
    }
    /// @notice Checks whether a call is reentrant or not
    modifier nonReentrant() {
        if (_status == 2) revert Errors.ReentrantCall();
        // Any calls to nonReentrant after this point will fail
        _status = 2;
        _;
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = 1;
    }
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                      CONSTRUCTOR                                                   
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    constructor() initializer {}
    function initialize(IAccessControlManager _accessControlManager) external initializer {
        if (address(_accessControlManager) == address(0)) revert Errors.ZeroAddress();
        accessControlManager = _accessControlManager;
    }
    /// @inheritdoc UUPSHelper
    function _authorizeUpgrade(address) internal view override onlyUpgradeableInstance {}
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                    MAIN FUNCTIONS                                                  
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Claims rewards for a given set of users
    /// @dev Unless another address has been approved for claiming, only an address can claim for itself
    /// @param users Addresses for which claiming is taking place
    /// @param tokens ERC20 token claimed
    /// @param amounts Amount of tokens that will be sent to the corresponding users
    /// @param proofs Array of hashes bridging from a leaf `(hash of user | token | amount)` to the Merkle root
    function claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs
    ) external {
        address[] memory recipients = new address[](users.length);
        bytes[] memory datas = new bytes[](users.length);
        _claim(users, tokens, amounts, proofs, recipients, datas);
    }
    /// @notice Same as the function above except that for each token claimed, the caller may set different
    /// recipients for rewards and pass arbitrary data to the reward recipient on claim
    /// @dev Only a `msg.sender` calling for itself can set a different recipient for the token rewards
    /// within the context of a call to claim
    /// @dev Non-zero recipient addresses given by the `msg.sender` can override any previously set reward address
    function claimWithRecipient(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs,
        address[] calldata recipients,
        bytes[] memory datas
    ) external {
        _claim(users, tokens, amounts, proofs, recipients, datas);
    }
    /// @notice Returns the Merkle root that is currently live for the contract
    function getMerkleRoot() public view returns (bytes32) {
        if (block.timestamp >= endOfDisputePeriod && disputer == address(0)) return tree.merkleRoot;
        else return lastTree.merkleRoot;
    }
    function getEpochDuration() public view returns (uint32 epochDuration) {
        epochDuration = _epochDuration;
        if (epochDuration == 0) epochDuration = _EPOCH_DURATION;
    }
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                 USER ADMIN FUNCTIONS                                               
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Toggles whitelisting for a given user and a given operator
    /// @dev When an operator is whitelisted for a user, the operator can claim rewards on behalf of the user
    function toggleOperator(address user, address operator) external onlyTrustedOrUser(user) {
        uint256 oldValue = operators[user][operator];
        operators[user][operator] = 1 - oldValue;
        emit OperatorToggled(user, operator, oldValue == 0);
    }
    /// @notice Sets a recipient for a user claiming rewards for a token
    /// @dev This is an optional functionality and if the `recipient` is set to the zero address, then
    /// the user will still accrue all rewards to its address
    /// @dev Users may still specify a different recipient when they claim token rewards with the
    /// `claimWithRecipient` function
    function setClaimRecipient(address recipient, address token) external {
        claimRecipient[msg.sender][token] = recipient;
        emit ClaimRecipientUpdated(msg.sender, recipient, token);
    }
    /// @notice Freezes the Merkle tree update until the dispute is resolved
    /// @dev Requires a deposit of `disputeToken` that'll be slashed if the dispute is not accepted
    /// @dev It is only possible to create a dispute within `disputePeriod` after each tree update
    function disputeTree(string memory reason) external {
        if (disputer != address(0)) revert Errors.UnresolvedDispute();
        if (block.timestamp >= endOfDisputePeriod) revert Errors.InvalidDispute();
        IERC20(disputeToken).safeTransferFrom(msg.sender, address(this), disputeAmount);
        disputer = msg.sender;
        emit Disputed(reason);
    }
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                 GOVERNANCE FUNCTIONS                                               
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Updates the Merkle tree
    function updateTree(MerkleTree calldata _tree) external {
        if (
            // A trusted address cannot update a tree right after a precedent tree update otherwise it can de facto
            // validate a tree which has not passed the dispute period
            disputer != address(0)
                || (
                    (canUpdateMerkleRoot[msg.sender] != 1 || block.timestamp < endOfDisputePeriod)
                        && !accessControlManager.isGovernor(msg.sender)
                )
        ) revert Errors.NotTrusted();
        MerkleTree memory _lastTree = tree;
        tree = _tree;
        lastTree = _lastTree;
        uint48 _endOfPeriod = _endOfDisputePeriod(uint48(block.timestamp));
        endOfDisputePeriod = _endOfPeriod;
        emit TreeUpdated(_tree.merkleRoot, _tree.ipfsHash, _endOfPeriod);
    }
    /// @notice Adds or removes addresses which are trusted to update the Merkle root
    function toggleTrusted(address trustAddress) external onlyGovernor {
        uint256 trustedStatus = 1 - canUpdateMerkleRoot[trustAddress];
        canUpdateMerkleRoot[trustAddress] = trustedStatus;
        emit TrustedToggled(trustAddress, trustedStatus == 1);
    }
    /// @notice Prevents future contract upgrades
    function revokeUpgradeability() external onlyGovernor {
        upgradeabilityDeactivated = 1;
        emit UpgradeabilityRevoked();
    }
    /// @notice Updates the epoch duration period
    function setEpochDuration(uint32 epochDuration) external onlyGovernor {
        _epochDuration = epochDuration;
        emit EpochDurationUpdated(epochDuration);
    }
    /// @notice Resolve the ongoing dispute, if any
    /// @param valid Whether the dispute was valid
    function resolveDispute(bool valid) external onlyGovernor {
        if (disputer == address(0)) revert Errors.NoDispute();
        if (valid) {
            IERC20(disputeToken).safeTransfer(disputer, disputeAmount);
            // If a dispute is valid, the contract falls back to the last tree that was updated
            _revokeTree();
        } else {
            IERC20(disputeToken).safeTransfer(msg.sender, disputeAmount);
            endOfDisputePeriod = _endOfDisputePeriod(uint48(block.timestamp));
        }
        disputer = address(0);
        emit DisputeResolved(valid);
    }
    /// @notice Allows the governor of this contract to fallback to the last version of the tree
    /// immediately
    function revokeTree() external onlyGovernor {
        if (disputer != address(0)) revert Errors.UnresolvedDispute();
        _revokeTree();
    }
    /// @notice Recovers any ERC20 token left on the contract
    function recoverERC20(address tokenAddress, address to, uint256 amountToRecover) external onlyGovernor {
        IERC20(tokenAddress).safeTransfer(to, amountToRecover);
        emit Recovered(tokenAddress, to, amountToRecover);
    }
    /// @notice Sets the dispute period after which a tree update becomes effective
    function setDisputePeriod(uint48 _disputePeriod) external onlyGovernor {
        disputePeriod = uint48(_disputePeriod);
        emit DisputePeriodUpdated(_disputePeriod);
    }
    /// @notice Sets the token used as a caution during disputes
    function setDisputeToken(IERC20 _disputeToken) external onlyGovernor {
        if (disputer != address(0)) revert Errors.UnresolvedDispute();
        disputeToken = _disputeToken;
        emit DisputeTokenUpdated(address(_disputeToken));
    }
    /// @notice Sets the amount of `disputeToken` used as a caution during disputes
    function setDisputeAmount(uint256 _disputeAmount) external onlyGovernor {
        if (disputer != address(0)) revert Errors.UnresolvedDispute();
        disputeAmount = _disputeAmount;
        emit DisputeAmountUpdated(_disputeAmount);
    }
    /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                                   INTERNAL HELPERS                                                 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/
    /// @notice Internal version of `claimWithRecipient`
    function _claim(
        address[] calldata users,
        address[] calldata tokens,
        uint256[] calldata amounts,
        bytes32[][] calldata proofs,
        address[] memory recipients,
        bytes[] memory datas
    ) internal nonReentrant {
        uint256 usersLength = users.length;
        if (
            usersLength == 0 || usersLength != tokens.length || usersLength != amounts.length
                || usersLength != proofs.length || usersLength != recipients.length || usersLength != datas.length
        ) revert Errors.InvalidLengths();
        for (uint256 i; i < usersLength;) {
            address user = users[i];
            address token = tokens[i];
            uint256 amount = amounts[i];
            bytes memory data = datas[i];
            // Only approved operator can claim for `user`
            if (msg.sender != user && tx.origin != user && operators[user][msg.sender] == 0) {
                revert Errors.NotWhitelisted();
            }
            // Verifying proof
            bytes32 leaf = keccak256(abi.encode(user, token, amount));
            if (!_verifyProof(leaf, proofs[i])) revert Errors.InvalidProof();
            // Closing reentrancy gate here
            uint256 toSend = amount - claimed[user][token].amount;
            claimed[user][token] = Claim(SafeCast.toUint208(amount), uint48(block.timestamp), getMerkleRoot());
            emit Claimed(user, token, toSend);
            address recipient = recipients[i];
            // Only `msg.sender` can set a different recipient for itself within the context of a call to claim
            // The recipient set in the context of the call to `claim` can override the default recipient set by the user
            if (msg.sender != user || recipient == address(0)) {
                address userSetRecipient = claimRecipient[user][token];
                if (userSetRecipient == address(0)) recipient = user;
                else recipient = userSetRecipient;
            }
            if (toSend != 0) {
                IERC20(token).safeTransfer(recipient, toSend);
                if (data.length != 0) {
                    try IClaimRecipient(recipient).onClaim(user, token, amount, data) returns (bytes32 callbackSuccess)
                    {
                        if (callbackSuccess != CALLBACK_SUCCESS) revert Errors.InvalidReturnMessage();
                    } catch {}
                }
            }
            unchecked {
                ++i;
            }
        }
    }
    /// @notice Fallback to the last version of the tree
    function _revokeTree() internal {
        MerkleTree memory _tree = lastTree;
        endOfDisputePeriod = 0;
        tree = _tree;
        uint32 epochDuration = getEpochDuration();
        emit Revoked();
        emit TreeUpdated(
            _tree.merkleRoot,
            _tree.ipfsHash,
            (uint48(block.timestamp) / epochDuration) * (epochDuration) // Last hour
        );
    }
    /// @notice Returns the end of the dispute period
    /// @dev treeUpdate is rounded up to next hour and then `disputePeriod` hours are added
    function _endOfDisputePeriod(uint48 treeUpdate) internal view returns (uint48) {
        uint32 epochDuration = getEpochDuration();
        return ((treeUpdate - 1) / epochDuration + 1 + disputePeriod) * (epochDuration);
    }
    /// @notice Checks the validity of a proof
    /// @param leaf Hashed leaf data, the starting point of the proof
    /// @param proof Array of hashes forming a hash chain from leaf to root
    /// @return true If proof is correct, else false
    function _verifyProof(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) {
        bytes32 currentHash = leaf;
        uint256 proofLength = proof.length;
        for (uint256 i; i < proofLength;) {
            if (currentHash < proof[i]) {
                currentHash = keccak256(abi.encode(currentHash, proof[i]));
            } else {
                currentHash = keccak256(abi.encode(proof[i], currentHash));
            }
            unchecked {
                ++i;
            }
        }
        bytes32 root = getMerkleRoot();
        if (root == bytes32(0)) revert Errors.InvalidUninitializedRoot();
        return currentHash == root;
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface 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[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IClock.sol";
interface IClockV1_2_0 is IClock {
    function epochPrevCheckpointTs() external view returns (uint256);
    function resolveEpochPrevCheckpointTs(uint256 timestamp) external pure returns (uint256);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IGaugeVoter.sol";
interface IAddressGaugeVote {
    /// @param votes gauge => votes cast at that time
    /// @param gaugesVotedFor array of gauges we have active votes for
    /// @param usedVotingPower total voting power used at the time of the vote
    /// @dev this changes so we need an historic snapshot
    /// @param lastVoted is the last time the user voted
    struct AddressVoteData {
        mapping(address => uint256) voteWeights;
        address[] gaugesVotedFor;
        uint256 usedVotingPower;
        uint256 lastVoted;
    }
    /// @param weight proportion of voting power the address will allocate to the gauge. Will be normalised.
    /// @param gauge address of the gauge to vote for
    struct GaugeVote {
        uint256 weight;
        address gauge;
    }
}
/*///////////////////////////////////////////////////////////////
                            Gauge Voter
//////////////////////////////////////////////////////////////*/
interface IAddressGaugeVoterEvents {
    /// @param votingPowerCastForGauge votes cast by this address for this gauge in this vote
    /// @param totalVotingPowerInGauge total voting power in the gauge at the time of the vote, after applying the vote
    /// @param totalVotingPowerInContract total voting power in the contract at the time of the vote, after applying the vote
    event Voted(
        address indexed voter,
        address indexed gauge,
        uint256 indexed epoch,
        uint256 votingPowerCastForGauge,
        uint256 totalVotingPowerInGauge,
        uint256 totalVotingPowerInContract,
        uint256 timestamp
    );
    /// @param votingPowerRemovedFromGauge votes removed by this address for this gauge, at the time of this rest
    /// @param totalVotingPowerInGauge total voting power in the gauge at the time of the reset, after applying the reset
    /// @param totalVotingPowerInContract total voting power in the contract at the time of the reset, after applying the reset
    event Reset(
        address indexed voter,
        address indexed gauge,
        uint256 indexed epoch,
        uint256 votingPowerRemovedFromGauge,
        uint256 totalVotingPowerInGauge,
        uint256 totalVotingPowerInContract,
        uint256 timestamp
    );
}
interface IAddressGaugeVoterErrors {
    error VotingInactive();
    error NotApprovedOrOwner();
    error GaugeDoesNotExist(address _pool);
    error GaugeInactive(address _gauge);
    error DoubleVote();
    error NoVotes();
    error NoVotingPower();
    error NotCurrentlyVoting();
    error OnlyEscrow();
    error UpdateVotingPowerHookNotEnabled();
    error AlreadyVoted(address _address);
}
interface IAddressGaugeVoter is
    IAddressGaugeVoterEvents,
    IAddressGaugeVoterErrors,
    IAddressGaugeVote,
    IGaugeManager,
    IGauge
{
    /// @notice Called by users to vote for pools. Votes distributed proportionally based on weights.
    /// @param _votes       Array of votes to be cast, contains gauge address and weight.
    function vote(GaugeVote[] memory _votes) external;
    /// @notice Called by users to reset voting state. Required when withdrawing or transferring veNFT.
    function reset() external;
    /// @notice Can be called to check if an address is currently voting
    function isVoting(address _address) external view returns (bool);
    function updateVotingPower(address _from, address _to) external;
}
/*///////////////////////////////////////////////////////////////
                      Address Gauge Voter
//////////////////////////////////////////////////////////////*/
interface IAddressGaugeVoterStorageEventsErrors is
    IGaugeManagerEvents,
    IGaugeManagerErrors,
    IAddressGaugeVoterEvents,
    IAddressGaugeVoterErrors
{
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.
    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;
    uint256 private _status;
    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }
    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
        // 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;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;
/**
 * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
 *
 * _Available since v4.5._
 */
interface IVotesUpgradeable {
    /**
     * @dev Emitted when an account changes their delegate.
     */
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
    /**
     * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
     */
    event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
    /**
     * @dev Returns the current amount of votes that `account` has.
     */
    function getVotes(address account) external view returns (uint256);
    /**
     * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     */
    function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
    /**
     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     *
     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
     * Votes that have not been delegated are still part of total supply, even though they would not participate in a
     * vote.
     */
    function getPastTotalSupply(uint256 timepoint) external view returns (uint256);
    /**
     * @dev Returns the delegate that `account` has chosen.
     */
    function delegates(address account) external view returns (address);
    /**
     * @dev Delegates votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) external;
    /**
     * @dev Delegates votes from signer to `delegatee`.
     */
    function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {IERC1822ProxiableUpgradeable} from "@openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol";
import {ERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import {ERC165CheckerUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol";
import {IProtocolVersion} from "../utils/versioning/IProtocolVersion.sol";
import {ProtocolVersion} from "../utils/versioning/ProtocolVersion.sol";
import {DaoAuthorizableUpgradeable} from "../permission/auth/DaoAuthorizableUpgradeable.sol";
import {IPlugin} from "./IPlugin.sol";
import {IDAO} from "../dao/IDAO.sol";
import {IExecutor, Action} from "../executors/IExecutor.sol";
/// @title PluginUUPSUpgradeable
/// @author Aragon X - 2022-2024
/// @notice An abstract, upgradeable contract to inherit from when creating a plugin being deployed via the UUPS pattern (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
/// @custom:security-contact [email protected]
abstract contract PluginUUPSUpgradeable is
    IPlugin,
    ERC165Upgradeable,
    UUPSUpgradeable,
    DaoAuthorizableUpgradeable,
    ProtocolVersion
{
    using ERC165CheckerUpgradeable for address;
    // NOTE: When adding new state variables to the contract, the size of `_gap` has to be adapted below as well.
    /// @notice Stores the current target configuration, defining the target contract and operation type for a plugin.
    TargetConfig private currentTargetConfig;
    /// @notice Thrown when target is of type 'IDAO', but operation is `delegateCall`.
    /// @param targetConfig The target config to update it to.
    error InvalidTargetConfig(TargetConfig targetConfig);
    /// @notice Thrown when `delegatecall` fails.
    error DelegateCallFailed();
    /// @notice Thrown when initialize is called after it has already been executed.
    error AlreadyInitialized();
    /// @notice Emitted each time the TargetConfig is set.
    event TargetSet(TargetConfig newTargetConfig);
    /// @notice The ID of the permission required to call the `setTargetConfig` function.
    bytes32 public constant SET_TARGET_CONFIG_PERMISSION_ID =
        keccak256("SET_TARGET_CONFIG_PERMISSION");
    /// @notice The ID of the permission required to call the `_authorizeUpgrade` function.
    bytes32 public constant UPGRADE_PLUGIN_PERMISSION_ID = keccak256("UPGRADE_PLUGIN_PERMISSION");
    /// @notice Disables the initializers on the implementation contract to prevent it from being left uninitialized.
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }
    /// @notice This ensures that the initialize function cannot be called during the upgrade process.
    modifier onlyCallAtInitialization() {
        if (_getInitializedVersion() != 0) {
            revert AlreadyInitialized();
        }
        _;
    }
    /// @inheritdoc IPlugin
    function pluginType() public pure override returns (PluginType) {
        return PluginType.UUPS;
    }
    /// @notice Returns the currently set target contract.
    /// @return TargetConfig The currently set target.
    function getCurrentTargetConfig() public view virtual returns (TargetConfig memory) {
        return currentTargetConfig;
    }
    /// @notice A convenient function to get current target config only if its target is not address(0), otherwise dao().
    /// @return TargetConfig The current target config if its target is not address(0), otherwise returns dao()."
    function getTargetConfig() public view virtual returns (TargetConfig memory) {
        TargetConfig memory targetConfig = currentTargetConfig;
        if (targetConfig.target == address(0)) {
            targetConfig = TargetConfig({target: address(dao()), operation: Operation.Call});
        }
        return targetConfig;
    }
    /// @notice Initializes the plugin by storing the associated DAO.
    /// @param _dao The DAO contract.
    // solhint-disable-next-line func-name-mixedcase
    function __PluginUUPSUpgradeable_init(IDAO _dao) internal virtual onlyInitializing {
        __DaoAuthorizableUpgradeable_init(_dao);
    }
    /// @dev Sets the target to a new target (`newTarget`).
    ///      The caller must have the `SET_TARGET_CONFIG_PERMISSION_ID` permission.
    /// @param _targetConfig The target Config containing the address and operation type.
    function setTargetConfig(
        TargetConfig calldata _targetConfig
    ) public auth(SET_TARGET_CONFIG_PERMISSION_ID) {
        _setTargetConfig(_targetConfig);
    }
    /// @notice Checks if an interface is supported by this or its parent contract.
    /// @param _interfaceId The ID of the interface.
    /// @return Returns `true` if the interface is supported.
    function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
        return
            _interfaceId == type(IPlugin).interfaceId ||
            _interfaceId == type(IProtocolVersion).interfaceId ||
            _interfaceId == type(IERC1822ProxiableUpgradeable).interfaceId ||
            _interfaceId ==
            this.setTargetConfig.selector ^
                this.getTargetConfig.selector ^
                this.getCurrentTargetConfig.selector ||
            super.supportsInterface(_interfaceId);
    }
    /// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
    /// @return The address of the implementation contract.
    function implementation() public view returns (address) {
        return _getImplementation();
    }
    /// @notice Sets the target to a new target (`newTarget`).
    /// @param _targetConfig The target Config containing the address and operation type.
    function _setTargetConfig(TargetConfig memory _targetConfig) internal virtual {
        // safety check to avoid setting dao as `target` with `delegatecall` operation
        // as this would not work and cause the plugin to be bricked.
        if (
            _targetConfig.target.supportsInterface(type(IDAO).interfaceId) &&
            _targetConfig.operation == Operation.DelegateCall
        ) {
            revert InvalidTargetConfig(_targetConfig);
        }
        currentTargetConfig = _targetConfig;
        emit TargetSet(_targetConfig);
    }
    /// @notice Forwards the actions to the currently set `target` for the execution.
    /// @dev If target is not set, passes actions to the dao.
    /// @param _callId Identifier for this execution.
    /// @param _actions actions that will be eventually called.
    /// @param _allowFailureMap Bitmap-encoded number.
    /// @return execResults address of the implementation contract.
    /// @return failureMap address of the implementation contract.
    function _execute(
        bytes32 _callId,
        Action[] memory _actions,
        uint256 _allowFailureMap
    ) internal virtual returns (bytes[] memory execResults, uint256 failureMap) {
        TargetConfig memory targetConfig = getTargetConfig();
        return
            _execute(
                targetConfig.target,
                _callId,
                _actions,
                _allowFailureMap,
                targetConfig.operation
            );
    }
    /// @notice Forwards the actions to the `target` for the execution.
    /// @param _target The address of the target contract.
    /// @param _callId Identifier for this execution.
    /// @param _actions actions that will be eventually called.
    /// @param _allowFailureMap A bitmap allowing the execution to succeed, even if individual actions might revert.
    ///     If the bit at index `i` is 1, the execution succeeds even if the `i`th action reverts.
    ///     A failure map value of 0 requires every action to not revert.
    /// @param _op The type of operation (`Call` or `DelegateCall`) to be used for the execution.
    /// @return execResults address of the implementation contract.
    /// @return failureMap address of the implementation contract.
    function _execute(
        address _target,
        bytes32 _callId,
        Action[] memory _actions,
        uint256 _allowFailureMap,
        Operation _op
    ) internal virtual returns (bytes[] memory execResults, uint256 failureMap) {
        if (_op == Operation.DelegateCall) {
            bool success;
            bytes memory data;
            // solhint-disable-next-line avoid-low-level-calls
            (success, data) = _target.delegatecall(
                abi.encodeCall(IExecutor.execute, (_callId, _actions, _allowFailureMap))
            );
            if (!success) {
                if (data.length > 0) {
                    // solhint-disable-next-line no-inline-assembly
                    assembly {
                        let returndata_size := mload(data)
                        revert(add(32, data), returndata_size)
                    }
                } else {
                    revert DelegateCallFailed();
                }
            }
            (execResults, failureMap) = abi.decode(data, (bytes[], uint256));
        } else {
            (execResults, failureMap) = IExecutor(_target).execute(
                _callId,
                _actions,
                _allowFailureMap
            );
        }
    }
    /// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
    /// @dev The caller must have the `UPGRADE_PLUGIN_PERMISSION_ID` permission.
    function _authorizeUpgrade(
        address
    )
        internal
        virtual
        override
        auth(UPGRADE_PLUGIN_PERMISSION_ID)
    // solhint-disable-next-line no-empty-blocks
    {
    }
    /// @notice This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain (see [OpenZeppelin's guide about storage gaps](https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps)).
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @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
pragma solidity ^0.8.0;
import {
    IERC721Enumerable
} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IERC721EnumerableMintableBurnable is IERC721Enumerable {
    function mint(address to, uint256 tokenId) external;
    function burn(uint256 tokenId) external;
    function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IEscrowCurveIncreasing.sol";
import "../IDeprecated.sol";
/*///////////////////////////////////////////////////////////////
                        Global Curve
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveGlobalStorage {
    /// @notice Captures the shape of the aggregate voting curve at a specific point in time
    /// @param bias The y intercept of the aggregate voting curve at the given time
    /// @param slope The slope of the aggregate voting curve at the given time
    /// @param writtenTs The timestamp at which the we last updated the aggregate voting curve
    struct GlobalPoint {
        int256 bias;
        int256 slope;
        uint48 writtenTs;
    }
}
interface IEscrowCurveGlobal is IEscrowCurveGlobalStorage {
    /// @notice Returns the global point at the passed epoch
    /// @param _index The index in an array to return the point for
    function globalPointHistory(uint256 _index) external view returns (GlobalPoint memory);
}
/*///////////////////////////////////////////////////////////////
                        Token Curve
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveTokenV1_2_0 is IEscrowCurveTokenStorage {
    /// @notice Returns the latest index of the tokenId which can be used
    ///         to retrive token point from `tokenPointHistory` function.
    /// @dev This has been renamed to `tokenPointLatestIndex` in the latest upgrade, but
    ///      for backwards-compatibility, the function still stays in the contract.
    ///      Note that we treat it as deprecated, So use `tokenPointLatestIndex` instead.
    /// @return The latest index of the token id.
    function tokenPointIntervals(uint256 _tokenId) external view returns (uint256);
    /// @notice Returns the latest index of the tokenId which can be used
    ///         to retrive token point from `tokenPointHistory` function.
    /// @param _tokenId The NFT to return the latest token point index
    /// @return The latest index of the token id.
    function tokenPointLatestIndex(uint256 _tokenId) external view returns (uint256);
    /// @notice Returns the TokenPoint at the passed `_index`.
    /// @param _tokenId The NFT to return the TokenPoint for
    /// @param _index The index to return the TokenPoint at.
    function tokenPointHistory(
        uint256 _tokenId,
        uint256 _index
    ) external view returns (TokenPoint memory);
}
interface IEscrowCurveMaxTime is IEscrowCurveErrorsAndEvents {
    /// @return The max time allowed for the lock duration.
    function maxTime() external view returns (uint256);
}
/*///////////////////////////////////////////////////////////////
                        INCREASING CURVE
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveIncreasingV1_2_0 is
    IEscrowCurveCore,
    IEscrowCurveMath,
    IEscrowCurveTokenV1_2_0,
    IEscrowCurveMaxTime,
    IEscrowCurveGlobal,
    IDeprecated
{}
interface IEscrowCurveIncreasingV1_2_0_NoSupply is
    IEscrowCurveCore,
    IEscrowCurveMath,
    IEscrowCurveTokenV1_2_0,
    IEscrowCurveMaxTime,
    IDeprecated
{}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IExitQueueCoreErrorsAndEvents {
    error OnlyEscrow();
    error AlreadyQueued();
    error ZeroAddress();
    error CannotExit();
    error NoLockBalance();
    event ExitQueued(uint256 indexed tokenId, address indexed holder, uint256 exitDate);
    event Exit(uint256 indexed tokenId, uint256 fee);
}
interface ITicket {
    struct Ticket {
        address holder;
        uint256 exitDate;
    }
}
/*///////////////////////////////////////////////////////////////
                        Fee Collection
//////////////////////////////////////////////////////////////*/
interface IExitQueueFeeErrorsAndEvents {
    error FeeTooHigh(uint256 maxFee);
    event Withdraw(address indexed to, uint256 amount);
    event FeePercentSet(uint256 feePercent);
}
interface IExitQueueFee is IExitQueueFeeErrorsAndEvents {
    /// @notice optional fee charged for exiting the queue
    function feePercent() external view returns (uint256);
    /// @notice The exit queue manager can set the fee
    function setFeePercent(uint256 _fee) external;
    /// @notice withdraw accumulated fees
    function withdraw(uint256 _amount) external;
}
/*///////////////////////////////////////////////////////////////
                        Cooldown
//////////////////////////////////////////////////////////////*/
interface IExitQueueCooldownErrorsAndEvents {
    error CooldownTooHigh();
    event CooldownSet(uint48 cooldown);
}
interface IExitQueueCooldown is IExitQueueCooldownErrorsAndEvents {
    /// @notice time in seconds between exit and withdrawal
    function cooldown() external view returns (uint48);
    /// @notice The exit queue manager can set the cooldown period
    /// @param _cooldown time in seconds between exit and withdrawal
    function setCooldown(uint48 _cooldown) external;
}
/*///////////////////////////////////////////////////////////////
                        Min Lock
//////////////////////////////////////////////////////////////*/
interface IExitMinLockCooldownErrorsAndEvents {
    event MinLockSet(uint48 minLock);
    error MinLockOutOfBounds();
    error MinLockNotReached(uint256 tokenId, uint48 minLock, uint48 earliestExitDate);
}
interface IExitQueueMinLock is IExitMinLockCooldownErrorsAndEvents {
    /// @notice minimum time from the original lock date before one can enter the queue
    function minLock() external view returns (uint48);
    /// @notice The exit queue manager can set the minimum lock time
    function setMinLock(uint48 _cooldown) external;
}
/*///////////////////////////////////////////////////////////////
                        Exit Queue
//////////////////////////////////////////////////////////////*/
interface IExitQueueCancelErrorsAndEvents {
    error CannotCancelExit();
    event ExitCancelled(uint256 indexed tokenId, address indexed holder);
}
interface IExitQueueCancel {
    function cancelExit(uint256 _tokenId) external;
}
/*///////////////////////////////////////////////////////////////
                        Exit Queue
//////////////////////////////////////////////////////////////*/
interface IExitQueueErrorsAndEvents is
    IExitQueueCoreErrorsAndEvents,
    IExitQueueFeeErrorsAndEvents,
    IExitQueueCooldownErrorsAndEvents,
    IExitMinLockCooldownErrorsAndEvents,
    IExitQueueCancelErrorsAndEvents
{}
interface IExitQueue is
    IExitQueueErrorsAndEvents,
    ITicket,
    IExitQueueFee,
    IExitQueueCooldown,
    IExitQueueMinLock,
    IExitQueueCancel
{
    /// @notice tokenId => Ticket
    function queue(uint256 _tokenId) external view returns (Ticket memory);
    /// @notice queue an exit for a given tokenId, granting the ticket to the passed holder
    /// @param _tokenId the tokenId to queue an exit for
    /// @param _ticketHolder the address that will be granted the ticket
    function queueExit(uint256 _tokenId, address _ticketHolder) external;
    function cancelExit(uint256 _tokenId) external;
    /// @notice exit the queue for a given tokenId. Requires the cooldown period to have passed
    /// @return exitAmount the amount of tokens that can be withdrawn
    function exit(uint256 _tokenId) external returns (uint256 exitAmount);
    /// @return true if the tokenId corresponds to a valid ticket and the cooldown period has passed
    function canExit(uint256 _tokenId) external view returns (bool);
    /// @return the ticket holder for a given tokenId
    function ticketHolder(uint256 _tokenId) external view returns (address);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IVotingEscrowIncreasing.sol";
import {IEscrowIVotesAdapter, IDelegateUpdateVotingPower} from "@delegation/IEscrowIVotesAdapter.sol";
interface IVotingEscrowExiting {
    /// @notice How much amount has been exiting.
    /// @return total The total amount for which beginWithdrawal has been called
    ///         but withdraw has not yet been executed.
    function currentExitingAmount() external view returns (uint256);
}
interface IMergeEventsAndErrors {
    event Merged(
        address indexed _sender,
        uint256 indexed _from,
        uint256 indexed _to,
        uint208 _amountFrom,
        uint208 _amountTo,
        uint208 _amountFinal
    );
    error CannotMerge(uint256 _from, uint256 _to);
    error SameNFT();
}
interface IMerge is ILockedBalanceIncreasing, IMergeEventsAndErrors {
    /// @notice Merge two tokens - i.e  `from` into `_to`.
    /// @param _from The token id from which merge is occuring
    /// @param _to The token id to which `_from` is merging
    function merge(uint256 _from, uint256 _to) external;
    /// @notice Whether 2 tokens can be merged.
    /// @param _from The token id from which merge should occur.
    /// @param _to The token id to which `_from` should merge.
    function canMerge(
        LockedBalance memory _from,
        LockedBalance memory _to
    ) external view returns (bool);
}
interface ISplitEventsAndErrors {
    event Split(
        uint256 indexed _from,
        uint256 indexed newTokenId,
        address _sender,
        uint208 _splitAmount1,
        uint208 _splitAmount2
    );
    event SplitWhitelistSet(address indexed account, bool status);
    error SplitNotWhitelisted();
    error SplitAmountTooBig();
}
interface ISplit is ISplitEventsAndErrors {
    /// @notice Split token into two new, separate tokens.
    /// @param _from The token id that should be split
    /// @param _value The amount that determines how token is split
    /// @return _newTokenId The new token id after split.
    function split(
        uint256 _from,
        uint256 _value
    ) external returns (uint256 _newTokenId);
}
interface IDelegateMoveVoteCaller {
    /// @notice After a token transfer, decreases `_from`'s voting power and increases `_to`'s voting power.
    /// @dev Called upon a token transfer.
    /// @param _from The current delegatee of `_tokenId`.
    /// @param _to The new delegatee of `_tokenId`
    /// @param _tokenId The token id that is being transferred.
    function moveDelegateVotes(
        address _from,
        address _to,
        uint256 _tokenId
    ) external;
}
interface IVotingEscrowIncreasingV1_2_0 is
    IVotingEscrowIncreasing,
    IVotingEscrowExiting,
    IMerge,
    ISplit,
    IDelegateUpdateVotingPower,
    IDelegateMoveVoteCaller
{}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
 * @dev Wrappers over Solidity's uintXX/intXX 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.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCastUpgradeable {
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }
    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        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
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }
    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {
    IVotesUpgradeable
} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
import {ILockedBalanceIncreasing} from "@escrow/IVotingEscrowIncreasing.sol";
interface IEscrowIVotesAdapterErrorsAndEvents {
    event AutoDelegationDisabledSet(address indexed delegate, bool enabled);
    event TokensDelegated(address indexed sender, address indexed delegatee, uint256[] tokenIds);
    event TokensUndelegated(address indexed sender, address indexed delegatee, uint256[] tokenIds);
    error OnlyEscrow();
    error DelegateBySigNotSupported();
    error NotApprovedOrOwner();
    error InvalidTokenId();
    error DelegationNotAllowed();
    error DelegateeNotSet();
    error TokenAlreadyDelegated(uint256 tokenId);
    error TokenNotDelegated(uint256 tokenId);
    error VotingPowerZero(uint256 tokenId);
    error TokenListEmpty();
    error ZeroTransition();
}
interface IDelegateMoveVoteRecipient {
    struct TokenLock {
        address account;
        uint256 tokenId;
        ILockedBalanceIncreasing.LockedBalance locked;
    }
    /// @notice The hook function that is called upon `split`.
    function splitDelegateVotes(TokenLock calldata _from, TokenLock calldata _to) external;
    /// @notice The hook function that is called upon `merge`.
    function mergeDelegateVotes(TokenLock calldata _from, TokenLock calldata _to) external;
    /// @notice After a token transfer, decreases `_from`'s voting power and increases `_to`'s voting power.
    /// @dev Called upon a token transfer or create lock.
    /// @param _from The current delegatee of `_tokenId`.
    /// @param _to The new delegatee of `_tokenId`
    /// @param _tokenId The token id that is being transferred.
    /// @param _locked The lock data of the token.
    function moveDelegateVotes(
        address _from,
        address _to,
        uint256 _tokenId,
        ILockedBalanceIncreasing.LockedBalance memory _locked
    ) external;
}
interface IDelegateUpdateVotingPower {
    /// @notice Updates current voting power of `_from` and `_to`.
    /// @dev Called upon a token transfer and delegate/undelegate.
    function updateVotingPower(address _from, address _to) external;
}
interface IEscrowIVotesAdapterStorage {
    struct GlobalPoint {
        int256 bias;
        int256 slope;
        uint48 writtenTs;
    }
}
interface IEscrowIVotesAdapter is
    IEscrowIVotesAdapterErrorsAndEvents,
    IEscrowIVotesAdapterStorage,
    IDelegateMoveVoteRecipient,
    IVotesUpgradeable
{
    /// @notice Allows to delegate `_tokenIds` to the current delegatee
    ///         which is set by IVotes's `delegate` function.
    /// @param _tokenIds The list of token ids that are being delegated.
    function delegate(uint256[] calldata _tokenIds) external;
    /// @notice Allows to un-delegate `_tokenIds` from the current delegatee
    ///         which was set by delegate.
    /// @param _tokenIds The list of token ids that are being un-delegated.
    function undelegate(uint256[] calldata _tokenIds) external;
    /// @notice Check if the token is currently delegated or not.
    function tokenIsDelegated(uint256 _tokenId) external view returns (bool);
    /// @notice Returns the current delegatee of `_account`.
    function delegates(address _account) external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {
    IExitQueueMinLock,
    IExitMinLockCooldownErrorsAndEvents,
    IExitQueueCoreErrorsAndEvents,
    IExitQueueCancelErrorsAndEvents
} from "./IExitQueue.sol";
interface ITicketV2 {
    struct TicketV2 {
        address holder;
        uint48 queuedAt;
    }
    event ExitQueuedV2(uint256 indexed tokenId, address indexed holder, uint48 queuedAt);
}
/*///////////////////////////////////////////////////////////////
                        Fee Collection
//////////////////////////////////////////////////////////////*/
interface IExitFeeWithdrawErrorsAndEvents {
    event Withdraw(address indexed to, uint256 amount);
}
interface IExitFeeWithdraw is IExitFeeWithdrawErrorsAndEvents {
    /// @notice withdraw accumulated fees
    function withdraw(uint256 _amount) external;
}
/*///////////////////////////////////////////////////////////////
                        Early Exit Queue
//////////////////////////////////////////////////////////////*/
interface IDynamicExitQueueEventsAndErrors {
    enum ExitFeeType {
        Fixed,
        Tiered,
        Dynamic
    }
    // Events
    event ExitFeePercentAdjusted(
        uint256 maxFeePercent,
        uint256 minFeePercent,
        uint48 minCooldown,
        ExitFeeType feeType
    );
    // Errors
    error EarlyExitDisabled();
    error MinCooldownNotMet();
    error InvalidFeeParameters();
    error FeePercentTooHigh(uint256 maxAllowed);
    error CooldownTooShort();
    error LegacyFunctionDeprecated();
}
interface IDynamicExitQueueFee is IDynamicExitQueueEventsAndErrors {
    /// @notice Calculate the absolute fee amount for exiting a specific token
    /// @param tokenId The token ID to calculate fee for
    /// @return Fee amount in underlying token units
    function calculateFee(uint256 tokenId) external view returns (uint256);
    /// @notice Check if a token has completed its full cooldown period (minimum fee applies)
    /// @param tokenId The token ID to check
    /// @return True if full cooldown elapsed, false otherwise
    function isCool(uint256 tokenId) external view returns (bool);
    /// @notice Configure linear fee decay system where fees decrease continuously over time
    /// @param _minFeePercent Fee percent after full cooldown (basis points, 0-10000)
    /// @param _maxFeePercent Fee percent immediately after minCooldown (basis points, 0-10000)
    /// @param _cooldown Total cooldown period in seconds
    /// @param _minCooldown Minimum wait before any exit allowed in seconds
    function setDynamicExitFeePercent(
        uint256 _minFeePercent,
        uint256 _maxFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) external;
    /// @notice Configure two-tier fee system with early exit penalty and normal exit rate
    /// @param _baseFeePercent Fee percent for normal exits after cooldown (basis points, 0-10000)
    /// @param _earlyFeePercent Fee percent for early exits after minCooldown (basis points, 0-10000)
    /// @param _cooldown Total cooldown period in seconds
    /// @param _minCooldown Minimum wait before any exit allowed in seconds
    function setTieredExitFeePercent(
        uint256 _baseFeePercent,
        uint256 _earlyFeePercent,
        uint48 _cooldown,
        uint48 _minCooldown
    ) external;
    /// @notice Configure single fee rate system with optional early exit control
    /// @param _feePercent Fee percent for all exits (basis points, 0-10000)
    /// @param _cooldown Total cooldown period in seconds
    /// @param _allowEarlyExit If true, allow exits after minCooldown=0; if false, require full cooldown
    function setFixedExitFeePercent(
        uint256 _feePercent,
        uint48 _cooldown,
        bool _allowEarlyExit
    ) external;
    /// @notice Minimum fee percent charged after full cooldown
    /// @return Fee percent in basis points (0-10000)
    function minFeePercent() external view returns (uint256);
    /// @notice Minimum wait time before any exit is possible
    /// @return Time in seconds
    function minCooldown() external view returns (uint48);
}
/*///////////////////////////////////////////////////////////////
                        Exit Queue
//////////////////////////////////////////////////////////////*/
interface IDynamicExitQueueErrorsAndEvents is
    IExitQueueCoreErrorsAndEvents,
    IExitMinLockCooldownErrorsAndEvents,
    IDynamicExitQueueEventsAndErrors,
    IExitQueueCancelErrorsAndEvents
{}
interface IDynamicExitQueue is
    IDynamicExitQueueErrorsAndEvents,
    ITicketV2,
    IExitQueueMinLock,
    IDynamicExitQueueFee
{
    /// @notice tokenId => TicketV2
    function queue(uint256 _tokenId) external view returns (TicketV2 memory);
    /// @notice queue an exit for a given tokenId, granting the ticket to the passed holder
    /// @param _tokenId the tokenId to queue an exit for
    /// @param _ticketHolder the address that will be granted the ticket
    function queueExit(uint256 _tokenId, address _ticketHolder) external;
    /// @notice exit the queue for a given tokenId. Requires the cooldown period to have passed
    /// @return exitAmount the amount of tokens that can be withdrawn
    function exit(uint256 _tokenId) external returns (uint256 exitAmount);
    /// @notice return true if the tokenId corresponds to a valid ticket and the cooldown period has passed
    function canExit(uint256 _tokenId) external view returns (bool);
    /// @notice return the ticket holder for a given tokenId
    function ticketHolder(uint256 _tokenId) external view returns (address);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*///////////////////////////////////////////////////////////////
                        CORE FUNCTIONALITY
//////////////////////////////////////////////////////////////*/
interface ILockedBalanceIncreasing {
    struct LockedBalance {
        uint208 amount;
        uint48 start; // mirrors oz ERC20 timestamp clocks
    }
}
interface IVotingEscrowCoreErrors {
    error NoLockFound();
    error NotOwner();
    error NoOwner();
    error NotSameOwner();
    error NonExistentToken();
    error NotApprovedOrOwner();
    error ZeroAddress();
    error ZeroAmount();
    error ZeroBalance();
    error SameAddress();
    error LockNFTAlreadySet();
    error MustBe18Decimals();
    error TransferBalanceIncorrect();
    error AmountTooSmall();
    error OnlyLockNFT();
    error OnlyIVotesAdapter();
    error AddressAlreadySet();
}
interface IVotingEscrowCoreEvents {
    event MinDepositSet(uint256 minDeposit);
    event Deposit(
        address indexed depositor,
        uint256 indexed tokenId,
        uint256 indexed startTs,
        uint256 value,
        uint256 newTotalLocked
    );
    event Withdraw(
        address indexed depositor,
        uint256 indexed tokenId,
        uint256 value,
        uint256 ts,
        uint256 newTotalLocked
    );
}
interface IVotingEscrowCore is
    ILockedBalanceIncreasing,
    IVotingEscrowCoreErrors,
    IVotingEscrowCoreEvents
{
    /// @notice Address of the underying ERC20 token.
    function token() external view returns (address);
    /// @notice Address of the lock receipt NFT.
    function lockNFT() external view returns (address);
    /// @notice Total underlying tokens deposited in the contract
    function totalLocked() external view returns (uint256);
    /// @notice Get the raw locked balance for `_tokenId`
    function locked(uint256 _tokenId) external view returns (LockedBalance memory);
    /// @notice Deposit `_value` tokens for `msg.sender`
    /// @param _value Amount to deposit
    /// @return TokenId of created veNFT
    function createLock(uint256 _value) external returns (uint256);
    /// @notice Deposit `_value` tokens for `_to`
    /// @param _value Amount to deposit
    /// @param _to Address to deposit
    /// @return TokenId of created veNFT
    function createLockFor(uint256 _value, address _to) external returns (uint256);
    /// @notice Withdraw all tokens for `_tokenId`
    function withdraw(uint256 _tokenId) external;
    /// @notice helper utility for NFT checks
    function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
/*///////////////////////////////////////////////////////////////
                        WITHDRAWAL QUEUE
//////////////////////////////////////////////////////////////*/
interface IWithdrawalQueueErrors {
    error NotTicketHolder();
    error CannotExit();
    error CannotWithdrawInSameBlock();
}
interface IWithdrawalQueueEvents {}
interface IWithdrawalQueue is IWithdrawalQueueErrors, IWithdrawalQueueEvents {
    /// @notice Enters a tokenId into the withdrawal queue by transferring to this contract and creating a ticket.
    /// @param _tokenId The tokenId to begin withdrawal for. Will be transferred to this contract before burning.
    /// @dev The user must not have active votes in the voter contract.
    function beginWithdrawal(uint256 _tokenId) external;
    /// @notice Address of the contract that manages exit queue logic for withdrawals
    function queue() external view returns (address);
}
/*///////////////////////////////////////////////////////////////
                        SWEEPER
//////////////////////////////////////////////////////////////*/
interface ISweeperEvents {
    event Sweep(address indexed to, uint256 amount);
    event SweepNFT(address indexed to, uint256 tokenId);
}
interface ISweeperErrors {
    error NothingToSweep();
}
interface ISweeper is ISweeperEvents, ISweeperErrors {
    /// @notice sweeps excess tokens from the contract to a designated address
    function sweep() external;
    function sweepNFT(uint256 _tokenId, address _to) external;
}
/*///////////////////////////////////////////////////////////////
                        DYNAMIC VOTER
//////////////////////////////////////////////////////////////*/
interface IDynamicVoterErrors {
    error NotVoter();
    error OwnershipChange();
    error AlreadyVoted();
}
interface IDynamicVoter is IDynamicVoterErrors {
    /// @notice Address of the voting contract.
    /// @dev We need to ensure votes are not left in this contract before allowing positing changes
    function voter() external view returns (address);
    /// @notice Address of the voting Escrow Curve contract that will calculate the voting power
    function curve() external view returns (address);
    /// @notice Get the voting power for _tokenId at the current timestamp
    /// @dev Returns 0 if called in the same block as a transfer.
    /// @param _tokenId .
    /// @return Voting power
    function votingPower(uint256 _tokenId) external view returns (uint256);
    /// @notice Get the voting power for _tokenId at a given timestamp
    /// @param _tokenId .
    /// @param _t Timestamp to query voting power
    /// @return Voting power
    function votingPowerAt(uint256 _tokenId, uint256 _t) external view returns (uint256);
    /// @notice Get the voting power for _account at the current timestamp
    /// Aggregtes all voting power for all tokens owned by the account
    /// @dev This cannot be used historically without token snapshots
    function votingPowerForAccount(address _account) external view returns (uint256);
    /// @notice Calculate total voting power at current timestamp
    /// @return Total voting power at current timestamp
    function totalVotingPower() external view returns (uint256);
    /// @notice Calculate total voting power at a given timestamp
    /// @param _t Timestamp to query total voting power
    /// @return Total voting power at given timestamp
    function totalVotingPowerAt(uint256 _t) external view returns (uint256);
    /// @notice See if a queried _tokenId has actively voted
    /// @return True if voted, else false
    function isVoting(uint256 _tokenId) external view returns (bool);
    /// @notice Set the global state voter
    function setVoter(address _voter) external;
}
/*///////////////////////////////////////////////////////////////
                        INCREASED ESCROW
//////////////////////////////////////////////////////////////*/
interface IVotingEscrowIncreasing is IVotingEscrowCore, IDynamicVoter, IWithdrawalQueue, ISweeper {}
/// @dev useful for testing
interface IVotingEscrowEventsStorageErrorsEvents is
    IVotingEscrowCoreErrors,
    IVotingEscrowCoreEvents,
    IWithdrawalQueueErrors,
    IWithdrawalQueueEvents,
    ILockedBalanceIncreasing,
    ISweeperEvents,
    ISweeperErrors
{}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IClockUser {
    function clock() external view returns (address);
}
interface IClock {
    function epochDuration() external pure returns (uint256);
    function checkpointInterval() external pure returns (uint256);
    function voteDuration() external pure returns (uint256);
    function voteWindowBuffer() external pure returns (uint256);
    function currentEpoch() external view returns (uint256);
    function resolveEpoch(uint256 timestamp) external pure returns (uint256);
    function elapsedInEpoch() external view returns (uint256);
    function resolveElapsedInEpoch(uint256 timestamp) external pure returns (uint256);
    function epochStartsIn() external view returns (uint256);
    function resolveEpochStartsIn(uint256 timestamp) external pure returns (uint256);
    function epochStartTs() external view returns (uint256);
    function resolveEpochStartTs(uint256 timestamp) external pure returns (uint256);
    function votingActive() external view returns (bool);
    function resolveVotingActive(uint256 timestamp) external pure returns (bool);
    function epochVoteStartsIn() external view returns (uint256);
    function resolveEpochVoteStartsIn(uint256 timestamp) external pure returns (uint256);
    function epochVoteStartTs() external view returns (uint256);
    function resolveEpochVoteStartTs(uint256 timestamp) external pure returns (uint256);
    function epochVoteEndsIn() external view returns (uint256);
    function resolveEpochVoteEndsIn(uint256 timestamp) external pure returns (uint256);
    function epochVoteEndTs() external view returns (uint256);
    function resolveEpochVoteEndTs(uint256 timestamp) external pure returns (uint256);
    function epochNextCheckpointIn() external view returns (uint256);
    function resolveEpochNextCheckpointIn(uint256 timestamp) external pure returns (uint256);
    function epochNextCheckpointTs() external view returns (uint256);
    function resolveEpochNextCheckpointTs(uint256 timestamp) external pure returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);
    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);
    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);
    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);
    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);
    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;
    /**
     * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }
    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }
    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }
    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }
    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }
    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }
    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.
        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }
    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.
        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
 * @dev Wrappers over Solidity's uintXX/intXX 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.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }
    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        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
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }
    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }
    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@solmate/utils/SignedWadMath.sol";
error NegativeBase();
// shared interface for fixed point math implementations.
library SignedFixedPointMath {
    // solmate does this unchecked to save gas, easier to do this here
    // be extremely careful that you are doing all operations in FP
    // unlike PRB Math (unsupported in solidity 0.8.17)
    // solmate will not warn you that you are operating in scaled down mode
    function toFP(int256 x) internal pure returns (int256) {
        return x * 1e18;
    }
    function fromFP(int256 x) internal pure returns (int256) {
        return x / 1e18;
    }
    function mul(int256 x, int256 y) internal pure returns (int256) {
        return wadMul(x, y);
    }
    function div(int256 x, int256 y) internal pure returns (int256) {
        return wadDiv(x, y);
    }
    function add(int256 x, int256 y) internal pure returns (int256) {
        return x + y;
    }
    function sub(int256 x, int256 y) internal pure returns (int256) {
        return x - y;
    }
    function pow(int256 x, int256 y) internal pure returns (int256) {
        if (x < 0) revert NegativeBase();
        if (x == 0) return 0;
        return wadPow(x, y);
    }
    function lt(int256 x, int256 y) internal pure returns (bool) {
        return x < y;
    }
    function gt(int256 x, int256 y) internal pure returns (bool) {
        return x > y;
    }
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// The initial bias is scaled by a multiplier, which defaults to 1x (no scaling).
// To start with a higher initial bias (e.g., 1.5x the amount), update this value accordingly.
// For example, set it to 1.5 in case you want to start with 1.5 * amount.
int256 constant INITIAL_BIAS_MULTIPLIER = 1;
/// @title CurveConstantLib
/// @notice Precomputed coefficients for escrow curve
/// Below are the shared coefficients for the linear and quadratic terms
/// @dev This curve goes from 1x -> 2x voting power over a 2 year time horizon
/// Epochs are still 2 weeks long
library CurveConstantLib {
    int256 internal constant SHARED_CONSTANT_COEFFICIENT = INITIAL_BIAS_MULTIPLIER * 1e18;
    /// @dev straight line so the curve is increasing only in the linear term
    /// 1 / (52 * SECONDS_IN_2_WEEKS)
    int256 internal constant SHARED_LINEAR_COEFFICIENT = 1e18 / (int256(MAX_EPOCHS) * 2 weeks);
    /// @dev this curve is linear
    int256 internal constant SHARED_QUADRATIC_COEFFICIENT = 0;
    /// @dev the maxiumum number of epochs the cure can keep increasing
    /// 26 epochs in a year, 2 years = 52 epochs
    uint256 internal constant MAX_EPOCHS = 52;
    function getCoefficients() internal pure returns (int256[3] memory, uint256) {
        int256[3] memory coefficients;
        coefficients[0] = SHARED_CONSTANT_COEFFICIENT;
        coefficients[1] = SHARED_LINEAR_COEFFICIENT;
        coefficients[2] = SHARED_QUADRATIC_COEFFICIENT;
        uint256 maxEpoch = MAX_EPOCHS;
        return (coefficients, maxEpoch);
    }
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*///////////////////////////////////////////////////////////////
                        WHITELIST
//////////////////////////////////////////////////////////////*/
interface IWhitelistEvents {
    event WhitelistSet(address indexed account, bool status);
}
interface IWhitelistErrors {
    error NotWhitelisted();
    error ForbiddenWhitelistAddress();
}
interface IWhitelist is IWhitelistEvents, IWhitelistErrors {
    /// @notice Set whitelist status for an address
    function setWhitelisted(address addr, bool isWhitelisted) external;
    /// @notice Check if an address is whitelisted
    function whitelisted(address addr) external view returns (bool);
}
interface ILock is IWhitelist {
    error OnlyEscrow();
    /// @notice Address of the escrow contract that holds underyling assets
    function escrow() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
    function __ERC721Enumerable_init() internal onlyInitializing {
    }
    function __ERC721Enumerable_init_unchained() internal onlyInitializing {
    }
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;
    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;
    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
        return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }
    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }
    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }
    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }
    /**
     * @dev See {ERC721-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
        if (batchSize > 1) {
            // Will only trigger during construction. Batch transferring (minting) is not available afterwards.
            revert("ERC721Enumerable: consecutive transfers not supported");
        }
        uint256 tokenId = firstTokenId;
        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }
    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721Upgradeable.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }
    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }
    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).
        uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];
        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }
        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }
    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).
        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];
        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];
        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[46] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC6372.sol)
pragma solidity ^0.8.0;
interface IERC6372 {
    /**
     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
     */
    function clock() external view returns (uint48);
    /**
     * @dev Description of the clock
     */
    // solhint-disable-next-line func-name-mixedcase
    function CLOCK_MODE() external view returns (string memory);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {
    IVotesUpgradeable
} from "@openzeppelin/contracts-upgradeable/governance/utils/IVotesUpgradeable.sol";
import {
    PausableUpgradeable as Pausable
} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
    IVotingEscrowIncreasingV1_2_0 as IVotingEscrow,
    ILockedBalanceIncreasing
} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
import {IEscrowIVotesAdapter, IDelegateMoveVoteRecipient} from "./IEscrowIVotesAdapter.sol";
abstract contract DelegationHelper is IEscrowIVotesAdapter, Pausable, UUPSUpgradeable {
    /// @notice Address of the voting escrow contract that will track voting power
    address public escrow;
    /// @notice the mapping that stores how many token an address has delegated currently.
    mapping(address => uint256) public numberOfDelegatedTokens;
    /// @notice Efficiently stores which token is delegated.
    mapping(uint256 => uint256) private delegatedBitmap;
    error IncorrectTokenIds();
    modifier onlyEscrow() {
        if (_msgSender() != escrow) {
            revert OnlyEscrow();
        }
        _;
    }
    /// @notice The initializer.
    function __DelegationHelper_init(address _escrow) internal onlyInitializing {
        escrow = _escrow;
    }
    /// @inheritdoc IDelegateMoveVoteRecipient
    function splitDelegateVotes(
        TokenLock calldata _from,
        TokenLock calldata _to
    ) public virtual whenNotPaused onlyEscrow {
        if (_from.tokenId == 0 || _to.tokenId == 0) {
            revert IncorrectTokenIds();
        }
        // If `x` is split into `x` and `y`, and `x` is delegated,
        // then automatically delegate `y` as well. This is to ensure that
        // later on, delegating `y` manually will revert, otherwise it would
        // cause votes to be double spent as original `x` that was delegated
        // already included the amount of `y`.
        if (tokenIsDelegated(_from.tokenId)) {
            numberOfDelegatedTokens[_from.account]++;
            _setDelegated(_to.tokenId, true);
            emit TokensDelegated(_to.account, delegates(_to.account), _getTokenIdList(_to.tokenId));
        }
    }
    /// @inheritdoc IDelegateMoveVoteRecipient
    function mergeDelegateVotes(
        TokenLock calldata _from,
        TokenLock calldata _to
    ) public virtual whenNotPaused onlyEscrow {
        if (_from.tokenId == 0 || _to.tokenId == 0) {
            revert IncorrectTokenIds();
        }
        bool isFromTokenDelegated = tokenIsDelegated(_from.tokenId);
        bool isToTokenDelegated = tokenIsDelegated(_to.tokenId);
        address fromDelegatee = delegates(_from.account);
        if (!isFromTokenDelegated) {
            // from is not delegated and to is delegated.
            if (isToTokenDelegated) {
                (int256 bias, int256 slope) = _getBiasAndSlope(
                    fromDelegatee,
                    _from.locked,
                    _positive
                );
                _checkpoint(bias, slope, fromDelegatee);
            }
            // If none of them are delegated, do nothing.
        } else {
            // from is delegated and to is delegated.
            // since both are already delegated, their amounts are already included in checkpoints.
            // We only need to mark `from` as false and decrease count since `from` actually
            // gets burnt(note that its amount moves in `to`)
            if (isToTokenDelegated) {
                numberOfDelegatedTokens[_from.account]--;
            } else {
                // from is delegated, but `to` is not delegated.
                // We must add `to`'s amount in the checkpoints. Otherwise, after the merge,
                // user can manually delegate `to` which's vp at the time will include
                // the total amount after the merge. This will cause double spend.
                // lock needs to be `to`'s amount.
                (int256 bias, int256 slope) = _getBiasAndSlope(
                    fromDelegatee,
                    _to.locked,
                    _positive
                );
                _checkpoint(bias, slope, fromDelegatee);
                _setDelegated(_to.tokenId, true);
                emit TokensDelegated(
                    _to.account,
                    delegates(_to.account),
                    _getTokenIdList(_to.tokenId)
                );
            }
            _setDelegated(_from.tokenId, false);
            emit TokensUndelegated(_from.account, fromDelegatee, _getTokenIdList(_from.tokenId));
        }
    }
    /// @inheritdoc IDelegateMoveVoteRecipient
    /// @dev This is called on `transfer`, `withdraw` and `createLock`.
    /// @notice Assumes that: if this is called on transfer, then it can only be called if _from and _to are different.
    function moveDelegateVotes(
        address _from,
        address _to,
        uint256 _tokenId,
        IVotingEscrow.LockedBalance memory _locked
    ) public virtual whenNotPaused onlyEscrow {
        address fromDelegatee = delegates(_from);
        address toDelegatee = delegates(_to);
        // undelegated src and recipient, no balances to update
        if (fromDelegatee == address(0) && toDelegatee == address(0)) {
            return;
        }
        uint256[] memory tokenIds = _getTokenIdList(_tokenId);
        if (fromDelegatee != address(0)) {
            if (tokenIsDelegated(_tokenId)) {
                (int256 bias, int256 slope) = _getBiasAndSlope(fromDelegatee, _locked, _negative);
                _checkpoint(bias, slope, fromDelegatee);
                numberOfDelegatedTokens[_from]--;
                emit TokensUndelegated(_from, fromDelegatee, tokenIds);
            }
        }
        if (toDelegatee != address(0)) {
            (int256 bias, int256 slope) = _getBiasAndSlope(toDelegatee, _locked, _positive);
            _checkpoint(bias, slope, toDelegatee);
            numberOfDelegatedTokens[_to]++;
            _setDelegated(_tokenId, true);
            emit TokensDelegated(_to, toDelegatee, tokenIds);
        } else {
            // else this is new delegate voting power being burned
            _setDelegated(_tokenId, false);
        }
        if (fromDelegatee != toDelegatee) {
            IVotingEscrow(escrow).updateVotingPower(fromDelegatee, toDelegatee);
        }
    }
    /// @dev Whether token is currently delegated or not.
    function tokenIsDelegated(uint256 tokenId) public view virtual returns (bool) {
        uint256 bucket = tokenId >> 8;
        uint256 mask = 1 << (tokenId & 0xff);
        return (delegatedBitmap[bucket] & mask) != 0;
    }
    /// @dev Internal helper function to set token delegated to true by using bitmap operations.
    function _setDelegated(uint256 tokenId, bool value) internal virtual {
        uint256 bucket = tokenId >> 8; // tokenId / 256
        uint256 mask = 1 << (tokenId & 0xff); // tokenId % 256
        if (value) {
            delegatedBitmap[bucket] |= mask;
        } else {
            delegatedBitmap[bucket] &= ~mask;
        }
    }
    function _positive(int256 _value) internal pure returns (int256) {
        return _value;
    }
    function _negative(int256 _value) internal pure returns (int256) {
        return -_value;
    }
    function _getTokenIdList(uint256 _tokenId) private pure returns (uint256[] memory tokenIds) {
        tokenIds = new uint256[](1);
        tokenIds[0] = _tokenId;
    }
    /*//////////////////////////////////////////////////////////////
                        Abstract Functions.
    //////////////////////////////////////////////////////////////*/
    function delegates(address _account) public view virtual returns (address);
    function _getBiasAndSlope(
        address _delegatee,
        IVotingEscrow.LockedBalance memory _locked,
        function(int256) view returns (int256) op
    ) internal virtual returns (int256, int256);
    function _checkpoint(
        int256 _totalBias,
        int256 _totalSlope,
        address _delegatee
    ) internal virtual;
    function _checkpoint(
        int256 _totalBias,
        int256 _totalSlope,
        address _delegatee,
        uint256 _transitionCount
    ) internal virtual;
    /// @dev Reserved storage space to allow for layout changes in the future.
    uint256[47] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }
    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
    function __ERC1967Upgrade_init() internal onlyInitializing {
    }
    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }
    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }
    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }
    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(newImplementation, data);
        }
    }
    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }
    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }
    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }
    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }
    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }
    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }
    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20PermitUpgradeable {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);
    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())
            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())
            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }
    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
     * and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);
    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _beforeFallback();
        _delegate(_implementation());
    }
    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
     * is empty.
     */
    receive() external payable virtual {
        _fallback();
    }
    /**
     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
     * call, or as part of the Solidity `fallback` or `receive` functions.
     *
     * If overridden should call `super._beforeFallback()`.
     */
    function _beforeFallback() internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967Upgrade is IERC1967 {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }
    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }
    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }
    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(newImplementation, data);
        }
    }
    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }
    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
    }
    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }
    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }
    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
    }
    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            Address.isContract(IBeacon(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }
    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * 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 ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => 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.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }
    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }
    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }
    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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 override returns (uint8) {
        return 18;
    }
    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }
    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override 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 `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }
    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }
    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }
    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * 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 `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }
    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }
    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }
        return true;
    }
    /**
     * @dev Moves `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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        _beforeTokenTransfer(from, to, amount);
        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }
        emit Transfer(from, to, amount);
        _afterTokenTransfer(from, to, amount);
    }
    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");
        _beforeTokenTransfer(address(0), account, amount);
        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);
        _afterTokenTransfer(address(0), account, amount);
    }
    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");
        _beforeTokenTransfer(account, address(0), amount);
        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }
        emit Transfer(account, address(0), amount);
        _afterTokenTransfer(account, address(0), amount);
    }
    /**
     * @dev Sets `amount` 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.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");
        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }
    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }
    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20Upgradeable.sol";
import "../token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );
    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);
    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);
    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);
    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);
    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);
    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);
    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);
    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);
    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);
    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);
    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);
    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);
    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);
    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);
    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }
    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }
    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }
    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }
            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // 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^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv 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.
            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)
                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)
                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }
            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;
            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;
            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256
            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }
    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }
    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }
        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);
        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }
    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }
    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }
    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }
    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }
    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }
    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }
    /**
     * @dev Return the log in base 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }
    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }
    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
import {IDAO} from "../../dao/IDAO.sol";
/// @title DAO Authorization Utilities
/// @author Aragon X - 2022-2024
/// @notice Provides utility functions for verifying if a caller has specific permissions in an associated DAO.
/// @custom:security-contact [email protected]
/// @notice Thrown if a call is unauthorized in the associated DAO.
/// @param dao The associated DAO.
/// @param where The context in which the authorization reverted.
/// @param who The address (EOA or contract) missing the permission.
/// @param permissionId The permission identifier.
error DaoUnauthorized(address dao, address where, address who, bytes32 permissionId);
/// @notice A free function checking if a caller is granted permissions on a target contract via a permission identifier that redirects the approval to a `PermissionCondition` if this was specified in the setup.
/// @param _where The address of the target contract for which `who` receives permission.
/// @param _who The address (EOA or contract) owning the permission.
/// @param _permissionId The permission identifier.
/// @param _data The optional data passed to the `PermissionCondition` registered.
function _auth(
    IDAO _dao,
    address _where,
    address _who,
    bytes32 _permissionId,
    bytes calldata _data
) view {
    if (!_dao.hasPermission(_where, _who, _permissionId, _data))
        revert DaoUnauthorized({
            dao: address(_dao),
            where: _where,
            who: _who,
            permissionId: _permissionId
        });
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
 * @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 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;
    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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
        // 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 v4.9.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
    using AddressUpgradeable for address;
    using StringsUpgradeable for uint256;
    // Token name
    string private _name;
    // Token symbol
    string private _symbol;
    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;
    // Mapping owner address to token count
    mapping(address => uint256) private _balances;
    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;
    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;
    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC721_init_unchained(name_, symbol_);
    }
    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
        return
            interfaceId == type(IERC721Upgradeable).interfaceId ||
            interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
            super.supportsInterface(interfaceId);
    }
    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }
    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }
    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }
    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }
    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);
        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }
    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }
    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");
        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );
        _approve(to, tokenId);
    }
    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);
        return _tokenApprovals[tokenId];
    }
    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }
    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }
    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _transfer(from, to, tokenId);
    }
    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }
    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }
    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }
    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }
    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }
    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }
    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }
    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }
    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");
        _beforeTokenTransfer(address(0), to, tokenId, 1);
        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");
        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }
        _owners[tokenId] = to;
        emit Transfer(address(0), to, tokenId);
        _afterTokenTransfer(address(0), to, tokenId, 1);
    }
    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721Upgradeable.ownerOf(tokenId);
        _beforeTokenTransfer(owner, address(0), tokenId, 1);
        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721Upgradeable.ownerOf(tokenId);
        // Clear approvals
        delete _tokenApprovals[tokenId];
        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];
        emit Transfer(owner, address(0), tokenId);
        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }
    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");
        _beforeTokenTransfer(from, to, tokenId, 1);
        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];
        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;
        emit Transfer(from, to, tokenId);
        _afterTokenTransfer(from, to, tokenId, 1);
    }
    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
    }
    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }
    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }
    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }
    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[44] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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.
 *
 * By default, the owner account will be the one that deploys the contract. 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }
    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }
    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }
    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
    function __AccessControlEnumerable_init() internal onlyInitializing {
    }
    function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
    }
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
    mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
        return _roleMembers[role].at(index);
    }
    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
        return _roleMembers[role].length();
    }
    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }
    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
/// @title IAccessControlManager
/// @author Angle Labs, Inc.
/// @notice Interface for the `AccessControlManager` contracts of Merkl contracts
interface IAccessControlManager {
    /// @notice Checks whether an address is governor
    /// @param admin Address to check
    /// @return Whether the address has the `GOVERNOR_ROLE` or not
    function isGovernor(address admin) external view returns (bool);
    /// @notice Checks whether an address is a governor or a guardian of a module
    /// @param admin Address to check
    /// @return Whether the address has the `GUARDIAN_ROLE` or not
    /// @dev Governance should make sure when adding a governor to also give this governor the guardian
    /// role by calling the `addGovernor` function
    function isGovernorOrGuardian(address admin) external view returns (bool);
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { IAccessControlManager } from "../interfaces/IAccessControlManager.sol";
import { Errors } from "./Errors.sol";
/// @title UUPSHelper
/// @notice Helper contract for UUPSUpgradeable contracts where the upgradeability is controlled by a specific address
/// @author Angle Labs., Inc
/// @dev The 0 address check in the modifier allows the use of these modifiers during initialization
abstract contract UUPSHelper is UUPSUpgradeable {
    modifier onlyGuardianUpgrader(IAccessControlManager _accessControlManager) {
        if (address(_accessControlManager) != address(0) && !_accessControlManager.isGovernorOrGuardian(msg.sender))
            revert Errors.NotGovernorOrGuardian();
        _;
    }
    modifier onlyGovernorUpgrader(IAccessControlManager _accessControlManager) {
        if (address(_accessControlManager) != address(0) && !_accessControlManager.isGovernor(msg.sender))
            revert Errors.NotGovernor();
        _;
    }
    constructor() initializer {}
    /// @inheritdoc UUPSUpgradeable
    function _authorizeUpgrade(address newImplementation) internal virtual override {}
}// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.17;
library Errors {
    error CampaignDoesNotExist();
    error CampaignAlreadyExists();
    error CampaignDurationBelowHour();
    error CampaignRewardTokenNotWhitelisted();
    error CampaignRewardTooLow();
    error CampaignShouldStartInFuture();
    error InvalidDispute();
    error InvalidLengths();
    error InvalidOverride();
    error InvalidParam();
    error InvalidParams();
    error InvalidProof();
    error InvalidUninitializedRoot();
    error InvalidReturnMessage();
    error InvalidReward();
    error InvalidSignature();
    error KeyAlreadyUsed();
    error NoDispute();
    error NoOverrideForCampaign();
    error NotAllowed();
    error NotEnoughPayment();
    error NotGovernor();
    error NotGovernorOrGuardian();
    error NotSigned();
    error NotTrusted();
    error NotUpgradeable();
    error NotWhitelisted();
    error UnresolvedDispute();
    error ZeroAddress();
    error DisputeFundsTransferFailed();
    error EthNotAccepted();
    error ReentrantCall();
    error WithdrawalFailed();
    error InvalidClaim();
    error RefererNotSet();
}// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import {console as console2} from "./console.sol";/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IGauge {
    /// @param metadataURI URI for the metadata of the gauge
    struct Gauge {
        bool active;
        uint256 created; // timestamp or epoch
        string metadataURI;
        // more space for data as this is a struct in a mapping
    }
}
/*///////////////////////////////////////////////////////////////
                            Gauge Manager
//////////////////////////////////////////////////////////////*/
interface IGaugeManagerEvents {
    event GaugeCreated(address indexed gauge, address indexed creator, string metadataURI);
    event GaugeDeactivated(address indexed gauge);
    event GaugeActivated(address indexed gauge);
    event GaugeMetadataUpdated(address indexed gauge, string metadataURI);
}
interface IGaugeManagerErrors {
    error ZeroGauge();
    error GaugeActivationUnchanged();
    error GaugeExists();
}
interface IGaugeManager is IGaugeManagerEvents, IGaugeManagerErrors {
    function isActive(address gauge) external view returns (bool);
    function createGauge(address _gauge, string calldata _metadata) external returns (address);
    function deactivateGauge(address _gauge) external;
    function activateGauge(address _gauge) external;
    function updateGaugeMetadata(address _gauge, string calldata _metadata) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165CheckerUpgradeable {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
    /**
     * @dev Returns true if `account` supports the {IERC165} interface.
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165Upgradeable).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
    }
    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }
    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(
        address account,
        bytes4[] memory interfaceIds
    ) internal view returns (bool[] memory) {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }
        return interfaceIdsSupported;
    }
    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }
        // query support of each interface in interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }
        // all interfaces supported
        return true;
    }
    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     *
     * Some precompiled contracts will falsely indicate support for a given interface, so caution
     * should be exercised when using this function.
     *
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable.supportsInterface.selector, interfaceId);
        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }
        return success && returnSize >= 0x20 && returnValue > 0;
    }
}// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.8; /// @title IPlugin /// @author Aragon X - 2022-2024 /// @notice An interface defining the traits of a plugin. /// @custom:security-contact [email protected] interface IPlugin { /// @notice Types of plugin implementations available within OSx. enum PluginType { UUPS, Cloneable, Constructable } /// @notice Specifies the type of operation to perform. enum Operation { Call, DelegateCall } /// @notice Configuration for the target contract that the plugin will interact with, including the address and operation type. /// @dev By default, the plugin typically targets the associated DAO and performs a `Call` operation. However, this /// configuration allows the plugin to specify a custom executor and select either `Call` or `DelegateCall` based on /// the desired execution context. /// @param target The address of the target contract, typically the associated DAO but configurable to a custom executor. /// @param operation The type of operation (`Call` or `DelegateCall`) to execute on the target, as defined by `Operation`. struct TargetConfig { address target; Operation operation; } /// @notice Returns the plugin's type function pluginType() external view returns (PluginType); }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);
    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ILockedBalanceIncreasing} from "@escrow/IVotingEscrowIncreasing.sol";
/*///////////////////////////////////////////////////////////////
                        Token Curve
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveTokenStorage {
    /// @notice Captures the shape of the user's voting curve at a specific point in time
    /// @param bias The y intercept of the user's voting curve at the given time
    /// @param checkpointTs The checkpoint when the user voting curve is/was/will be updated
    /// @param writtenTs The timestamp at which we locked the checkpoint
    /// @param coefficients The coefficients of the curve, supports up to quadratic curves.
    /// @dev Coefficients are stored in the following order: [constant, linear, quadratic]
    /// and not all coefficients are used for all curves.
    struct TokenPoint {
        uint256 bias;
        uint128 checkpointTs;
        uint128 writtenTs;
        int256[3] coefficients;
    }
}
interface IEscrowCurveToken is IEscrowCurveTokenStorage {
    /// @notice returns the token point at time `timestamp`
    function tokenPointIntervals(uint256 timestamp) external view returns (uint256);
    /// @notice Returns the TokenPoint at the passed epoch
    /// @param _tokenId The NFT to return the TokenPoint for
    /// @param _loc The epoch to return the TokenPoint at
    function tokenPointHistory(
        uint256 _tokenId,
        uint256 _loc
    ) external view returns (TokenPoint memory);
}
/*///////////////////////////////////////////////////////////////
                        Core Functions
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveErrorsAndEvents {
    error InvalidTokenId();
    error InvalidCheckpoint();
    error OnlyEscrow();
    error CheckpointOnDepositIntervalNotAllowed();
    error InvalidLocks(
        uint256 tokenId,
        ILockedBalanceIncreasing.LockedBalance fromLocked,
        ILockedBalanceIncreasing.LockedBalance newLocked
    );
}
interface IEscrowCurveCore is IEscrowCurveErrorsAndEvents {
    /// @notice Get the current voting power for `_tokenId`
    /// @dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility
    ///      Fetches last token point prior to a certain timestamp, then walks forward to timestamp.
    /// @param _tokenId NFT for lock
    /// @param _t Epoch time to return voting power at
    /// @return Token voting power
    function votingPowerAt(uint256 _tokenId, uint256 _t) external view returns (uint256);
    /// @notice Calculate total voting power at some point in the past
    /// @param _t Time to calculate the total voting power at
    /// @return Total voting power at that time
    function supplyAt(uint256 _t) external view returns (uint256);
    /// @notice Writes a snapshot of voting power at the current epoch
    /// @param _tokenId Snapshot a specific token
    /// @param _oldLocked The token's previous locked balance
    /// @param _newLocked The token's new locked balance
    function checkpoint(
        uint256 _tokenId,
        ILockedBalanceIncreasing.LockedBalance memory _oldLocked,
        ILockedBalanceIncreasing.LockedBalance memory _newLocked
    ) external;
}
interface IEscrowCurveMath {
    /// @notice Preview the curve coefficients for curves up to quadratic.
    /// @param amount The amount of tokens to calculate the coefficients for - given a fixed algebraic representation
    /// @return coefficients in the form [constant, linear, quadratic]
    /// @dev Not all coefficients are used for all curves
    function getCoefficients(uint256 amount) external view returns (int256[3] memory coefficients);
    /// @notice Bias is the token's voting weight
    function getBias(uint256 timeElapsed, uint256 amount) external view returns (uint256 bias);
}
/*///////////////////////////////////////////////////////////////
                        WARMUP CURVE
//////////////////////////////////////////////////////////////*/
interface IWarmupEvents {
    event WarmupSet(uint48 warmup);
}
interface IWarmup is IWarmupEvents {
    /// @notice Set the warmup period for the curve
    function setWarmupPeriod(uint48 _warmup) external;
    /// @notice the warmup period for the curve
    function warmupPeriod() external view returns (uint48);
    /// @notice check if the curve is past the warming period
    function isWarm(uint256 _tokenId) external view returns (bool);
}
/*///////////////////////////////////////////////////////////////
                        INCREASING CURVE
//////////////////////////////////////////////////////////////*/
/// @dev first version only accounts for token-level point histories
interface IEscrowCurveIncreasing is
    IEscrowCurveCore,
    IEscrowCurveMath,
    IEscrowCurveToken,
    IWarmup
{}// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
interface IDeprecated {
    /// @notice This function is deprecated and should not be used.
    error Deprecated();
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);
    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @notice Signed 18 decimal fixed point (wad) arithmetic library.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SignedWadMath.sol)
/// @author Modified from Remco Bloemen (https://xn--2-umb.com/22/exp-ln/index.html)
/// @dev Will not revert on overflow, only use where overflow is not possible.
function toWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18.
        r := mul(x, 1000000000000000000)
    }
}
/// @dev Takes an integer amount of seconds and converts it to a wad amount of days.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative second amounts, it assumes x is positive.
function toDaysWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and then divide it by 86400.
        r := div(mul(x, 1000000000000000000), 86400)
    }
}
/// @dev Takes a wad amount of days and converts it to an integer amount of seconds.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative day amounts, it assumes x is positive.
function fromDaysWadUnsafe(int256 x) pure returns (uint256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 86400 and then divide it by 1e18.
        r := div(mul(x, 86400), 1000000000000000000)
    }
}
/// @dev Will not revert on overflow, only use where overflow is not possible.
function unsafeWadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by y and divide by 1e18.
        r := sdiv(mul(x, y), 1000000000000000000)
    }
}
/// @dev Will return 0 instead of reverting if y is zero and will
/// not revert on overflow, only use where overflow is not possible.
function unsafeWadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and divide it by y.
        r := sdiv(mul(x, 1000000000000000000), y)
    }
}
function wadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * y in r for now.
        r := mul(x, y)
        // Combined overflow check (`x == 0 || (x * y) / x == y`) and edge case check
        // where x == -1 and y == type(int256).min, for y == -1 and x == min int256,
        // the second overflow check will catch this.
        // See: https://secure-contracts.com/learn_evm/arithmetic-checks.html#arithmetic-checks-for-int256-multiplication
        // Combining into 1 expression saves gas as resulting bytecode will only have 1 `JUMPI`
        // rather than 2.
        if iszero(
            and(
                or(iszero(x), eq(sdiv(r, x), y)),
                or(lt(x, not(0)), sgt(y, 0x8000000000000000000000000000000000000000000000000000000000000000))
            )
        ) {
            revert(0, 0)
        }
        // Scale the result down by 1e18.
        r := sdiv(r, 1000000000000000000)
    }
}
function wadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * 1e18 in r for now.
        r := mul(x, 1000000000000000000)
        // Equivalent to require(y != 0 && ((x * 1e18) / 1e18 == x))
        if iszero(and(iszero(iszero(y)), eq(sdiv(r, 1000000000000000000), x))) {
            revert(0, 0)
        }
        // Divide r by y.
        r := sdiv(r, y)
    }
}
/// @dev Will not work with negative bases, only use when x is positive.
function wadPow(int256 x, int256 y) pure returns (int256) {
    // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)
    return wadExp((wadLn(x) * y) / 1e18); // Using ln(x) means x must be greater than 0.
}
function wadExp(int256 x) pure returns (int256 r) {
    unchecked {
        // When the result is < 0.5 we return zero. This happens when
        // x <= floor(log(0.5e18) * 1e18) ~ -42e18
        if (x <= -42139678854452767551) return 0;
        // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
        // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
        if (x >= 135305999368893231589) revert("EXP_OVERFLOW");
        // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
        // for more intermediate precision and a binary basis. This base conversion
        // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
        x = (x << 78) / 5**18;
        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
        int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;
        x = x - k * 54916777467707473351141471128;
        // k is in the range [-61, 195].
        // Evaluate using a (6, 7)-term rational approximation.
        // p is made monic, we'll multiply by a scale factor later.
        int256 y = x + 1346386616545796478920950773328;
        y = ((y * x) >> 96) + 57155421227552351082224309758442;
        int256 p = y + x - 94201549194550492254356042504812;
        p = ((p * y) >> 96) + 28719021644029726153956944680412240;
        p = p * x + (4385272521454847904659076985693276 << 96);
        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        int256 q = x - 2855989394907223263936484059900;
        q = ((q * x) >> 96) + 50020603652535783019961831881945;
        q = ((q * x) >> 96) - 533845033583426703283633433725380;
        q = ((q * x) >> 96) + 3604857256930695427073651918091429;
        q = ((q * x) >> 96) - 14423608567350463180887372962807573;
        q = ((q * x) >> 96) + 26449188498355588339934803723976023;
        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial won't have zeros in the domain as all its roots are complex.
            // No scaling is necessary because p is already 2**96 too large.
            r := sdiv(p, q)
        }
        // r should be in the range (0.09, 0.25) * 2**96.
        // We now need to multiply r by:
        // * the scale factor s = ~6.031367120.
        // * the 2**k factor from the range reduction.
        // * the 1e18 / 2**96 factor for base conversion.
        // We do this all at once, with an intermediate result in 2**213
        // basis, so the final right shift is always by a positive amount.
        r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
    }
}
function wadLn(int256 x) pure returns (int256 r) {
    unchecked {
        require(x > 0, "UNDEFINED");
        // We want to convert x from 10**18 fixed point to 2**96 fixed point.
        // We do this by multiplying by 2**96 / 10**18. But since
        // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
        // and add ln(2**96 / 10**18) at the end.
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            r := or(r, shl(2, lt(0xf, shr(r, x))))
            r := or(r, shl(1, lt(0x3, shr(r, x))))
            r := or(r, lt(0x1, shr(r, x)))
        }
        // Reduce range of x to (1, 2) * 2**96
        // ln(2^k * x) = k * ln(2) + ln(x)
        int256 k = r - 96;
        x <<= uint256(159 - k);
        x = int256(uint256(x) >> 159);
        // Evaluate using a (8, 8)-term rational approximation.
        // p is made monic, we will multiply by a scale factor later.
        int256 p = x + 3273285459638523848632254066296;
        p = ((p * x) >> 96) + 24828157081833163892658089445524;
        p = ((p * x) >> 96) + 43456485725739037958740375743393;
        p = ((p * x) >> 96) - 11111509109440967052023855526967;
        p = ((p * x) >> 96) - 45023709667254063763336534515857;
        p = ((p * x) >> 96) - 14706773417378608786704636184526;
        p = p * x - (795164235651350426258249787498 << 96);
        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        // q is monic by convention.
        int256 q = x + 5573035233440673466300451813936;
        q = ((q * x) >> 96) + 71694874799317883764090561454958;
        q = ((q * x) >> 96) + 283447036172924575727196451306956;
        q = ((q * x) >> 96) + 401686690394027663651624208769553;
        q = ((q * x) >> 96) + 204048457590392012362485061816622;
        q = ((q * x) >> 96) + 31853899698501571402653359427138;
        q = ((q * x) >> 96) + 909429971244387300277376558375;
        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already 2**96 too large.
            r := sdiv(p, q)
        }
        // r is in the range (0, 0.125) * 2**96
        // Finalization, we need to:
        // * multiply by the scale factor s = 5.549…
        // * add ln(2**96 / 10**18)
        // * add k * ln(2)
        // * multiply by 10**18 / 2**96 = 5**18 >> 78
        // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
        r *= 1677202110996718588342820967067443963516166;
        // add ln(2) * k * 5e18 * 2**192
        r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
        // add ln(2**96 / 10**18) * 5e18 * 2**192
        r += 600920179829731861736702779321621459595472258049074101567377883020018308;
        // base conversion: mul 2**18 / 2**192
        r >>= 174;
    }
}
/// @dev Will return 0 instead of reverting if y is zero.
function unsafeDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Divide x by y.
        r := sdiv(x, y)
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);
    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967Upgradeable {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);
    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);
    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlotUpgradeable {
    struct AddressSlot {
        address value;
    }
    struct BooleanSlot {
        bool value;
    }
    struct Bytes32Slot {
        bytes32 value;
    }
    struct Uint256Slot {
        uint256 value;
    }
    struct StringSlot {
        string value;
    }
    struct BytesSlot {
        bytes value;
    }
    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);
    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);
    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }
    struct BooleanSlot {
        bool value;
    }
    struct Bytes32Slot {
        bytes32 value;
    }
    struct Uint256Slot {
        uint256 value;
    }
    struct StringSlot {
        string value;
    }
    struct BytesSlot {
        bytes value;
    }
    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }
    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721Upgradeable is IERC165Upgradeable {
    /**
     * @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 ERC721 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 ERC721
     * 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 caller.
     *
     * 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 v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);
    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);
    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;
    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }
    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.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, MathUpgradeable.log256(value) + 1);
        }
    }
    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);
    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }
    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }
    mapping(bytes32 => RoleData) private _roles;
    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }
    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }
    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }
    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }
    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }
    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }
    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }
    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");
        _revokeRole(role, account);
    }
    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }
    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }
    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }
    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSetUpgradeable {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.
    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];
        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.
            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;
            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];
                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }
            // Delete the slot where the moved value was stored
            set._values.pop();
            // Delete the index for the deleted slot
            delete set._indexes[value];
            return true;
        } else {
            return false;
        }
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }
    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }
    // Bytes32Set
    struct Bytes32Set {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
    // AddressSet
    struct AddressSet {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
    // UintSet
    struct UintSet {
        Set _inner;
    }
    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }
    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }
    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }
    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }
    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;
        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }
        return result;
    }
}// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
library console {
    address constant CONSOLE_ADDRESS =
        0x000000000000000000636F6e736F6c652e6c6f67;
    function _sendLogPayloadImplementation(bytes memory payload) internal view {
        address consoleAddress = CONSOLE_ADDRESS;
        /// @solidity memory-safe-assembly
        assembly {
            pop(
                staticcall(
                    gas(),
                    consoleAddress,
                    add(payload, 32),
                    mload(payload),
                    0,
                    0
                )
            )
        }
    }
    function _castToPure(
      function(bytes memory) internal view fnIn
    ) internal pure returns (function(bytes memory) pure fnOut) {
        assembly {
            fnOut := fnIn
        }
    }
    function _sendLogPayload(bytes memory payload) internal pure {
        _castToPure(_sendLogPayloadImplementation)(payload);
    }
    function log() internal pure {
        _sendLogPayload(abi.encodeWithSignature("log()"));
    }
    function logInt(int256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
    }
    function logUint(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }
    function logString(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }
    function logBool(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }
    function logAddress(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }
    function logBytes(bytes memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
    }
    function logBytes1(bytes1 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
    }
    function logBytes2(bytes2 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
    }
    function logBytes3(bytes3 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
    }
    function logBytes4(bytes4 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
    }
    function logBytes5(bytes5 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
    }
    function logBytes6(bytes6 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
    }
    function logBytes7(bytes7 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
    }
    function logBytes8(bytes8 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
    }
    function logBytes9(bytes9 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
    }
    function logBytes10(bytes10 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
    }
    function logBytes11(bytes11 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
    }
    function logBytes12(bytes12 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
    }
    function logBytes13(bytes13 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
    }
    function logBytes14(bytes14 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
    }
    function logBytes15(bytes15 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
    }
    function logBytes16(bytes16 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
    }
    function logBytes17(bytes17 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
    }
    function logBytes18(bytes18 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
    }
    function logBytes19(bytes19 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
    }
    function logBytes20(bytes20 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
    }
    function logBytes21(bytes21 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
    }
    function logBytes22(bytes22 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
    }
    function logBytes23(bytes23 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
    }
    function logBytes24(bytes24 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
    }
    function logBytes25(bytes25 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
    }
    function logBytes26(bytes26 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
    }
    function logBytes27(bytes27 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
    }
    function logBytes28(bytes28 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
    }
    function logBytes29(bytes29 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
    }
    function logBytes30(bytes30 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
    }
    function logBytes31(bytes31 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
    }
    function logBytes32(bytes32 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
    }
    function log(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }
    function log(int256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
    }
    function log(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }
    function log(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }
    function log(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }
    function log(uint256 p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
    }
    function log(uint256 p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
    }
    function log(uint256 p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
    }
    function log(uint256 p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
    }
    function log(string memory p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
    }
    function log(string memory p0, int256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1));
    }
    function log(string memory p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
    }
    function log(string memory p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
    }
    function log(string memory p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
    }
    function log(bool p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
    }
    function log(bool p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
    }
    function log(bool p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
    }
    function log(bool p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
    }
    function log(address p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
    }
    function log(address p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
    }
    function log(address p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
    }
    function log(address p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
    }
    function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
    }
    function log(uint256 p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
    }
    function log(uint256 p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
    }
    function log(uint256 p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
    }
    function log(uint256 p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
    }
    function log(uint256 p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
    }
    function log(uint256 p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
    }
    function log(uint256 p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
    }
    function log(uint256 p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
    }
    function log(uint256 p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
    }
    function log(uint256 p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
    }
    function log(uint256 p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
    }
    function log(uint256 p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
    }
    function log(uint256 p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
    }
    function log(uint256 p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
    }
    function log(uint256 p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
    }
    function log(string memory p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
    }
    function log(string memory p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
    }
    function log(string memory p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
    }
    function log(string memory p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
    }
    function log(string memory p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
    }
    function log(string memory p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
    }
    function log(string memory p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
    }
    function log(string memory p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
    }
    function log(string memory p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
    }
    function log(string memory p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
    }
    function log(string memory p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
    }
    function log(string memory p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
    }
    function log(string memory p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
    }
    function log(string memory p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
    }
    function log(string memory p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
    }
    function log(string memory p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
    }
    function log(bool p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
    }
    function log(bool p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
    }
    function log(bool p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
    }
    function log(bool p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
    }
    function log(bool p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
    }
    function log(bool p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
    }
    function log(bool p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
    }
    function log(bool p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
    }
    function log(bool p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
    }
    function log(bool p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
    }
    function log(bool p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
    }
    function log(bool p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
    }
    function log(bool p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
    }
    function log(bool p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
    }
    function log(bool p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
    }
    function log(bool p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
    }
    function log(address p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
    }
    function log(address p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
    }
    function log(address p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
    }
    function log(address p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
    }
    function log(address p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
    }
    function log(address p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
    }
    function log(address p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
    }
    function log(address p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
    }
    function log(address p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
    }
    function log(address p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
    }
    function log(address p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
    }
    function log(address p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
    }
    function log(address p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
    }
    function log(address p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
    }
    function log(address p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
    }
    function log(address p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
    }
    function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
    }
    function log(uint256 p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
    }
    function log(string memory p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
    }
    function log(bool p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
    }
    function log(address p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
    }
    function log(address p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
    }
    function log(address p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
    }
    function log(address p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
 * @dev Required interface of an ERC721 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 ERC721 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 ERC721
     * 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 caller.
     *
     * 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 v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }
    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return 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 {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);
    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);
    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;
    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;
    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}{
  "remappings": [
    "@clock/=lib/ve-governance/src/clock/",
    "@curve/=lib/ve-governance/src/curve/",
    "@delegation/=lib/ve-governance/src/delegation/",
    "@escrow-interfaces/=lib/ve-governance/src/escrow/increasing/interfaces/",
    "@escrow/=lib/ve-governance/src/escrow/",
    "@factory/=lib/ve-governance/src/factory/",
    "@foundry-upgrades/=lib/ve-governance/lib/openzeppelin-foundry-upgrades/src/",
    "@helpers/=lib/ve-governance/test/helpers/",
    "@interfaces/=lib/ve-governance/src/interfaces/",
    "@libs/=lib/ve-governance/src/libs/",
    "@lock/=lib/ve-governance/src/lock/",
    "@mocks/=lib/ve-governance/test/mocks/",
    "@openzeppelin/contracts-upgradeable/=lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/ve-governance/lib/openzeppelin-contracts/contracts/",
    "@queue/=lib/ve-governance/src/queue/",
    "@setup/=lib/ve-governance/src/setup/",
    "@solmate/=lib/ve-governance/lib/solmate/src/",
    "@utils/=lib/ve-governance/src/utils/",
    "@voting/=lib/ve-governance/src/voting/",
    "@ve/=lib/ve-governance/src/",
    "@aragon/protocol-factory/=lib/protocol-factory/",
    "@openzeppelin/openzeppelin-foundry-upgrades/=lib/staged-proposal-processor-plugin/node_modules/@openzeppelin/openzeppelin-foundry-upgrades/src/",
    "@ensdomains/buffer/=lib/protocol-factory/lib/buffer/",
    "@ensdomains/ens-contracts/=lib/protocol-factory/lib/ens-contracts/",
    "@merkl/=lib/merkl/contracts/",
    "@aragon/osx-commons-contracts/=lib/osx-commons/contracts/",
    "@aragon/osx/=lib/ve-governance/lib/osx/packages/contracts/src/",
    "@aragon/multisig-plugin/=lib/protocol-factory/lib/multisig-plugin/packages/contracts/src/",
    "@aragon/admin-plugin/=lib/protocol-factory/lib/admin-plugin/packages/contracts/src/",
    "@aragon/admin/=lib/ve-governance/lib/osx/packages/contracts/src/plugins/governance/admin/",
    "@aragon/multisig/=lib/ve-governance/lib/multisig-plugin/packages/contracts/",
    "@aragon/staged-proposal-processor-plugin/=lib/protocol-factory/lib/staged-proposal-processor-plugin/src/",
    "@aragon/token-voting-plugin/=lib/protocol-factory/lib/token-voting-plugin/src/",
    "@test/=lib/ve-governance/test/",
    "admin-plugin/=lib/protocol-factory/lib/admin-plugin/",
    "buffer/=lib/protocol-factory/lib/buffer/contracts/",
    "ds-test/=lib/ve-governance/lib/ds-test/src/",
    "ens-contracts/=lib/ve-governance/lib/ens-contracts/contracts/",
    "erc4626-tests/=lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "merkl/=lib/merkl/",
    "multisig-plugin/=lib/ve-governance/lib/multisig-plugin/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/ve-governance/lib/openzeppelin-foundry-upgrades/src/",
    "openzeppelin/=lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/",
    "osx-commons/=lib/osx-commons/",
    "osx/=lib/osx/",
    "oz/=lib/merkl/node_modules/@openzeppelin/contracts/",
    "plugin-version-1.3/=lib/protocol-factory/lib/token-voting-plugin/lib/plugin-version-1.3/",
    "protocol-factory/=lib/protocol-factory/",
    "solidity-stringutils/=lib/protocol-factory/lib/staged-proposal-processor-plugin/node_modules/solidity-stringutils/",
    "solmate/=lib/ve-governance/lib/solmate/src/",
    "staged-proposal-processor-plugin/=lib/protocol-factory/lib/staged-proposal-processor-plugin/src/",
    "token-voting-plugin/=lib/protocol-factory/lib/token-voting-plugin/",
    "utils/=lib/ve-governance/test/utils/",
    "ve-governance/=lib/ve-governance/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 2000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": false
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"components":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"autoCompoundStrategy","type":"address"},{"internalType":"address","name":"defaultStrategy","type":"address"},{"internalType":"address","name":"vkatMetadata","type":"address"}],"internalType":"struct BaseContracts","name":"_bases","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"components":[{"internalType":"address","name":"merklDistributor","type":"address"},{"internalType":"address","name":"dao","type":"address"},{"internalType":"address","name":"escrow","type":"address"}],"internalType":"struct DeploymentParameters","name":"_params","type":"tuple"}],"name":"deployOnce","outputs":[{"components":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"autoCompoundStrategy","type":"address"},{"internalType":"address","name":"defaultStrategy","type":"address"},{"internalType":"address","name":"swapper","type":"address"},{"internalType":"address","name":"vkatMetadata","type":"address"}],"internalType":"struct Deployment","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x608060405234801562000010575f80fd5b5060405162002fe138038062002fe18339810160408190526200003391620000bc565b5f8054336001600160a01b03199182161790915581516001805483166001600160a01b03928316179055602083015160028054841691831691909117905560408301516003805484169183169190911790556060909201516004805490921692169190911790556200014c565b80516001600160a01b0381168114620000b7575f80fd5b919050565b5f60808284031215620000cd575f80fd5b604051608081016001600160401b0381118282101715620000fc57634e487b7160e01b5f52604160045260245ffd5b6040526200010a83620000a0565b81526200011a60208401620000a0565b60208201526200012d60408401620000a0565b60408201526200014060608401620000a0565b60608201529392505050565b612e87806200015a5f395ff3fe608060405234801562000010575f80fd5b50600436106200002c575f3560e01c8063505992e71462000030575b5f80fd5b6200004762000041366004620011cb565b620000a0565b60405162000097919081516001600160a01b039081168252602080840151821690830152604080840151821690830152606080840151821690830152608092830151169181019190915260a00190565b60405180910390f35b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f546001600160a01b0316331462000143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600960248201527f4e4f545f4f574e4552000000000000000000000000000000000000000000000060448201526064015b60405180910390fd5b6008546001600160a01b031615620001b8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f414c52454144595f4445504c4f5945440000000000000000000000000000000060448201526064016200013a565b602082015160408084015190516001600160a01b039283166024820152911660448201525f6064820152620002409060840160408051601f198184030181529190526020810180516001600160e01b03167fc0c53b8b000000000000000000000000000000000000000000000000000000001790526003546001600160a01b03169062000760565b600a805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283169081179091556020840151604080860151905191841660248301529092166044830152606482015260a06084820152601460c48201527f4175746f636f6d706f756e64696e6720764b415400000000000000000000000060e482015260e060a482015260056101048201527f61764b415400000000000000000000000000000000000000000000000000000061012482015262000357906101440160408051601f198184030181529190526020810180516001600160e01b03167f83b43589000000000000000000000000000000000000000000000000000000001790526001546001600160a01b03169062000760565b6008805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03928316908117909155600a546040517f8c5f36bb000000000000000000000000000000000000000000000000000000008152600481019290925290911690638c5f36bb906024015f604051808303815f87803b158015620003d9575f80fd5b505af1158015620003ec573d5f803e3d5ffd5b505050505f82604001516001600160a01b031663bee266096040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000432573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000458919062001245565b90506200046d835f01518460400151620007a0565b600b805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039290921691909117905560208301516200053b90825f604051908082528060200260200182016040528015620004d0578160200160208202803683370190505b50604051602401620004e5939291906200126a565b60408051601f198184030181529190526020810180516001600160e01b03167f77a24f36000000000000000000000000000000000000000000000000000000001790526004546001600160a01b03169062000760565b600c805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556020840151604080860151600b546008548851935194861660248601529185166044850152841660648401528316608483015290911660a4820152620005fd9060c40160408051601f198184030181529190526020810180516001600160e01b03167f1459457a000000000000000000000000000000000000000000000000000000001790526002546001600160a01b03169062000760565b6009805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03928316908117909155602085810151604080880151815160a0810183526008548716815293840194909452600a54851690830152600b5484166060830152600c5490931660808201525f926200067a9290918590620007ec565b60208501516040517fc71bf3240000000000000000000000000000000000000000000000000000000081529192506001600160a01b03169063c71bf32490620006cc90309085905f9060040162001321565b5f604051808303815f875af1158015620006e8573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052620007119190810190620013da565b50506040805160a0810182526008546001600160a01b03908116825260095481166020830152600a54811692820192909252600b5482166060820152600c549091166080820152949350505050565b5f828260405162000771906200114f565b6200077e92919062001502565b604051809103905ff08015801562000798573d5f803e3d5ffd5b509392505050565b5f808383604051620007b2906200115d565b6001600160a01b03928316815291166020820152604001604051809103905ff080158015620007e3573d5f803e3d5ffd5b50949350505050565b60408051600680825260e082019092526060915f9190816020015b6040805160a0810182525f808252602080830182905292820181905260608201819052608082015282527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90920191018162000807579050506040805160a08101909152909150805f815260200184608001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184608001516001600160a01b03166375b238fc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620008e7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200090d91906200152d565b815250815f8151811062000925576200092562001545565b60209081029190910101526040805160a08101909152805f815260200184602001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184602001516001600160a01b031663c67d161d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620009b4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620009da91906200152d565b81525081600181518110620009f357620009f362001545565b60209081029190910101526040805160a08101909152805f815260200184604001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184604001516001600160a01b0316639eee24a06040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000a82573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000aa891906200152d565b8152508160028151811062000ac15762000ac162001545565b60209081029190910101526040805160a08101909152805f8152602001845f01516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b03168152602001845f01516001600160a01b0316639e3411196040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000b4e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000b7491906200152d565b8152508160038151811062000b8d5762000b8d62001545565b60209081029190910101526040805160a08101909152805f8152602001845f01516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b03168152602001845f01516001600160a01b0316635f82abb96040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000c1a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000c4091906200152d565b8152508160048151811062000c595762000c5962001545565b60209081029190910101526040805160a081019091528060018152602001876001600160a01b03168152602001306001600160a01b031681526020015f6001600160a01b03168152602001876001600160a01b0316630729d0546040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000ce1573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000d0791906200152d565b8152508160058151811062000d205762000d2062001545565b602090810291909101015260408051600680825260e082019092525f91816020015b60408051606080820183525f80835260208301529181019190915281526020019060019003908162000d4257905050905086815f8151811062000d895762000d8962001545565b60209081029190910101516001600160a01b03909116905260405162000db490839060240162001559565b60408051601f198184030181529190526020810180516001600160e01b03167fe978afe500000000000000000000000000000000000000000000000000000000179052815182905f9062000e0c5762000e0c62001545565b602002602001015160400181905250848160018151811062000e325762000e3262001545565b60209081029190910101516001600160a01b0391821690528451604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600190811062000ea25762000ea262001545565b602002602001015160400181905250848160028151811062000ec85762000ec862001545565b60209081029190910101516001600160a01b0391821690526040858101519051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600290811062000f3b5762000f3b62001545565b602002602001015160400181905250848160038151811062000f615762000f6162001545565b6020908102919091018101516001600160a01b039283169052850151604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600390811062000fd35762000fd362001545565b602002602001015160400181905250858160048151811062000ff95762000ff962001545565b60209081029190910101516001600160a01b0391821690526040858101519051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b03167fd68e8ecc0000000000000000000000000000000000000000000000000000000017905281518290600490811062001085576200108562001545565b6020026020010151604001819052508581600581518110620010ab57620010ab62001545565b6020908102919091018101516001600160a01b039283169052850151604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b03167fd68e8ecc0000000000000000000000000000000000000000000000000000000017905281518290600590811062001136576200113662001545565b6020908102919091010151604001529695505050505050565b61049b80620015f683390190565b6113f68062001a9183390190565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715620011ab57620011ab6200116b565b604052919050565b6001600160a01b0381168114620011c8575f80fd5b50565b5f60608284031215620011dc575f80fd5b6040516060810181811067ffffffffffffffff821117156200120257620012026200116b565b60405282356200121281620011b3565b815260208301356200122481620011b3565b602082015260408301356200123981620011b3565b60408201529392505050565b5f6020828403121562001256575f80fd5b81516200126381620011b3565b9392505050565b5f606082016001600160a01b03808716845260208187166020860152606060408601528286518085526080870191506020880194505f5b81811015620012c1578551851683529483019491830191600101620012a1565b50909998505050505050505050565b5f5b83811015620012ec578181015183820152602001620012d2565b50505f910152565b5f81518084526200130d816020860160208601620012d0565b601f01601f19169290920160200192915050565b5f6060808301868452602060608186015281875180845260808701915060808160051b88010193508289015f5b82811015620013c3578886037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80018452815180516001600160a01b031687528581015186880152604090810151908701889052620013af88880182620012f4565b96505092840192908401906001016200134e565b505050505060409390930193909352509392505050565b5f806040808486031215620013ed575f80fd5b835167ffffffffffffffff8082111562001405575f80fd5b8186019150601f87601f8401126200141b575f80fd5b82516020838211156200143257620014326200116b565b8160051b620014438282016200117f565b928352858101820192828101908c8511156200145d575f80fd5b83880192505b84831015620014ed578251878111156200147b575f80fd5b8801603f81018e136200148c575f80fd5b8481015188811115620014a357620014a36200116b565b620014b686601f198a840116016200117f565b8181528f8c838501011115620014ca575f80fd5b620014db828883018e8601620012d0565b84525050918301919083019062001463565b9a90920151999b999a50505050505050505050565b6001600160a01b0383168152604060208201525f620015256040830184620012f4565b949350505050565b5f602082840312156200153e575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f919060409081850190868401855b82811015620015e85781518051600381106200159f57634e487b7160e01b5f52602160045260245ffd5b8552808701516001600160a01b039081168887015286820151811687870152606080830151909116908601526080908101519085015260a0909301929085019060010162001575565b509197965050505050505056fe608060405260405161049b38038061049b833981016040819052610022916102d2565b61002d82825f610034565b50506103e7565b61003d8361005f565b5f825111806100495750805b1561005a57610058838361009e565b505b505050565b610068816100ca565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a250565b60606100c383836040518060600160405280602781526020016104746027913961017d565b9392505050565b6001600160a01b0381163b61013c5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f80856001600160a01b031685604051610199919061039a565b5f60405180830381855af49150503d805f81146101d1576040519150601f19603f3d011682016040523d82523d5f602084013e6101d6565b606091505b5090925090506101e8868383876101f2565b9695505050505050565b606083156102605782515f03610259576001600160a01b0385163b6102595760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610133565b508161026a565b61026a8383610272565b949350505050565b8151156102825781518083602001fd5b8060405162461bcd60e51b815260040161013391906103b5565b634e487b7160e01b5f52604160045260245ffd5b5f5b838110156102ca5781810151838201526020016102b2565b50505f910152565b5f80604083850312156102e3575f80fd5b82516001600160a01b03811681146102f9575f80fd5b60208401519092506001600160401b0380821115610315575f80fd5b818501915085601f830112610328575f80fd5b81518181111561033a5761033a61029c565b604051601f8201601f19908116603f011681019083821181831017156103625761036261029c565b8160405282815288602084870101111561037a575f80fd5b61038b8360208301602088016102b0565b80955050505050509250929050565b5f82516103ab8184602087016102b0565b9190910192915050565b602081525f82518060208401526103d38160408501602087016102b0565b601f01601f19169190910160400192915050565b6081806103f35f395ff3fe608060405236601057600e6013565b005b600e5b601f601b6021565b6064565b565b5f605f7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b905090565b365f80375f80365f845af43d5f803e808015607d573d5ff35b3d5ffd416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c656460e060405234801562000010575f80fd5b50604051620013f6380380620013f68339810160408190526200003391620000dd565b60015f556001600160a01b03808316608052811660a081905260408051637e062a3560e11b8152905163fc0c546a916004808201926020929091908290030181865afa15801562000086573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620000ac919062000113565b6001600160a01b031660c05250620001369050565b80516001600160a01b0381168114620000d8575f80fd5b919050565b5f8060408385031215620000ef575f80fd5b620000fa83620000c1565b91506200010a60208401620000c1565b90509250929050565b5f6020828403121562000124575f80fd5b6200012f82620000c1565b9392505050565b60805160a05160c051611266620001905f395f8181605d015281816102f40152818161072f015261085d01525f8181610108015281816106fc01526107d501525f818160d50152818161021401526104f901526112665ff3fe608060405260043610610041575f3560e01c80632fe319da1461004c5780633740a9dc1461009c578063acc2166a146100c4578063e2fdcc17146100f7575f80fd5b3661004857005b5f80fd5b348015610057575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100af6100aa366004610b62565b61012a565b60408051928352602083019190915201610093565b3480156100cf575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b348015610102575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b5f8061013461040f565b612710831115610170576040517f4ea8406d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f61017b8780610c01565b905067ffffffffffffffff81111561019557610195610c4e565b6040519080825280602002602001820160405280156101be578160200160208202803683370190505b5090505f5b6101cd8880610c01565b905081101561020957338282815181106101e9576101e9610c62565b6001600160a01b03909216602092830291909101909101526001016101c3565b506001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166371ee95c0826102448a80610c01565b61025160208d018d610c01565b61025e60408f018f610c01565b6040518863ffffffff1660e01b81526004016102809796959493929190610d1f565b5f604051808303815f87803b158015610297575f80fd5b505af11580156102a9573d5f803e3d5ffd5b505050505f6102c38787906102be9190610e82565b61046b565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610341573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103659190610f94565b935061038260405180604001604052805f81526020015f81525090565b8415610395576103928686610685565b90505b61039d61088b565b337f043b6dc983aced20ddbda9755d23a163e8ad65335d3087e29b668d11f5bddae36103c98b80610c01565b6103d660208e018e610c01565b8b878f8f8b6040516103f099989796959493929190611050565b60405180910390a2519250505061040660015f55565b94509492505050565b60025f54036104655760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b60025f55565b80516060905f81900361047e5750919050565b8067ffffffffffffffff81111561049757610497610c4e565b6040519080825280602002602001820160405280156104ca57816020015b60608152602001906001900390816104b55790505b5091505f5b8181101561067e575f8482815181106104ea576104ea610c62565b60200260200101515f015190507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316816001600160a01b031603610562576040517ff8434ab800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f80826001600160a01b031687858151811061058057610580610c62565b60200260200101516020015188868151811061059e5761059e610c62565b6020026020010151604001516040516105b791906111b0565b5f6040518083038185875af1925050503d805f81146105f1576040519150601f19603f3d011682016040523d82523d5f602084013e6105f6565b606091505b50915091508086858151811061060e5761060e610c62565b602002602001018190525061066e82826040518060400160405280600c81526020017f416374696f6e4661696c65640000000000000000000000000000000000000000815250866001600160a01b03166108d2909392919063ffffffff16565b5050600190920191506104cf9050565b5050919050565b604080518082019091525f808252602082015281831561084a576127106106ac85856111df565b6106b691906111fc565b602083018190526106c7908461121b565b60208301516040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015260248201929092529192507f0000000000000000000000000000000000000000000000000000000000000000169063095ea7b3906044016020604051808303815f875af1158015610775573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610799919061122e565b5060208201516040517fa039d32c00000000000000000000000000000000000000000000000000000000815260048101919091523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a039d32c906044016020604051808303815f875af1158015610823573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108479190610f94565b82525b8015610884576108846001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163383610952565b5092915050565b604051339047905f81818185875af1925050503d805f81146108c8576040519150601f19603f3d011682016040523d82523d5f602084013e505050565b606091505b505050565b606083156109405782515f03610939576001600160a01b0385163b6109395760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161045c565b508161094a565b61094a83836109d2565b949350505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001790526108cd9084906109fc565b8151156109e25781518083602001fd5b8060405162461bcd60e51b815260040161045c9190611254565b5f610a50826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610ae29092919063ffffffff16565b905080515f1480610a70575080806020019051810190610a70919061122e565b6108cd5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f74207375636365656400000000000000000000000000000000000000000000606482015260840161045c565b606061094a84845f85855f80866001600160a01b03168587604051610b0791906111b0565b5f6040518083038185875af1925050503d805f8114610b41576040519150601f19603f3d011682016040523d82523d5f602084013e610b46565b606091505b5091509150610b57878383876108d2565b979650505050505050565b5f805f8060608587031215610b75575f80fd5b843567ffffffffffffffff80821115610b8c575f80fd5b9086019060608289031215610b9f575f80fd5b90945060208601359080821115610bb4575f80fd5b818701915087601f830112610bc7575f80fd5b813581811115610bd5575f80fd5b8860208260051b8501011115610be9575f80fd5b95986020929092019750949560400135945092505050565b5f808335601e19843603018112610c16575f80fd5b83018035915067ffffffffffffffff821115610c30575f80fd5b6020019150600581901b3603821315610c47575f80fd5b9250929050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b80356001600160a01b0381168114610c8c575f80fd5b919050565b8183525f60208085019450825f5b85811015610ccb576001600160a01b03610cb883610c76565b1687529582019590820190600101610c9f565b509495945050505050565b8183525f7f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115610d06575f80fd5b8260051b80836020870137939093016020019392505050565b608080825288519082018190525f9060209060a0840190828c01845b82811015610d605781516001600160a01b031684529284019290840190600101610d3b565b50505083810382850152610d75818a8c610c91565b90508381036040850152610d8a81888a610cd6565b84810360608601528581529050818101600586811b83018401885f5b89811015610e1457601f198684030185528135601e198c3603018112610dca575f80fd5b8b01878101903567ffffffffffffffff811115610de5575f80fd5b80861b3603821315610df5575f80fd5b610e00858284610cd6565b968901969450505090860190600101610da6565b50909e9d5050505050505050505050505050565b6040516060810167ffffffffffffffff81118282101715610e4b57610e4b610c4e565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610e7a57610e7a610c4e565b604052919050565b5f67ffffffffffffffff80841115610e9c57610e9c610c4e565b8360051b6020610ead818301610e51565b868152918501918181019036841115610ec4575f80fd5b865b84811015610f8857803586811115610edc575f80fd5b88016060368290031215610eee575f80fd5b610ef6610e28565b610eff82610c76565b8152858201358682015260408083013589811115610f1b575f80fd5b9290920191601f3681850112610f2f575f80fd5b83358a811115610f4157610f41610c4e565b610f5289601f198484011601610e51565b91508082523689828701011115610f67575f80fd5b808986018a8401375f90820189015290820152845250918301918301610ec6565b50979650505050505050565b5f60208284031215610fa4575f80fd5b5051919050565b5f5b83811015610fc5578181015183820152602001610fad565b50505f910152565b5f8151808452610fe4816020860160208601610fab565b601f01601f19169290920160200192915050565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561104357601f19868403018952611031838351610fcd565b98840198925090830190600101611015565b5090979650505050505050565b60e081525f61106360e083018b8d610c91565b602083820381850152611077828b8d610cd6565b915088604085015260608851606086015281890151608081608088015286850360a08801528491508885528385019150838960051b8601018a5f5b8b81101561118657601f198089850301865282357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa18f36030181126110f5575f80fd5b8e016001600160a01b0361110882610c76565b16855288810135898601526040810135601e19823603018112611129575f80fd5b01888101903567ffffffffffffffff811115611143575f80fd5b803603821315611151575f80fd5b88604087015280898701528082888801375f86820188015296890196601f0190911690930184019250908601906001016110b2565b505087810360c089015261119a818a610ff8565b96505050505050509a9950505050505050505050565b5f82516111c1818460208701610fab565b9190910192915050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176111f6576111f66111cb565b92915050565b5f8261121657634e487b7160e01b5f52601260045260245ffd5b500490565b818103818111156111f6576111f66111cb565b5f6020828403121561123e575f80fd5b8151801515811461124d575f80fd5b9392505050565b602081525f61124d6020830184610fcd560000000000000000000000009911af893015d78bf99e2a883e1b3bc4d008ab9c0000000000000000000000002aca6c99155fee6ce4e59358be9a6b34f57a49ed000000000000000000000000fbdb76fd8ac8d9374a0c73e1a0d59972f0d8dd110000000000000000000000005b0dd6d431692255cda6311708275d2525d69bd7
Deployed Bytecode
0x608060405234801562000010575f80fd5b50600436106200002c575f3560e01c8063505992e71462000030575b5f80fd5b6200004762000041366004620011cb565b620000a0565b60405162000097919081516001600160a01b039081168252602080840151821690830152604080840151821690830152606080840151821690830152608092830151169181019190915260a00190565b60405180910390f35b6040805160a0810182525f808252602082018190529181018290526060810182905260808101919091525f546001600160a01b0316331462000143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600960248201527f4e4f545f4f574e4552000000000000000000000000000000000000000000000060448201526064015b60405180910390fd5b6008546001600160a01b031615620001b8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f414c52454144595f4445504c4f5945440000000000000000000000000000000060448201526064016200013a565b602082015160408084015190516001600160a01b039283166024820152911660448201525f6064820152620002409060840160408051601f198184030181529190526020810180516001600160e01b03167fc0c53b8b000000000000000000000000000000000000000000000000000000001790526003546001600160a01b03169062000760565b600a805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283169081179091556020840151604080860151905191841660248301529092166044830152606482015260a06084820152601460c48201527f4175746f636f6d706f756e64696e6720764b415400000000000000000000000060e482015260e060a482015260056101048201527f61764b415400000000000000000000000000000000000000000000000000000061012482015262000357906101440160408051601f198184030181529190526020810180516001600160e01b03167f83b43589000000000000000000000000000000000000000000000000000000001790526001546001600160a01b03169062000760565b6008805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03928316908117909155600a546040517f8c5f36bb000000000000000000000000000000000000000000000000000000008152600481019290925290911690638c5f36bb906024015f604051808303815f87803b158015620003d9575f80fd5b505af1158015620003ec573d5f803e3d5ffd5b505050505f82604001516001600160a01b031663bee266096040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000432573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000458919062001245565b90506200046d835f01518460400151620007a0565b600b805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039290921691909117905560208301516200053b90825f604051908082528060200260200182016040528015620004d0578160200160208202803683370190505b50604051602401620004e5939291906200126a565b60408051601f198184030181529190526020810180516001600160e01b03167f77a24f36000000000000000000000000000000000000000000000000000000001790526004546001600160a01b03169062000760565b600c805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556020840151604080860151600b546008548851935194861660248601529185166044850152841660648401528316608483015290911660a4820152620005fd9060c40160408051601f198184030181529190526020810180516001600160e01b03167f1459457a000000000000000000000000000000000000000000000000000000001790526002546001600160a01b03169062000760565b6009805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03928316908117909155602085810151604080880151815160a0810183526008548716815293840194909452600a54851690830152600b5484166060830152600c5490931660808201525f926200067a9290918590620007ec565b60208501516040517fc71bf3240000000000000000000000000000000000000000000000000000000081529192506001600160a01b03169063c71bf32490620006cc90309085905f9060040162001321565b5f604051808303815f875af1158015620006e8573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052620007119190810190620013da565b50506040805160a0810182526008546001600160a01b03908116825260095481166020830152600a54811692820192909252600b5482166060820152600c549091166080820152949350505050565b5f828260405162000771906200114f565b6200077e92919062001502565b604051809103905ff08015801562000798573d5f803e3d5ffd5b509392505050565b5f808383604051620007b2906200115d565b6001600160a01b03928316815291166020820152604001604051809103905ff080158015620007e3573d5f803e3d5ffd5b50949350505050565b60408051600680825260e082019092526060915f9190816020015b6040805160a0810182525f808252602080830182905292820181905260608201819052608082015282527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90920191018162000807579050506040805160a08101909152909150805f815260200184608001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184608001516001600160a01b03166375b238fc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620008e7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906200090d91906200152d565b815250815f8151811062000925576200092562001545565b60209081029190910101526040805160a08101909152805f815260200184602001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184602001516001600160a01b031663c67d161d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015620009b4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620009da91906200152d565b81525081600181518110620009f357620009f362001545565b60209081029190910101526040805160a08101909152805f815260200184604001516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b0316815260200184604001516001600160a01b0316639eee24a06040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000a82573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000aa891906200152d565b8152508160028151811062000ac15762000ac162001545565b60209081029190910101526040805160a08101909152805f8152602001845f01516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b03168152602001845f01516001600160a01b0316639e3411196040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000b4e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000b7491906200152d565b8152508160038151811062000b8d5762000b8d62001545565b60209081029190910101526040805160a08101909152805f8152602001845f01516001600160a01b03168152602001876001600160a01b031681526020015f6001600160a01b03168152602001845f01516001600160a01b0316635f82abb96040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000c1a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000c4091906200152d565b8152508160048151811062000c595762000c5962001545565b60209081029190910101526040805160a081019091528060018152602001876001600160a01b03168152602001306001600160a01b031681526020015f6001600160a01b03168152602001876001600160a01b0316630729d0546040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000ce1573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019062000d0791906200152d565b8152508160058151811062000d205762000d2062001545565b602090810291909101015260408051600680825260e082019092525f91816020015b60408051606080820183525f80835260208301529181019190915281526020019060019003908162000d4257905050905086815f8151811062000d895762000d8962001545565b60209081029190910101516001600160a01b03909116905260405162000db490839060240162001559565b60408051601f198184030181529190526020810180516001600160e01b03167fe978afe500000000000000000000000000000000000000000000000000000000179052815182905f9062000e0c5762000e0c62001545565b602002602001015160400181905250848160018151811062000e325762000e3262001545565b60209081029190910101516001600160a01b0391821690528451604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600190811062000ea25762000ea262001545565b602002602001015160400181905250848160028151811062000ec85762000ec862001545565b60209081029190910101516001600160a01b0391821690526040858101519051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600290811062000f3b5762000f3b62001545565b602002602001015160400181905250848160038151811062000f615762000f6162001545565b6020908102919091018101516001600160a01b039283169052850151604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b0316639281aa0b60e01b17905281518290600390811062000fd35762000fd362001545565b602002602001015160400181905250858160048151811062000ff95762000ff962001545565b60209081029190910101516001600160a01b0391821690526040858101519051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b03167fd68e8ecc0000000000000000000000000000000000000000000000000000000017905281518290600490811062001085576200108562001545565b6020026020010151604001819052508581600581518110620010ab57620010ab62001545565b6020908102919091018101516001600160a01b039283169052850151604051911660248201526001604482015260640160408051601f198184030181529190526020810180516001600160e01b03167fd68e8ecc0000000000000000000000000000000000000000000000000000000017905281518290600590811062001136576200113662001545565b6020908102919091010151604001529695505050505050565b61049b80620015f683390190565b6113f68062001a9183390190565b634e487b7160e01b5f52604160045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715620011ab57620011ab6200116b565b604052919050565b6001600160a01b0381168114620011c8575f80fd5b50565b5f60608284031215620011dc575f80fd5b6040516060810181811067ffffffffffffffff821117156200120257620012026200116b565b60405282356200121281620011b3565b815260208301356200122481620011b3565b602082015260408301356200123981620011b3565b60408201529392505050565b5f6020828403121562001256575f80fd5b81516200126381620011b3565b9392505050565b5f606082016001600160a01b03808716845260208187166020860152606060408601528286518085526080870191506020880194505f5b81811015620012c1578551851683529483019491830191600101620012a1565b50909998505050505050505050565b5f5b83811015620012ec578181015183820152602001620012d2565b50505f910152565b5f81518084526200130d816020860160208601620012d0565b601f01601f19169290920160200192915050565b5f6060808301868452602060608186015281875180845260808701915060808160051b88010193508289015f5b82811015620013c3578886037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80018452815180516001600160a01b031687528581015186880152604090810151908701889052620013af88880182620012f4565b96505092840192908401906001016200134e565b505050505060409390930193909352509392505050565b5f806040808486031215620013ed575f80fd5b835167ffffffffffffffff8082111562001405575f80fd5b8186019150601f87601f8401126200141b575f80fd5b82516020838211156200143257620014326200116b565b8160051b620014438282016200117f565b928352858101820192828101908c8511156200145d575f80fd5b83880192505b84831015620014ed578251878111156200147b575f80fd5b8801603f81018e136200148c575f80fd5b8481015188811115620014a357620014a36200116b565b620014b686601f198a840116016200117f565b8181528f8c838501011115620014ca575f80fd5b620014db828883018e8601620012d0565b84525050918301919083019062001463565b9a90920151999b999a50505050505050505050565b6001600160a01b0383168152604060208201525f620015256040830184620012f4565b949350505050565b5f602082840312156200153e575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b602080825282518282018190525f919060409081850190868401855b82811015620015e85781518051600381106200159f57634e487b7160e01b5f52602160045260245ffd5b8552808701516001600160a01b039081168887015286820151811687870152606080830151909116908601526080908101519085015260a0909301929085019060010162001575565b509197965050505050505056fe608060405260405161049b38038061049b833981016040819052610022916102d2565b61002d82825f610034565b50506103e7565b61003d8361005f565b5f825111806100495750805b1561005a57610058838361009e565b505b505050565b610068816100ca565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b905f90a250565b60606100c383836040518060600160405280602781526020016104746027913961017d565b9392505050565b6001600160a01b0381163b61013c5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b60605f80856001600160a01b031685604051610199919061039a565b5f60405180830381855af49150503d805f81146101d1576040519150601f19603f3d011682016040523d82523d5f602084013e6101d6565b606091505b5090925090506101e8868383876101f2565b9695505050505050565b606083156102605782515f03610259576001600160a01b0385163b6102595760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610133565b508161026a565b61026a8383610272565b949350505050565b8151156102825781518083602001fd5b8060405162461bcd60e51b815260040161013391906103b5565b634e487b7160e01b5f52604160045260245ffd5b5f5b838110156102ca5781810151838201526020016102b2565b50505f910152565b5f80604083850312156102e3575f80fd5b82516001600160a01b03811681146102f9575f80fd5b60208401519092506001600160401b0380821115610315575f80fd5b818501915085601f830112610328575f80fd5b81518181111561033a5761033a61029c565b604051601f8201601f19908116603f011681019083821181831017156103625761036261029c565b8160405282815288602084870101111561037a575f80fd5b61038b8360208301602088016102b0565b80955050505050509250929050565b5f82516103ab8184602087016102b0565b9190910192915050565b602081525f82518060208401526103d38160408501602087016102b0565b601f01601f19169190910160400192915050565b6081806103f35f395ff3fe608060405236601057600e6013565b005b600e5b601f601b6021565b6064565b565b5f605f7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b905090565b365f80375f80365f845af43d5f803e808015607d573d5ff35b3d5ffd416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c656460e060405234801562000010575f80fd5b50604051620013f6380380620013f68339810160408190526200003391620000dd565b60015f556001600160a01b03808316608052811660a081905260408051637e062a3560e11b8152905163fc0c546a916004808201926020929091908290030181865afa15801562000086573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190620000ac919062000113565b6001600160a01b031660c05250620001369050565b80516001600160a01b0381168114620000d8575f80fd5b919050565b5f8060408385031215620000ef575f80fd5b620000fa83620000c1565b91506200010a60208401620000c1565b90509250929050565b5f6020828403121562000124575f80fd5b6200012f82620000c1565b9392505050565b60805160a05160c051611266620001905f395f8181605d015281816102f40152818161072f015261085d01525f8181610108015281816106fc01526107d501525f818160d50152818161021401526104f901526112665ff3fe608060405260043610610041575f3560e01c80632fe319da1461004c5780633740a9dc1461009c578063acc2166a146100c4578063e2fdcc17146100f7575f80fd5b3661004857005b5f80fd5b348015610057575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b6100af6100aa366004610b62565b61012a565b60408051928352602083019190915201610093565b3480156100cf575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b348015610102575f80fd5b5061007f7f000000000000000000000000000000000000000000000000000000000000000081565b5f8061013461040f565b612710831115610170576040517f4ea8406d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f61017b8780610c01565b905067ffffffffffffffff81111561019557610195610c4e565b6040519080825280602002602001820160405280156101be578160200160208202803683370190505b5090505f5b6101cd8880610c01565b905081101561020957338282815181106101e9576101e9610c62565b6001600160a01b03909216602092830291909101909101526001016101c3565b506001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166371ee95c0826102448a80610c01565b61025160208d018d610c01565b61025e60408f018f610c01565b6040518863ffffffff1660e01b81526004016102809796959493929190610d1f565b5f604051808303815f87803b158015610297575f80fd5b505af11580156102a9573d5f803e3d5ffd5b505050505f6102c38787906102be9190610e82565b61046b565b6040517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610341573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103659190610f94565b935061038260405180604001604052805f81526020015f81525090565b8415610395576103928686610685565b90505b61039d61088b565b337f043b6dc983aced20ddbda9755d23a163e8ad65335d3087e29b668d11f5bddae36103c98b80610c01565b6103d660208e018e610c01565b8b878f8f8b6040516103f099989796959493929190611050565b60405180910390a2519250505061040660015f55565b94509492505050565b60025f54036104655760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b60025f55565b80516060905f81900361047e5750919050565b8067ffffffffffffffff81111561049757610497610c4e565b6040519080825280602002602001820160405280156104ca57816020015b60608152602001906001900390816104b55790505b5091505f5b8181101561067e575f8482815181106104ea576104ea610c62565b60200260200101515f015190507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316816001600160a01b031603610562576040517ff8434ab800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f80826001600160a01b031687858151811061058057610580610c62565b60200260200101516020015188868151811061059e5761059e610c62565b6020026020010151604001516040516105b791906111b0565b5f6040518083038185875af1925050503d805f81146105f1576040519150601f19603f3d011682016040523d82523d5f602084013e6105f6565b606091505b50915091508086858151811061060e5761060e610c62565b602002602001018190525061066e82826040518060400160405280600c81526020017f416374696f6e4661696c65640000000000000000000000000000000000000000815250866001600160a01b03166108d2909392919063ffffffff16565b5050600190920191506104cf9050565b5050919050565b604080518082019091525f808252602082015281831561084a576127106106ac85856111df565b6106b691906111fc565b602083018190526106c7908461121b565b60208301516040517f095ea7b30000000000000000000000000000000000000000000000000000000081526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116600483015260248201929092529192507f0000000000000000000000000000000000000000000000000000000000000000169063095ea7b3906044016020604051808303815f875af1158015610775573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610799919061122e565b5060208201516040517fa039d32c00000000000000000000000000000000000000000000000000000000815260048101919091523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063a039d32c906044016020604051808303815f875af1158015610823573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108479190610f94565b82525b8015610884576108846001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163383610952565b5092915050565b604051339047905f81818185875af1925050503d805f81146108c8576040519150601f19603f3d011682016040523d82523d5f602084013e505050565b606091505b505050565b606083156109405782515f03610939576001600160a01b0385163b6109395760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161045c565b508161094a565b61094a83836109d2565b949350505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001790526108cd9084906109fc565b8151156109e25781518083602001fd5b8060405162461bcd60e51b815260040161045c9190611254565b5f610a50826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610ae29092919063ffffffff16565b905080515f1480610a70575080806020019051810190610a70919061122e565b6108cd5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f74207375636365656400000000000000000000000000000000000000000000606482015260840161045c565b606061094a84845f85855f80866001600160a01b03168587604051610b0791906111b0565b5f6040518083038185875af1925050503d805f8114610b41576040519150601f19603f3d011682016040523d82523d5f602084013e610b46565b606091505b5091509150610b57878383876108d2565b979650505050505050565b5f805f8060608587031215610b75575f80fd5b843567ffffffffffffffff80821115610b8c575f80fd5b9086019060608289031215610b9f575f80fd5b90945060208601359080821115610bb4575f80fd5b818701915087601f830112610bc7575f80fd5b813581811115610bd5575f80fd5b8860208260051b8501011115610be9575f80fd5b95986020929092019750949560400135945092505050565b5f808335601e19843603018112610c16575f80fd5b83018035915067ffffffffffffffff821115610c30575f80fd5b6020019150600581901b3603821315610c47575f80fd5b9250929050565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b80356001600160a01b0381168114610c8c575f80fd5b919050565b8183525f60208085019450825f5b85811015610ccb576001600160a01b03610cb883610c76565b1687529582019590820190600101610c9f565b509495945050505050565b8183525f7f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115610d06575f80fd5b8260051b80836020870137939093016020019392505050565b608080825288519082018190525f9060209060a0840190828c01845b82811015610d605781516001600160a01b031684529284019290840190600101610d3b565b50505083810382850152610d75818a8c610c91565b90508381036040850152610d8a81888a610cd6565b84810360608601528581529050818101600586811b83018401885f5b89811015610e1457601f198684030185528135601e198c3603018112610dca575f80fd5b8b01878101903567ffffffffffffffff811115610de5575f80fd5b80861b3603821315610df5575f80fd5b610e00858284610cd6565b968901969450505090860190600101610da6565b50909e9d5050505050505050505050505050565b6040516060810167ffffffffffffffff81118282101715610e4b57610e4b610c4e565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715610e7a57610e7a610c4e565b604052919050565b5f67ffffffffffffffff80841115610e9c57610e9c610c4e565b8360051b6020610ead818301610e51565b868152918501918181019036841115610ec4575f80fd5b865b84811015610f8857803586811115610edc575f80fd5b88016060368290031215610eee575f80fd5b610ef6610e28565b610eff82610c76565b8152858201358682015260408083013589811115610f1b575f80fd5b9290920191601f3681850112610f2f575f80fd5b83358a811115610f4157610f41610c4e565b610f5289601f198484011601610e51565b91508082523689828701011115610f67575f80fd5b808986018a8401375f90820189015290820152845250918301918301610ec6565b50979650505050505050565b5f60208284031215610fa4575f80fd5b5051919050565b5f5b83811015610fc5578181015183820152602001610fad565b50505f910152565b5f8151808452610fe4816020860160208601610fab565b601f01601f19169290920160200192915050565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561104357601f19868403018952611031838351610fcd565b98840198925090830190600101611015565b5090979650505050505050565b60e081525f61106360e083018b8d610c91565b602083820381850152611077828b8d610cd6565b915088604085015260608851606086015281890151608081608088015286850360a08801528491508885528385019150838960051b8601018a5f5b8b81101561118657601f198089850301865282357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa18f36030181126110f5575f80fd5b8e016001600160a01b0361110882610c76565b16855288810135898601526040810135601e19823603018112611129575f80fd5b01888101903567ffffffffffffffff811115611143575f80fd5b803603821315611151575f80fd5b88604087015280898701528082888801375f86820188015296890196601f0190911690930184019250908601906001016110b2565b505087810360c089015261119a818a610ff8565b96505050505050509a9950505050505050505050565b5f82516111c1818460208701610fab565b9190910192915050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176111f6576111f66111cb565b92915050565b5f8261121657634e487b7160e01b5f52601260045260245ffd5b500490565b818103818111156111f6576111f66111cb565b5f6020828403121561123e575f80fd5b8151801515811461124d575f80fd5b9392505050565b602081525f61124d6020830184610fcd56
 0x0DA09b7575Ca92141477A854F8BAcdc0A6f6eb49
 
                                0x0DA09b7575Ca92141477A854F8BAcdc0A6f6eb49
                            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.