creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "PoolManager.sol": {
        "content": "// SPDX-License-Identifier: UNLICENSED\n// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol\n\npragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n    function factory() external pure returns (address);\n    function WETH() external pure returns (address);\n\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB, uint liquidity);\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountToken, uint amountETH);\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountToken, uint amountETH);\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n\n    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}\n\n// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol\n\npragma solidity >=0.6.2;\n\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountETH);\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountETH);\n\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external payable;\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n}\n\n// File: @openzeppelin/contracts/utils/Address.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n\n// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n\n// File: @openzeppelin/contracts/token/ERC20/IERC20.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n\n// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\n\n\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev An operation with an ERC20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data);\n        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;\n    }\n}\n\n// File: @openzeppelin/contracts/security/ReentrancyGuard.sol\n\n\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n\n// File: interfaces/IPoolExtension.sol\n\n\npragma solidity ^0.8.20;\n\ninterface IPoolExtension {\n  function setShare(\n    address wallet,\n    uint256 balanceChange,\n    bool isRemoving\n  ) external;\n}\n// File: @openzeppelin/contracts/utils/Context.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n\n// File: @openzeppelin/contracts/access/Ownable.sol\n\n\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n\n// File: StakingPool.sol\n\n\npragma solidity ^0.8.20;\n\n/// @author Juan Snaider Cruickshank \n/// Github: jscrui | Telegram: jscrui\n/// @title Staking Pool for UNREKT PROTOCOL\n/// @notice This contract has fixed APY, Eth Rewards, and lockup period.\n/// @dev This contract is designed for the Unrekt Protocol.\ncontract StakingPool is Context, Ownable, ReentrancyGuard {\n  using SafeERC20 for IERC20;\n\n  IUniswapV2Router02 immutable _router;\n  uint256 constant MULTIPLIER = 10 ** 36;\n  address public token;\n  uint256 public lockupPeriod;\n  uint256 public totalStakedUsers;\n  uint256 public totalSharesDeposited;\n\n  IPoolExtension public extension;\n\n  struct Share {\n    uint256 amount;\n    uint256 stakedTime;\n  }\n  struct Reward {\n    uint256 excluded;\n    uint256 realised;\n  }\n  mapping(address => Share) public shares;\n  mapping(address => Reward) public rewards;\n\n  uint256 public rewardsPerShare;\n  uint256 public totalDistributed;\n  uint256 public totalRewards;\n\n  event Stake(address indexed user, uint256 amount);\n  event Unstake(address indexed user, uint256 amount);\n  event ClaimReward(address user);\n  event DepositRewards(address indexed user, uint256 amountTokens);\n  event DistributeReward(\n    address indexed user,\n    uint256 amount,\n    bool _wasCompounded\n  );\n\n  constructor(address _token, uint256 _lockupPeriod, address __router) Ownable(msg.sender) {\n    token = _token;\n    lockupPeriod = _lockupPeriod;\n    _router = IUniswapV2Router02(__router);\n  }\n\n  function stake(uint256 _amount) external nonReentrant {\n    IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount);\n    _setShare(_msgSender(), _amount, false);\n  }\n\n  function stakeForWallets(\n    address[] memory _wallets,\n    uint256[] memory _amounts\n  ) external nonReentrant {\n    require(_wallets.length == _amounts.length, 'INSYNC');\n    uint256 _totalAmount;\n    for (uint256 _i; _i < _wallets.length; _i++) {\n      _totalAmount += _amounts[_i];\n      _setShare(_wallets[_i], _amounts[_i], false);\n    }\n    IERC20(token).safeTransferFrom(_msgSender(), address(this), _totalAmount);\n  }\n\n  function unstake(uint256 _amount) external nonReentrant {\n    IERC20(token).safeTransfer(_msgSender(), _amount);\n    _setShare(_msgSender(), _amount, true);\n  }\n\n  function _setShare(\n    address wallet,\n    uint256 balanceUpdate,\n    bool isRemoving\n  ) internal {\n    if (address(extension) != address(0)) {\n      try extension.setShare(wallet, balanceUpdate, isRemoving) {} catch {}\n    }\n    if (isRemoving) {\n      _removeShares(wallet, balanceUpdate);\n      emit Unstake(wallet, balanceUpdate);\n    } else {\n      _addShares(wallet, balanceUpdate);\n      emit Stake(wallet, balanceUpdate);\n    }\n  }\n\n  function _addShares(address wallet, uint256 amount) private {\n    if (shares[wallet].amount > 0) {\n      _distributeReward(wallet, false, 0);\n    }\n    uint256 sharesBefore = shares[wallet].amount;\n    totalSharesDeposited += amount;\n    shares[wallet].amount += amount;\n    shares[wallet].stakedTime = block.timestamp;\n    if (sharesBefore == 0 && shares[wallet].amount > 0) {\n      totalStakedUsers++;\n    }\n    rewards[wallet].excluded = _cumulativeRewards(shares[wallet].amount);\n  }\n\n  function _removeShares(address wallet, uint256 amount) private {\n    require(\n      shares[wallet].amount > 0 && amount <= shares[wallet].amount,\n      'REM: amount'\n    );\n    require(\n      block.timestamp > shares[wallet].stakedTime + lockupPeriod,\n      'REM: timelock'\n    );\n    uint256 _unclaimed = getUnpaid(wallet);\n    bool _otherStakersPresent = totalSharesDeposited - amount > 0;\n    if (!_otherStakersPresent) {\n      _distributeReward(wallet, false, 0);\n    }\n    totalSharesDeposited -= amount;\n    shares[wallet].amount -= amount;\n    if (shares[wallet].amount == 0) {\n      totalStakedUsers--;\n    }\n    rewards[wallet].excluded = _cumulativeRewards(shares[wallet].amount);\n    // if there are other stakers and unclaimed rewards,\n    // deposit them back into the pool for other stakers to claim\n    if (_otherStakersPresent && _unclaimed > 0) {\n      _depositRewards(wallet, _unclaimed);\n    }\n  }\n\n  function depositRewards() external payable {\n    _depositRewards(_msgSender(), msg.value);\n  }\n\n  function _depositRewards(address _wallet, uint256 _amountETH) internal {\n    require(_amountETH > 0, 'ETH');\n    require(totalSharesDeposited > 0, 'SHARES');\n    totalRewards += _amountETH;\n    rewardsPerShare += (MULTIPLIER * _amountETH) / totalSharesDeposited;\n    emit DepositRewards(_wallet, _amountETH);\n  }\n\n  function _distributeReward(\n    address _wallet,\n    bool _compound,\n    uint256 _compoundMinTokensToReceive\n  ) internal {\n    if (shares[_wallet].amount == 0) {\n      return;\n    }\n    shares[_wallet].stakedTime = block.timestamp; // reset every claim\n    uint256 _amountWei = getUnpaid(_wallet);\n    rewards[_wallet].realised += _amountWei;\n    rewards[_wallet].excluded = _cumulativeRewards(shares[_wallet].amount);\n    if (_amountWei > 0) {\n      totalDistributed += _amountWei;\n      if (_compound) {\n        _compoundRewards(_wallet, _amountWei, _compoundMinTokensToReceive);\n      } else {\n        uint256 _balBefore = address(this).balance;\n        (bool success, ) = payable(_wallet).call{ value: _amountWei }('');\n        require(success, 'DIST0');\n        require(address(this).balance >= _balBefore - _amountWei, 'DIST1');\n      }\n      emit DistributeReward(_wallet, _amountWei, _compound);\n    }\n  }\n\n  function _compoundRewards(\n    address _wallet,\n    uint256 _wei,\n    uint256 _minTokensToReceive\n  ) internal {\n    address[] memory path = new address[](2);\n    path[0] = _router.WETH();\n    path[1] = token;\n\n    IERC20 _token = IERC20(token);\n    uint256 _tokenBalBefore = _token.balanceOf(address(this));\n    _router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: _wei }(\n      _minTokensToReceive,\n      path,\n      address(this),\n      block.timestamp\n    );\n    uint256 _compoundAmount = _token.balanceOf(address(this)) - _tokenBalBefore;\n    _setShare(_wallet, _compoundAmount, false);\n  }\n\n  function claimReward(\n    bool _compound,\n    uint256 _compMinTokensToReceive\n  ) external nonReentrant {\n    _distributeReward(_msgSender(), _compound, _compMinTokensToReceive);\n    emit ClaimReward(_msgSender());\n  }\n\n  function claimRewardAdmin(\n    address _wallet,\n    bool _compound,\n    uint256 _compMinTokensToReceive\n  ) external nonReentrant onlyOwner {\n    _distributeReward(_wallet, _compound, _compMinTokensToReceive);\n    emit ClaimReward(_wallet);\n  }\n\n  function getUnpaid(address wallet) public view returns (uint256) {\n    if (shares[wallet].amount == 0) {\n      return 0;\n    }\n    uint256 earnedRewards = _cumulativeRewards(shares[wallet].amount);\n    uint256 rewardsExcluded = rewards[wallet].excluded;\n    if (earnedRewards <= rewardsExcluded) {\n      return 0;\n    }\n    return earnedRewards - rewardsExcluded;\n  }\n\n  function _cumulativeRewards(uint256 share) internal view returns (uint256) {\n    return (share * rewardsPerShare) / MULTIPLIER;\n  }\n\n  function setPoolExtension(IPoolExtension _extension) external onlyOwner {\n    extension = _extension;\n  }\n\n  function setLockupPeriod(uint256 _seconds) external onlyOwner {\n    require(_seconds < 365 days, 'lte 1 year');\n    lockupPeriod = _seconds;\n  }\n\n  function withdrawTokens(uint256 _amount) external onlyOwner {\n    IERC20 _token = IERC20(token);\n    _token.safeTransfer(\n      _msgSender(),\n      _amount == 0 ? _token.balanceOf(address(this)) : _amount\n    );\n  }\n}\n\n// File: PoolManager.sol\n\npragma solidity ^0.8.20;\n\n/// @author Juan Snaider Cruickshank\n/// Github: jscrui | Telegram: jscrui\n/// @title Pool Manager for UNREKT PROTOCOL\n/// @notice This contract manages all the Staking Pools.\n/// @dev This contract is designed for the Unrekt Protocol.\ncontract PoolManager is Ownable {\n    uint256 constant FACTOR = 10000;\n    address constant DEXROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n\n    address public stakingToken;\n    uint256 _totalPercentages;\n    bool public adminCanWithdraw = true;\n\n    struct PoolInfo {\n        address pool;\n        uint256 percentage;\n    }\n\n    PoolInfo[] public pools;\n\n    /**\n     * @dev Constructor to initialize the staking token.\n     * @param _stakingToken The address of the staking token.\n     */\n    constructor(address _stakingToken) Ownable(msg.sender) {\n        stakingToken = _stakingToken;\n        _totalPercentages = FACTOR;\n    }\n\n    /**\n     * @dev Returns all the pool information.\n     * @return An array of PoolInfo structs.\n     */\n    function getAllPools() external view returns (PoolInfo[] memory) {\n        return pools;\n    }\n\n    /**\n     * @dev Deposits rewards into all pools based on their percentage allocation.\n     */\n    function depositRewards() external payable {\n        require(msg.value > 0, \"POOLMANAGER: no rewards\");\n        uint256 _totalETH;\n        for (uint256 _i; _i < pools.length; _i++) {\n            uint256 _totalBefore = _totalETH;\n            _totalETH += (msg.value * pools[_i].percentage) / FACTOR;\n            StakingPool(pools[_i].pool).depositRewards{\n                value: _totalETH - _totalBefore\n            }();\n        }\n        uint256 _refund = msg.value - _totalETH;\n        if (_refund > 0) {\n            (bool _refunded, ) = payable(_msgSender()).call{value: _refund}(\"\");\n            require(_refunded, \"POOLMANAGER: could not refund\");\n        }\n    }\n\n    /**\n     * @dev Allows bulk claiming of rewards with optional compounding.\n     * @param _compound An array of booleans indicating whether to compound rewards for each pool.\n     * @param _minTokens An array of minimum tokens to be received for each pool.\n     */\n    function claimRewardsBulk(\n        bool[] memory _compound,\n        uint256[] memory _minTokens\n    ) external {\n        for (uint256 _i; _i < _compound.length; _i++) {\n            StakingPool(pools[_i].pool).claimRewardAdmin(\n                _msgSender(),\n                _compound[_i],\n                _minTokens[_i]\n            );\n        }\n    }\n\n    /**\n     * @dev Sets the lockup periods for the pools.\n     * @param _seconds An array of lockup periods in seconds for each pool.\n     */\n    function setLockupPeriods(uint256[] memory _seconds) external onlyOwner {\n        for (uint256 _i; _i < _seconds.length; _i++) {\n            StakingPool(pools[_i].pool).setLockupPeriod(_seconds[_i]);\n        }\n    }\n\n    /**\n     * @dev Sets the percentage allocations for the pools.\n     * @param _percentages An array of percentages for each pool.\n     */\n    function setPercentages(uint256[] memory _percentages) external onlyOwner {\n        _totalPercentages = 0;\n        for (uint256 _i; _i < _percentages.length; _i++) {\n            _totalPercentages += _percentages[_i];\n            pools[_i].percentage = _percentages[_i];\n        }\n        require(_totalPercentages <= FACTOR, \"POOLMANAGER: lte 100%\");\n    }\n\n    /**\n     * @dev Sets the pool extensions.\n     * @param _ext An array of IPoolExtension addresses for each pool.\n     */\n    function setExtension(IPoolExtension[] memory _ext) external onlyOwner {\n        for (uint256 _i; _i < _ext.length; _i++) {\n            StakingPool(pools[_i].pool).setPoolExtension(_ext[_i]);\n        }\n    }\n\n    /**\n     * @dev Removes the ability for the admin to withdraw from the pools.\n     */\n    function removeWithdrawAbility() external onlyOwner {\n        require(adminCanWithdraw, \"POOLMANAGER: already disabled\");\n        adminCanWithdraw = false;\n    }\n\n    /**\n     * @dev Withdraws tokens from the pools.\n     * @param _amounts An array of amounts to withdraw from each pool.\n     */\n    function withdrawFromPools(uint256[] memory _amounts) external onlyOwner {\n        require(adminCanWithdraw, \"POOLMANAGER: disabled\");\n        for (uint256 _i; _i < _amounts.length; _i++) {\n            StakingPool(pools[_i].pool).withdrawTokens(_amounts[_i]);\n        }\n    }\n\n    /**\n     * @dev Creates a new pool.\n     * @param _lockupSeconds The lockup period in seconds for the new pool.\n     * @param _percentage The percentage allocation for the new pool.\n     */\n    function createPool(\n        uint256 _lockupSeconds,\n        uint256 _percentage\n    ) external onlyOwner {\n        require(\n            _totalPercentages + _percentage <= FACTOR,\n            \"POOLMANAGER: max percentage\"\n        );\n        _totalPercentages += _percentage;\n        pools.push(\n            PoolInfo({\n                pool: address(\n                    new StakingPool(stakingToken, _lockupSeconds, DEXROUTER)\n                ),\n                percentage: _percentage\n            })\n        );\n    }\n\n    /**\n     * @dev Removes a pool by index.\n     * @param _idx The index of the pool to remove.\n     */\n    function removePool(uint256 _idx) external onlyOwner {\n        PoolInfo memory _pool = pools[_idx];\n        _totalPercentages -= _pool.percentage;\n        pools[_idx] = pools[pools.length - 1];\n        pools.pop();\n    }\n\n    /**\n     * @dev Renounces ownership of all pools and the PoolManager contract.\n     */\n    function renounceAllOwnership() external onlyOwner {\n        for (uint256 _i; _i < pools.length; _i++) {\n            StakingPool(pools[_i].pool).renounceOwnership();\n        }\n        renounceOwnership();\n    }\n}"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      }
    }
  }}