RangePositionManager

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// 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;
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
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].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}
"
    },
    "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (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. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    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));
    }
}
"
    },
    "@openzeppelin/contracts/token/ERC721/IERC721.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
      "content": "// 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 IERC721Receiver {
    /**
     * @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);
}
"
    },
    "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @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);
}
"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// 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);
        }
    }
}
"
    },
    "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
      "content": "// 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);
}
"
    },
    "contracts/RangePositionManager.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import { IPancakeV3Pool } from "./interfaces/IPancakeV3Pool.sol";
import { IUniswapV3Pool } from "./interfaces/IUniswapV3Pool.sol";
import { IWETH9 } from "./interfaces/IWETH9.sol";
import { IUniswapV3Factory } from "./interfaces/IUniswapV3Factory.sol";
import { IYieldManager } from "./interfaces/IYieldManager.sol";
import { IFeeDistributor } from "./interfaces/IFeeDistributor.sol";
import { IRangeMaster } from "./interfaces/IRangeMaster.sol";
import { IMasterChefV3 } from "./interfaces/IMasterChefV3.sol";
import { TickMath } from "./libraries/TickMath.sol";
import { LiquidityAmounts } from "./libraries/LiquidityAmounts.sol";
import { ISwapManager } from "./interfaces/ISwapManager.sol";
import { IRewardNFT } from "./interfaces/IRewardNFT.sol";
import { INonfungiblePositionManager, IERC721, IERC721Enumerable } from "./interfaces/INonfungiblePositionManager.sol";

/// @title RangePositionManager Contract
/// @notice Manages liquidity provision and fee collection across multiple DEXs
/// @dev This contract interacts with one pool of a V3 protocol and accepts user liquidity in order to earn trading fees.
/// @dev This contract is designed to work only with native ETH, users with WETH should unwrap prior to interact with the contract
/// @dev This contract is designed to work with non deflationary tokens and tokens without taxation
/// @dev This contract is designed to work only with corresponding position NFTs - dont send position NFTs directly, use provided methods
contract RangePositionManager is ReentrancyGuard, IERC721Receiver {
    using SafeERC20 for IERC20;
    using Address for address payable;

    // structs
    struct UserInfo {
        uint256 liquidity;
        uint256 token0Balance;
        uint256 token1Balance;
        uint256 cakeTokenBalance;
        uint256 token0Lifetime;
        uint256 token1Lifetime;
    }

    // struct for handling the variables in moveRange
    struct MoveRangeParams {
        address tokenIn;
        address tokenOut;
        uint256 amount0;
        uint256 amount1;
        uint256 amountIn;
        uint256 returnFromSwap;
    }

    uint256 public currentTokenId;
    uint256 internal immutable _productLock;
    uint128 public totalLiquidity;
    address[] public userList;
    address public owner;
    // indicates if the mint and increase liquidity is locked
    bool public isLocked;
    INonfungiblePositionManager public positionManager;

    mapping(address => UserInfo) public userMapping;

    address internal immutable _WETH;
    address internal _token0;
    address internal _token1;
    uint24 internal immutable _fee;
    int24 internal _currentTickLower;
    int24 internal _currentTickUpper;

    bool internal _contractInitiated;

    // indicates if moveRange check is on
    bool internal _checkMoveRangeDisabled;

    address internal _pendingOwner;
    address internal _feeReceiver;
    address internal _pendingFeeReceiver;
    address internal immutable _uniswapV3Pool;
    address internal immutable _cakeToken;
    IUniswapV3Factory internal _uniswapV3Factory;
    ISwapManager internal _swapManager;
    IFeeDistributor internal _feeDistributor;
    IMasterChefV3 internal _masterChef;

    address internal _rangeMaster;
    uint256 constant internal MAX_USERS = 50;
    uint256 internal immutable _distributionFee;
    uint256 internal _distributionRemainders0;
    uint256 internal _distributionRemainders1;

    mapping(address => bool) internal _isUser;
    mapping(address => bool) internal _operatorAddresses;

    // events
    event Mint(uint256 amount0, uint256 amount1, uint256 liquidity, uint256 tokenId, address indexed user);
    event IncreaseLiquidity(uint256 amount0, uint256 amount1, uint256 liquidity, address indexed user);
    event RemovedLiquidity(uint256 amount0, uint256 amount1, uint256 liquidity, address indexed user);
    event FeesWithdrawn(uint256 amount0, uint256 amount1, address indexed user);
    event NewOwner(address indexed oldOwner, address indexed owner);
    event Locked(bool oldLocked, bool locked);
    event MovedRange(int24 tickLower, int24 tickUpper);
    event CheckMoveRangeDisabled(bool oldCheckdisabled, bool checkDisabled);
    event OperatorAddressUpdated(address indexed operator, bool oldStatus, bool newStatus);
    event NewFeeReceiver(address indexed oldFeeReceiver, address indexed newFeeReceiver);
    event NewRangeMaster(address indexed oldRangeMaster, address indexed newRangeMaster);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event FeeReceiverTransferStarted(address indexed previousFeeReceiver, address indexed newFeeReceiver);
    event NewFeeDistributor(address indexed oldFeeDistributor, address indexed feeDistributor);
    event NewSwapManager(address indexed oldSwapManager, address indexed swapManager);
    event MasterDisabled();

    error UnauthorizedOwner();
    error UnauthorizedRangeMaster();
    error ZeroAddressFeeDistributor();
    error ZeroAddressTokens();
    error ZeroAddressPositionManager();
    error ZeroAddressSwapManager();
    error ZeroAddress();
    error DistributionFeeTooBig();
    error NoPoolFound();
    error NoValidSenderPositionNFT();
    error OnlyOneOwnerMint();
    error ValueMismatch();
    error UnauthorizedOperator();
    error MoveRangeNotAllowed();
    error AmountIs0();
    error Token0NotSufficient();
    error Token1NotSufficient();
    error MaxUsersReached();
    error NotEligibleToEnter();
    error UnauthorizedFeeReceiver();
    error NotEnoughLiquidity();
    error ProductLocked();
    error MismatchNativeETHToken();


    // only owner modifier
    modifier onlyOwner {
        _onlyOwner();
        _;
    }

    // only rangeMaster modifier
    modifier onlyRangeMaster {
        _onlyRangeMaster();
        _;
    }

    constructor(
        address positionManager_,
        address token0_,
        address token1_,
        uint24 fee_,
        uint256 productLock_,
        address feeDistributor_,
        uint256 distributionFee_,
        address masterChef_,
        address cakeAddress_,
        address swapManager_
    ){
        if(feeDistributor_ == address(0)){
            revert ZeroAddressFeeDistributor();
        }
        if(token1_ == address(0) || token0_ == address(0)){
            revert ZeroAddressTokens();
        }
        if(positionManager_ == address(0)){
            revert ZeroAddressPositionManager();
        }
        if(swapManager_ == address(0)){
            revert ZeroAddressSwapManager();
        }
        if(distributionFee_ >= 10000){
            revert DistributionFeeTooBig();
        }

        owner = msg.sender;
        _feeReceiver = msg.sender;
        _token0 = token0_;
        _token1 = token1_;
        _fee = fee_;

        positionManager = INonfungiblePositionManager(positionManager_);
        _uniswapV3Factory = IUniswapV3Factory(positionManager.factory());
        _uniswapV3Pool = _uniswapV3Factory.getPool(_token0, _token1, _fee);

        if(_uniswapV3Pool == address(0)){
            revert NoPoolFound();
        }

        _WETH = positionManager.WETH9();
        _productLock = productLock_;
        _feeDistributor = IFeeDistributor(feeDistributor_);
        _distributionFee = distributionFee_;

        _masterChef = IMasterChefV3(masterChef_);
        _cakeToken = cakeAddress_;

        _swapManager = ISwapManager(swapManager_);
    }

    // default fallback and receive functions
    fallback() external payable {}
    receive() external payable {}

    /// Function for the first mint of the initial position nft
    /// @dev mints the first initial position NFT, can only be called by the owner
    /// @dev this contract accepts native ETH and converts it to WETH
    /// @dev WETH deposits are not allowed (only ETH)
    /// @param tickLower the lower tick
    /// @param tickUpper the upper tick
    /// @param amountDesired0 the amount of token0 desired
    /// @param amountDesired1 the amount of token1 desired
    /// @param amount0Min the min amount of token0 desired
    /// @param amount1Min the min amount of token1 desired
    function mintOwner(
        int24 tickLower,
        int24 tickUpper,
        uint256 amountDesired0,
        uint256 amountDesired1,
        uint256 amount0Min,
        uint256 amount1Min
    )
    external payable onlyOwner nonReentrant {
        if(_contractInitiated) {
            revert OnlyOneOwnerMint();
        }
        if (_token0 == _WETH) {
            if(amountDesired0 != msg.value){
                revert ValueMismatch();
            }
        }
        if (_token1 == _WETH) {
            if(amountDesired1 != msg.value){
                revert ValueMismatch();
            }
        }

        _contractInitiated = true;
        _mint(tickLower, tickUpper, amountDesired0, amountDesired1, amount0Min,amount1Min, false);
    }

    /// function for moving range
    /// @dev this function is used to move the liquidity ranges (lower tick, upper tick). If possible (within the threshold)
    /// @dev it is possible to call this function. It will decrease all liquidity from the position, swap tokens in a ratio given in the parameter
    /// @dev and then mint a new position using this tokens swapped. Users will get the share of the new liquidity pro rata
    /// @param tickLower the new lower tick
    /// @param tickUpper the new upper tick
    /// @param tokenToSwap the token to be swapped
    /// @param amountToSwap the amount to be swapped from the tokenForRatios
    /// @param amountOutMinimum the minimum output
    function moveRange
    (
        int24 tickLower,
        int24 tickUpper,
        address tokenToSwap,
        uint256 amountToSwap,
        uint256 amountDecrease0Min,
        uint256 amountDecrease1Min,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 amountOutMinimum,
        uint24 poolFee
    )
    external nonReentrant
    {
        if(!_operatorAddresses[msg.sender]){
            revert UnauthorizedOperator();
        }
        if(!canMoveRange()){
            revert MoveRangeNotAllowed();
        }
        if(tokenToSwap != _token0 && tokenToSwap != _token1){
            revert ValueMismatch();
        }
        if(amountToSwap == 0){
            revert AmountIs0();
        }

        // if rewards are active
        if (address(_masterChef) != address(0)) {
            //get back from masterChef
            _updateUserCakeBalance(_masterChef.withdraw(currentTokenId, address(this)));
        }

        // collect fees
        _collect(0,0);

        MoveRangeParams memory params;

        // decrease to 0
        (params.amount0, params.amount1) = _decreaseLiquidity(amountDecrease0Min, amountDecrease1Min, totalLiquidity, address(this), true);

        // burn the position
        positionManager.burn(currentTokenId);

        // get correct input params
        params.tokenIn = (tokenToSwap == _token0) ? _token0 : _token1; // Token to swap from (depends on the token we get from the input)
        params.tokenOut = (tokenToSwap == _token0) ? _token1 : _token0; // Token to receive (opposite of tokenIn)
        params.amountIn = (tokenToSwap == _token0) ? params.amount1 : params.amount0; // Amount to swap from (either amount0 or amount1)

        // The call to `exactInputSingle` executes the swap.
        // approvals
        IERC20(params.tokenIn).forceApprove(address(_swapManager), amountToSwap);

        // swap
        params.returnFromSwap = _swapManager.swap{value: params.tokenIn == _WETH ? amountToSwap : 0}(params.tokenIn, params.tokenOut, amountToSwap, poolFee, amountOutMinimum);

        uint256 token0check;
        uint256 token1check;

        if (tokenToSwap == _token0) {
            token0check = params.amount0 - amountToSwap;
            token1check = params.amount1 + params.returnFromSwap;
        } else {
            token0check = params.amount0 + params.returnFromSwap;
            token1check = params.amount1 - amountToSwap;
        }

        // mint new position
        _mint(
            tickLower,
            tickUpper,
            token0check,
            token1check,
            amount0Min,
            amount1Min,
            true
        );

        emit MovedRange(tickLower, tickUpper);
    }

    /// public function for increasing liquidity
    /// @dev for increasing liquidity, also sets the sponsor if new user
    /// @param amountDesired0 the desired amount to use of token0
    /// @param amountDesired1 the desired amount to use of token1
    /// @param amount0Min the minimum amount of token0
    /// @param amount1Min the minimum amount of token1
    /// @param userToIncrease the user to increase
    function increaseLiquidityUser(
        uint256 amountDesired0,
        uint256 amountDesired1,
        uint256 amount0Min,
        uint256 amount1Min,
        address userToIncrease
    )
    external payable nonReentrant onlyRangeMaster
    {
        if(_token0 == _WETH) {
            if(amountDesired0 != msg.value){
                revert ValueMismatch();
            }
        }
        if(_token1 == _WETH) {
            if(amountDesired1 != msg.value){
                revert ValueMismatch();
            }
        }

        // increase the liquidity of the user
        _increaseLiquidity(
            amountDesired0,
            amountDesired1,
            amount0Min,
            amount1Min,
            userToIncrease,
            false
        );
    }

    /// public function for increasing liquidity automatically
    /// @dev for increasing liquidity auto
    /// @param amountDesired0 the desired amount to use of token0
    /// @param amountDesired1 the desired amount to use of token1
    /// @param amount0Min the minimum amount of token0
    /// @param amount1Min the minimum amount of token1
    /// @param userToIncrease the address of the user to increase
    function increaseLiquidityAuto(
        uint256 amountDesired0,
        uint256 amountDesired1,
        uint256 amount0Min,
        uint256 amount1Min,
        address userToIncrease
    )
    external nonReentrant
    {
        if(!_operatorAddresses[msg.sender]){
            revert UnauthorizedOperator();
        }
        if(userToIncrease == address(0)){
            revert ZeroAddress();
        }

        // get user element
        UserInfo storage userElement = userMapping[userToIncrease];

        if(userElement.token0Balance < amountDesired0){
            revert Token0NotSufficient();
        }
        if(userElement.token1Balance < amountDesired1){
            revert Token1NotSufficient();
        }

        _increaseLiquidity(
            amountDesired0,
            amountDesired1,
            amount0Min,
            amount1Min,
            userToIncrease,
            true
        );
    }


    /// function for decreasing liquidity, for msg.sender
    /// @dev for decreasing liquidity, for msg.sender
    /// @param amount0Min the minimum amount to receive of token0
    /// @param amount1Min the minimum amount to receive of token1
    /// @param liquidity the amount of liquidity to be decreased
    /// @param userToDecrease the userToDecrease to decrease
    /// @param userToDecrease the userToDecrease to decrease
    function decreaseLiquidityUser(
        uint256 amount0Min,
        uint256 amount1Min,
        uint128 liquidity,
        address userToDecrease
    )
    external
    nonReentrant
    {
        // ability for user to directly call function
        if (msg.sender != owner && msg.sender != _rangeMaster) {
            userToDecrease = msg.sender;
        }

        //get user element
        UserInfo storage userElement = userMapping[userToDecrease];

        // check for liquidity
        if(liquidity > userElement.liquidity){
            revert NotEnoughLiquidity();
        }

        // if rewards are active
        if (address(_masterChef) != address(0)) {
            //get back from masterChef
            _updateUserCakeBalance(_masterChef.withdraw(currentTokenId, address(this)));
        }

        // perform decrease liquidity
        _decreaseLiquidity(amount0Min, amount1Min, liquidity, userToDecrease, false);

        // if rewards are active
        if (address(_masterChef) != address(0)) {
            //send to stake in masterChef
            IERC721(positionManager).safeTransferFrom(address(this), address(_masterChef), currentTokenId);
        }
    }

    /// function for handling the collect
    /// @dev collects from a public address, can be called by anyone - used to collect fees
    /// @return amount0 the amount how much token0 we got as fees
    /// @return amount1 the amount how much token1 we got as fees
    function publicCollect() external nonReentrant returns
    (
        uint256 amount0,
        uint256 amount1
    )
    {
        // if rewards are active
        if (address(_masterChef) != address(0)) {
            // redeem token
            _updateUserCakeBalance(_masterChef.withdraw(currentTokenId, address(this)));
        }

        (amount0, amount1) = _collect(0, 0);

        // if rewards are active
        if (address(_masterChef) != address(0)) {
            //send to stake in masterChef
            IERC721(positionManager).safeTransferFrom(address(this), address(_masterChef), currentTokenId);
        }
    }

    /// function to collect the accrued fees
    /// @dev used to collect the earned fees from the contract (as a user)
    function userCollect(
        address userToCollect
    )
    external nonReentrant
    {
        // ability for user to directly call function
        if (msg.sender != owner && msg.sender != _rangeMaster) {
            userToCollect = msg.sender;
        }

        // get user
        UserInfo storage userElement = userMapping[userToCollect];
        uint256 token0Balance = userElement.token0Balance;
        uint256 token1Balance = userElement.token1Balance;
        uint256 cakeBalance = userElement.cakeTokenBalance;

        // check if no owner
        if (userToCollect != owner) {
            // send tokens
            if (_token0 == _WETH && (token0Balance > 0)) {
                payable(userToCollect).sendValue(token0Balance);
            }
            if (_token1 == _WETH && (token1Balance > 0)) {
                payable(userToCollect).sendValue(token1Balance);
            }
            if (_token0 != _WETH && token0Balance > 0) {
                IERC20(_token0).safeTransfer(userToCollect, token0Balance);
            }
            if (_token1 != _WETH && token1Balance > 0) {
                IERC20(_token1).safeTransfer(userToCollect, token1Balance);
            }
            if (cakeBalance > 0) {
                IERC20(_cakeToken).safeTransfer(userToCollect, cakeBalance);
            }
        }
        // user is owner
        else {
            // send tokens
            uint256 distributorFees0 = token0Balance * _distributionFee / 10000;
            uint256 distributorFees1 = token1Balance * _distributionFee / 10000;
            uint256 distributorFeesCake = cakeBalance * _distributionFee / 10000;

            if (_token0 == _WETH && (token0Balance > 0)) {
                payable(_feeReceiver).sendValue(token0Balance - distributorFees0);
                payable(address(_feeDistributor)).sendValue(distributorFees0);
            }
            if (_token1 == _WETH && (token1Balance > 0)) {
                payable(_feeReceiver).sendValue(token1Balance - distributorFees1);
                payable(address(_feeDistributor)).sendValue(distributorFees1);
            }
            if (_token0 != _WETH && token0Balance > 0) {
                IERC20(_token0).safeTransfer(_feeReceiver, token0Balance - distributorFees0);
                IERC20(_token0).forceApprove(address(_feeDistributor),distributorFees0);
                _feeDistributor.receiveERC20Fees(_token0, distributorFees0);
            }
            if (_token1 != _WETH && token1Balance > 0) {
                IERC20(_token1).safeTransfer(_feeReceiver, token1Balance - distributorFees1);
                IERC20(_token1).forceApprove(address(_feeDistributor),distributorFees1);
                _feeDistributor.receiveERC20Fees(_token1, distributorFees1);
            }
            if (cakeBalance > 0) {
                IERC20(_cakeToken).safeTransfer(_feeReceiver, cakeBalance - distributorFeesCake);
                IERC20(_cakeToken).forceApprove(address(_feeDistributor),distributorFeesCake);
                _feeDistributor.receiveERC20Fees(_cakeToken, distributorFeesCake);
            }
        }

        // set fees to 0 since withdrawn
        userElement.token0Balance = 0;
        userElement.token1Balance = 0;
        userElement.cakeTokenBalance = 0;

        emit FeesWithdrawn(token0Balance, token1Balance, userToCollect);
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
 * Can only be called by the current owner.
 */
    function changeOwner(address newOwner) external onlyOwner {
        if(newOwner == address(0)){
            revert ZeroAddress();
        }

        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
 */
    function acceptOwner() external {
        if(_pendingOwner != msg.sender){
            revert UnauthorizedOwner();
        }
        address oldOwner = owner;
        owner = _pendingOwner;
        delete _pendingOwner;
        emit NewOwner(oldOwner, owner);
    }

    /**
     * @dev Starts the fee receiver transfer of the contract to a new account. Replaces the pending transfer if there is one.
 * Can only be called by the current owner.
 */
    function changeFeeReceiver(address newFeeReceiver) external {
        if(newFeeReceiver == address(0)){
            revert ZeroAddress();
        }
        if(msg.sender != _feeReceiver){
            revert UnauthorizedFeeReceiver();
        }

        _pendingFeeReceiver = newFeeReceiver;
        emit FeeReceiverTransferStarted(_feeReceiver, newFeeReceiver);
    }

    /**
    * @dev The new fee receiver accepts the fee receiver transfer.
 */
    function acceptFeeReceiver() external {
        if(_pendingFeeReceiver != msg.sender){
            revert UnauthorizedFeeReceiver();
        }

        address oldFeeReceiver = _feeReceiver;
        _feeReceiver = _pendingFeeReceiver;
        delete _pendingFeeReceiver;
        emit NewFeeReceiver(oldFeeReceiver, _feeReceiver);
    }

    /// sets the new range master contract
    /// @dev sets the range master
    /// @param _newRangeMaster the new value for _newRangeMaster
    function changeRangeMaster(address _newRangeMaster) external onlyOwner nonReentrant {
        if(_newRangeMaster == address(0)){
            revert ZeroAddressPositionManager();
        }
        address oldRangeMaster = _rangeMaster;
        _rangeMaster = _newRangeMaster;
        emit NewRangeMaster(oldRangeMaster, _newRangeMaster);
    }

    /// stops using masterChef
    /// @dev withdraws the position NFT to the contract and stops staking in masterChef
    function disableMasterChef() external onlyOwner nonReentrant {
        // get back the NFT and distribute rewards
        _updateUserCakeBalance(_masterChef.withdraw(currentTokenId, address(this)));

        // set masterChef to 0
        _masterChef = IMasterChefV3(address(0));

        emit MasterDisabled();
    }

    /// sets the locked value
    /// @dev sets the value of isLocked and controls minting and increasing liquidity
    /// @param _locked the new value for _locked
    function setLocked(bool _locked) external onlyOwner {
        bool oldLocked = isLocked;
        isLocked = _locked;
        emit Locked(oldLocked, _locked);
    }

    /// sets the checkMoveRangeDisabled value
    /// @dev sets the value of _checkMoveRangeDisabled and controls moving the range
    /// @param _checkMoveRange the new value for _checkMoveRange
    function setCheckMoveRangeDisabled(bool _checkMoveRange) external onlyOwner {
        bool oldCheckMoveRangeDisabled = _checkMoveRangeDisabled;
        _checkMoveRangeDisabled = _checkMoveRange;
        emit CheckMoveRangeDisabled(oldCheckMoveRangeDisabled, _checkMoveRange);
    }

    /// sets the operator addresses
    /// @dev sets the value of the addresses which can operate
    /// @param operatorAddress the address to be updated
    /// @param allowed the bool to set
    function setOperatorRangeAddress(address operatorAddress, bool allowed) external onlyOwner {
        if(operatorAddress == address(0)){
            revert ZeroAddress();
        }

        bool oldAllowed = _operatorAddresses[operatorAddress];
        _operatorAddresses[operatorAddress] = allowed;
        emit OperatorAddressUpdated(operatorAddress, oldAllowed, allowed);
    }

    /// sets the feeDistributor value
    /// @dev sets the value of feeDistributor
    /// @dev changes the fee distributor
    /// @param newFeeDistributor the new value for feeDistributor
    /// @param newSwapManager the new value for swapManager
    function setFeeDistributorSwapper(address newFeeDistributor, address newSwapManager) external onlyOwner {
        if(newFeeDistributor == address(0)){
            revert ZeroAddressFeeDistributor();
        }
        if(newSwapManager == address(0)){
            revert ZeroAddressSwapManager();
        }

        address oldFeeDistributor = address(_feeDistributor);
        address oldSwapManager = address(_swapManager);
        _feeDistributor = IFeeDistributor(newFeeDistributor);
        _swapManager = ISwapManager(newSwapManager);

        emit NewFeeDistributor(oldFeeDistributor, newFeeDistributor);
        emit NewSwapManager(oldSwapManager, newSwapManager);
    }


    /// @dev Withdraws excess tokens or native ETH from the contract.
    /// This function allows the contract owner to withdraw tokens or ETH that are in excess of the accounted balances
    /// for all users. This can include mistakenly sent tokens or residual balances. The function can handle both ERC20 tokens
    /// and native Ethereum (ETH) withdrawals based on the `isEthNative` flag. Tokens that are accounted to users cannot be withdrawn.
    /// @param _token The address of the token to withdraw.
    /// @param _to The recipient address of the withdrawn tokens or ETH.
    /// @param isEthNative A boolean flag indicating whether the withdrawal is for native ETH.
    function withdrawExcessTokens(address _token, address _to, bool isEthNative) external onlyOwner {
        if(_token == address(0)){
            revert ZeroAddress();
        }
        if(_to == address(0)){
            revert ZeroAddress();
        }
        if(isEthNative && _token != _WETH) {
            revert MismatchNativeETHToken();
        }

        uint256 contractBalance;
        uint256 accountedBalance;

        if (isEthNative) {
            // For native ETH, use the contract's balance
            contractBalance = address(this).balance;
        } else {
            // For ERC20 tokens, use the balanceOf function
            contractBalance = IERC20(_token).balanceOf(address(this));
        }

        // special case for handling WETH sent to the contract by accident
        if (_token == _WETH && !isEthNative) {
            IERC20(_token).safeTransfer(_to, contractBalance);
            return;
        }

        uint256 userLength = userList.length;
        for (uint256 i = 0; i < userLength; i++) {
            UserInfo storage user = userMapping[userList[i]];
            if (_token == _token0) {
                accountedBalance += user.token0Balance;
            } else if (_token == _token1) {
                accountedBalance += user.token1Balance;
            } else if (_token == _cakeToken) {
                accountedBalance += user.cakeTokenBalance;
            }
        }

        // Calculate the excess balance b

Tags:
ERC20, ERC721, ERC165, Multisig, Mintable, Burnable, Non-Fungible, Swap, Liquidity, Staking, Yield, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x92526e1b076d7b33be12ec88cf08dfc9e05e281d|verified:true|block:23734856|tx:0xce12d1b97c56b32968a9815a4e978408be1447b7f4ac1c33e5f84335c70e688c|first_check:1762367614

Submitted on: 2025-11-05 19:33:36

Comments

Log in to comment.

No comments yet.