{ "language": "Solidity", "settings": { "evmVersion": "london", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "sources": { "contracts/external/@openzeppelin/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Interface of the ERC20 standard as defined in the EIP.\r\n */\r\ninterface IERC20 {\r\n /**\r\n * @dev Returns the amount of tokens in existence.\r\n */\r\n function totalSupply() external view returns (uint256);\r\n\r\n /**\r\n * @dev Returns the amount of tokens owned by `account`.\r\n */\r\n function balanceOf(address account) external view returns (uint256);\r\n\r\n /**\r\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\r\n *\r\n * Returns a boolean value indicating whether the operation succeeded.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function transfer(address recipient, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @dev Returns the remaining number of tokens that `spender` will be\r\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\r\n * zero by default.\r\n *\r\n * This value changes when {approve} or {transferFrom} are called.\r\n */\r\n function allowance(address owner, address spender) external view returns (uint256);\r\n\r\n /**\r\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\r\n *\r\n * Returns a boolean value indicating whether the operation succeeded.\r\n *\r\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\r\n * that someone may use both the old and the new allowance by unfortunate\r\n * transaction ordering. One possible solution to mitigate this race\r\n * condition is to first reduce the spender's allowance to 0 and set the\r\n * desired value afterwards:\r\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\r\n *\r\n * Emits an {Approval} event.\r\n */\r\n function approve(address spender, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\r\n * allowance mechanism. `amount` is then deducted from the caller's\r\n * allowance.\r\n *\r\n * Returns a boolean value indicating whether the operation succeeded.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function transferFrom(\r\n address sender,\r\n address recipient,\r\n uint256 amount\r\n ) external returns (bool);\r\n\r\n /**\r\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\r\n * another (`to`).\r\n *\r\n * Note that `value` may be zero.\r\n */\r\n event Transfer(address indexed from, address indexed to, uint256 value);\r\n\r\n /**\r\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\r\n * a call to {approve}. `value` is the new allowance.\r\n */\r\n event Approval(address indexed owner, address indexed spender, uint256 value);\r\n}\r\n" }, "contracts/external/@openzeppelin/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"../IERC20.sol\";\r\nimport \"../../../utils/Address.sol\";\r\n\r\n/**\r\n * @title SafeERC20\r\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\r\n * contract returns false). Tokens that return no value (and instead revert or\r\n * throw on failure) are also supported, non-reverting calls are assumed to be\r\n * successful.\r\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\r\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\r\n */\r\nlibrary SafeERC20 {\r\n using Address for address;\r\n\r\n function safeTransfer(\r\n IERC20 token,\r\n address to,\r\n uint256 value\r\n ) internal {\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\r\n }\r\n\r\n function safeTransferFrom(\r\n IERC20 token,\r\n address from,\r\n address to,\r\n uint256 value\r\n ) internal {\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\r\n }\r\n\r\n /**\r\n * @dev Deprecated. This function has issues similar to the ones found in\r\n * {IERC20-approve}, and its usage is discouraged.\r\n *\r\n * Whenever possible, use {safeIncreaseAllowance} and\r\n * {safeDecreaseAllowance} instead.\r\n */\r\n function safeApprove(\r\n IERC20 token,\r\n address spender,\r\n uint256 value\r\n ) internal {\r\n // safeApprove should only be called when setting an initial allowance,\r\n // or when resetting it to zero. To increase and decrease it, use\r\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\r\n require(\r\n (value == 0) || (token.allowance(address(this), spender) == 0),\r\n \"SafeERC20: approve from non-zero to non-zero allowance\"\r\n );\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\r\n }\r\n\r\n function safeIncreaseAllowance(\r\n IERC20 token,\r\n address spender,\r\n uint256 value\r\n ) internal {\r\n uint256 newAllowance = token.allowance(address(this), spender) + value;\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\r\n }\r\n\r\n function safeDecreaseAllowance(\r\n IERC20 token,\r\n address spender,\r\n uint256 value\r\n ) internal {\r\n unchecked {\r\n uint256 oldAllowance = token.allowance(address(this), spender);\r\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\r\n uint256 newAllowance = oldAllowance - value;\r\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\r\n }\r\n }\r\n\r\n /**\r\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\r\n * on the return value: the return value is optional (but if data is returned, it must not be false).\r\n * @param token The token targeted by the call.\r\n * @param data The call data (encoded using abi.encode or one of its variants).\r\n */\r\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\r\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\r\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\r\n // the target address contains contract code and also asserts for success in the low-level call.\r\n\r\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\r\n if (returndata.length > 0) {\r\n // Return data is optional\r\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\r\n }\r\n }\r\n}\r\n" }, "contracts/external/@openzeppelin/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Collection of functions related to the address type\r\n */\r\nlibrary Address {\r\n /**\r\n * @dev Returns true if `account` is a contract.\r\n *\r\n * [IMPORTANT]\r\n * ====\r\n * It is unsafe to assume that an address for which this function returns\r\n * false is an externally-owned account (EOA) and not a contract.\r\n *\r\n * Among others, `isContract` will return false for the following\r\n * types of addresses:\r\n *\r\n * - an externally-owned account\r\n * - a contract in construction\r\n * - an address where a contract will be created\r\n * - an address where a contract lived, but was destroyed\r\n * ====\r\n */\r\n function isContract(address account) internal view returns (bool) {\r\n // This method relies on extcodesize, which returns 0 for contracts in\r\n // construction, since the code is only stored at the end of the\r\n // constructor execution.\r\n\r\n uint256 size;\r\n assembly {\r\n size := extcodesize(account)\r\n }\r\n return size > 0;\r\n }\r\n\r\n /**\r\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\r\n * `recipient`, forwarding all available gas and reverting on errors.\r\n *\r\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\r\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\r\n * imposed by `transfer`, making them unable to receive funds via\r\n * `transfer`. {sendValue} removes this limitation.\r\n *\r\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\r\n *\r\n * IMPORTANT: because control is transferred to `recipient`, care must be\r\n * taken to not create reentrancy vulnerabilities. Consider using\r\n * {ReentrancyGuard} or the\r\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\r\n */\r\n function sendValue(address payable recipient, uint256 amount) internal {\r\n require(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\r\n (bool success, ) = recipient.call{value: amount}(\"\");\r\n require(success, \"Address: unable to send value, recipient may have reverted\");\r\n }\r\n\r\n /**\r\n * @dev Performs a Solidity function call using a low level `call`. A\r\n * plain `call` is an unsafe replacement for a function call: use this\r\n * function instead.\r\n *\r\n * If `target` reverts with a revert reason, it is bubbled up by this\r\n * function (like regular Solidity function calls).\r\n *\r\n * Returns the raw returned data. To convert to the expected return value,\r\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\r\n *\r\n * Requirements:\r\n *\r\n * - `target` must be a contract.\r\n * - calling `target` with `data` must not revert.\r\n *\r\n * _Available since v3.1._\r\n */\r\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\r\n return functionCall(target, data, \"Address: low-level call failed\");\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\r\n * `errorMessage` as a fallback revert reason when `target` reverts.\r\n *\r\n * _Available since v3.1._\r\n */\r\n function functionCall(\r\n address target,\r\n bytes memory data,\r\n string memory errorMessage\r\n ) internal returns (bytes memory) {\r\n return functionCallWithValue(target, data, 0, errorMessage);\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n * but also transferring `value` wei to `target`.\r\n *\r\n * Requirements:\r\n *\r\n * - the calling contract must have an ETH balance of at least `value`.\r\n * - the called Solidity function must be `payable`.\r\n *\r\n * _Available since v3.1._\r\n */\r\n function functionCallWithValue(\r\n address target,\r\n bytes memory data,\r\n uint256 value\r\n ) internal returns (bytes memory) {\r\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\r\n * with `errorMessage` as a fallback revert reason when `target` reverts.\r\n *\r\n * _Available since v3.1._\r\n */\r\n function functionCallWithValue(\r\n address target,\r\n bytes memory data,\r\n uint256 value,\r\n string memory errorMessage\r\n ) internal returns (bytes memory) {\r\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\r\n require(isContract(target), \"Address: call to non-contract\");\r\n\r\n (bool success, bytes memory returndata) = target.call{value: value}(data);\r\n return verifyCallResult(success, returndata, errorMessage);\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n * but performing a static call.\r\n *\r\n * _Available since v3.3._\r\n */\r\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\r\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\r\n * but performing a static call.\r\n *\r\n * _Available since v3.3._\r\n */\r\n function functionStaticCall(\r\n address target,\r\n bytes memory data,\r\n string memory errorMessage\r\n ) internal view returns (bytes memory) {\r\n require(isContract(target), \"Address: static call to non-contract\");\r\n\r\n (bool success, bytes memory returndata) = target.staticcall(data);\r\n return verifyCallResult(success, returndata, errorMessage);\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n * but performing a delegate call.\r\n *\r\n * _Available since v3.4._\r\n */\r\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\r\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\r\n }\r\n\r\n /**\r\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\r\n * but performing a delegate call.\r\n *\r\n * _Available since v3.4._\r\n */\r\n function functionDelegateCall(\r\n address target,\r\n bytes memory data,\r\n string memory errorMessage\r\n ) internal returns (bytes memory) {\r\n require(isContract(target), \"Address: delegate call to non-contract\");\r\n\r\n (bool success, bytes memory returndata) = target.delegatecall(data);\r\n return verifyCallResult(success, returndata, errorMessage);\r\n }\r\n\r\n /**\r\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\r\n * revert reason using the provided one.\r\n *\r\n * _Available since v4.3._\r\n */\r\n function verifyCallResult(\r\n bool success,\r\n bytes memory returndata,\r\n string memory errorMessage\r\n ) internal pure returns (bytes memory) {\r\n if (success) {\r\n return returndata;\r\n } else {\r\n // Look for revert reason and bubble it up if present\r\n if (returndata.length > 0) {\r\n // The easiest way to bubble the revert reason is using memory via assembly\r\n\r\n assembly {\r\n let returndata_size := mload(returndata)\r\n revert(add(32, returndata), returndata_size)\r\n }\r\n } else {\r\n revert(errorMessage);\r\n }\r\n }\r\n }\r\n}\r\n" }, "contracts/external/@openzeppelin/utils/SafeCast.sol": { "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\r\n * checks.\r\n *\r\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\r\n * easily result in undesired exploitation or bugs, since developers usually\r\n * assume that overflows raise errors. `SafeCast` restores this intuition by\r\n * reverting the transaction when such an operation overflows.\r\n *\r\n * Using this library instead of the unchecked operations eliminates an entire\r\n * class of bugs, so it's recommended to use it always.\r\n *\r\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\r\n * all math on `uint256` and `int256` and then downcasting.\r\n */\r\nlibrary SafeCast {\r\n /**\r\n * @dev Returns the downcasted uint224 from uint256, reverting on\r\n * overflow (when the input is greater than largest uint224).\r\n *\r\n * Counterpart to Solidity's `uint224` operator.\r\n *\r\n * Requirements:\r\n *\r\n * - input must fit into 224 bits\r\n */\r\n function toUint224(uint256 value) internal pure returns (uint224) {\r\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\r\n return uint224(value);\r\n }\r\n\r\n /**\r\n * @dev Returns the downcasted uint192 from uint256, reverting on\r\n * overflow (when the input is greater than largest uint192).\r\n *\r\n * Counterpart to Solidity's `uint192` operator.\r\n *\r\n * Requirements:\r\n *\r\n * - input must fit into 192 bits\r\n */\r\n function toUint192(uint256 value) internal pure returns (uint192) {\r\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 128 bits\");\r\n return uint192(value);\r\n }\r\n\r\n /**\r\n * @dev Returns the downcasted uint128 from uint256, reverting on\r\n * overflow (when the input is greater than largest uint128).\r\n *\r\n * Counterpart to Solidity's `uint128` operator.\r\n *\r\n * Requirements:\r\n *\r\n * - input must fit into 128 bits\r\n */\r\n function toUint128(uint256 value) internal pure returns (uint128) {\r\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\r\n return uint128(value);\r\n }\r\n}\r\n" }, "contracts/external/GNSPS-solidity-bytes-utils/BytesLib.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\r\n/*\r\n * @title Solidity Bytes Arrays Utils\r\n * @author Gonçalo Sá \r\n *\r\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\r\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\r\n */\r\npragma solidity 0.8.11;\r\n\r\nlibrary BytesLib {\r\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\r\n require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');\r\n address tempAddress;\r\n\r\n assembly {\r\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\r\n }\r\n\r\n return tempAddress;\r\n }\r\n\r\n function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {\r\n require(_bytes.length >= _start + 32, \"toBytes32_outOfBounds\");\r\n bytes32 tempBytes32;\r\n\r\n assembly {\r\n tempBytes32 := mload(add(add(_bytes, 0x20), _start))\r\n }\r\n\r\n return tempBytes32;\r\n }\r\n\r\n function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {\r\n require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');\r\n uint24 tempUint;\r\n\r\n assembly {\r\n tempUint := mload(add(add(_bytes, 0x3), _start))\r\n }\r\n\r\n return tempUint;\r\n }\r\n\r\n function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {\r\n require(_bytes.length >= _start + 1 , \"toUint8_outOfBounds\");\r\n uint8 tempUint;\r\n\r\n assembly {\r\n tempUint := mload(add(add(_bytes, 0x1), _start))\r\n }\r\n\r\n return tempUint;\r\n }\r\n}\r\n" }, "contracts/external/interfaces/aave/ILendingPool.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\r\n\r\npragma solidity 0.8.11;\r\n\r\ninterface ILendingPool {\r\n struct ReserveConfigurationMap {\r\n //bit 0-15: LTV\r\n //bit 16-31: Liq. threshold\r\n //bit 32-47: Liq. bonus\r\n //bit 48-55: Decimals\r\n //bit 56: Reserve is active\r\n //bit 57: reserve is frozen\r\n //bit 58: borrowing is enabled\r\n //bit 59: stable rate borrowing enabled\r\n //bit 60-63: reserved\r\n //bit 64-79: reserve factor\r\n uint256 data;\r\n }\r\n\r\n struct ReserveData {\r\n //stores the reserve configuration\r\n ReserveConfigurationMap configuration;\r\n //the liquidity index. Expressed in ray\r\n uint128 liquidityIndex;\r\n //variable borrow index. Expressed in ray\r\n uint128 variableBorrowIndex;\r\n //the current supply rate. Expressed in ray\r\n uint128 currentLiquidityRate;\r\n //the current variable borrow rate. Expressed in ray\r\n uint128 currentVariableBorrowRate;\r\n //the current stable borrow rate. Expressed in ray\r\n uint128 currentStableBorrowRate;\r\n uint40 lastUpdateTimestamp;\r\n //tokens addresses\r\n address aTokenAddress;\r\n address stableDebtTokenAddress;\r\n address variableDebtTokenAddress;\r\n //address of the interest rate strategy\r\n address interestRateStrategyAddress;\r\n //the id of the reserve. Represents the position in the list of the active reserves\r\n uint8 id;\r\n }\r\n\r\n /**\r\n * @dev Emitted on deposit()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address initiating the deposit\r\n * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens\r\n * @param amount The amount deposited\r\n * @param referral The referral code used\r\n **/\r\n event Deposit(\r\n address indexed reserve,\r\n address user,\r\n address indexed onBehalfOf,\r\n uint256 amount,\r\n uint16 indexed referral\r\n );\r\n\r\n /**\r\n * @dev Emitted on withdraw()\r\n * @param reserve The address of the underlyng asset being withdrawn\r\n * @param user The address initiating the withdrawal, owner of aTokens\r\n * @param to Address that will receive the underlying\r\n * @param amount The amount to be withdrawn\r\n **/\r\n event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\r\n\r\n /**\r\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\r\n * @param reserve The address of the underlying asset being borrowed\r\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\r\n * initiator of the transaction on flashLoan()\r\n * @param onBehalfOf The address that will be getting the debt\r\n * @param amount The amount borrowed out\r\n * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable\r\n * @param borrowRate The numeric rate at which the user has borrowed\r\n * @param referral The referral code used\r\n **/\r\n event Borrow(\r\n address indexed reserve,\r\n address user,\r\n address indexed onBehalfOf,\r\n uint256 amount,\r\n uint256 borrowRateMode,\r\n uint256 borrowRate,\r\n uint16 indexed referral\r\n );\r\n\r\n /**\r\n * @dev Emitted on repay()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The beneficiary of the repayment, getting his debt reduced\r\n * @param repayer The address of the user initiating the repay(), providing the funds\r\n * @param amount The amount repaid\r\n **/\r\n event Repay(address indexed reserve, address indexed user, address indexed repayer, uint256 amount);\r\n\r\n /**\r\n * @dev Emitted on swapBorrowRateMode()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user swapping his rate mode\r\n * @param rateMode The rate mode that the user wants to swap to\r\n **/\r\n event Swap(address indexed reserve, address indexed user, uint256 rateMode);\r\n\r\n /**\r\n * @dev Emitted on setUserUseReserveAsCollateral()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user enabling the usage as collateral\r\n **/\r\n event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on setUserUseReserveAsCollateral()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user enabling the usage as collateral\r\n **/\r\n event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on rebalanceStableBorrowRate()\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param user The address of the user for which the rebalance has been executed\r\n **/\r\n event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\r\n\r\n /**\r\n * @dev Emitted on flashLoan()\r\n * @param target The address of the flash loan receiver contract\r\n * @param initiator The address initiating the flash loan\r\n * @param asset The address of the asset being flash borrowed\r\n * @param amount The amount flash borrowed\r\n * @param premium The fee flash borrowed\r\n * @param referralCode The referral code used\r\n **/\r\n event FlashLoan(\r\n address indexed target,\r\n address indexed initiator,\r\n address indexed asset,\r\n uint256 amount,\r\n uint256 premium,\r\n uint16 referralCode\r\n );\r\n\r\n /**\r\n * @dev Emitted when the pause is triggered.\r\n */\r\n event Paused();\r\n\r\n /**\r\n * @dev Emitted when the pause is lifted.\r\n */\r\n event Unpaused();\r\n\r\n /**\r\n * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via\r\n * LendingPoolCollateral manager using a DELEGATECALL\r\n * This allows to have the events in the generated ABI for LendingPool.\r\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\r\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\r\n * @param user The address of the borrower getting liquidated\r\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\r\n * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator\r\n * @param liquidator The address of the liquidator\r\n * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\r\n * to receive the underlying collateral asset directly\r\n **/\r\n event LiquidationCall(\r\n address indexed collateralAsset,\r\n address indexed debtAsset,\r\n address indexed user,\r\n uint256 debtToCover,\r\n uint256 liquidatedCollateralAmount,\r\n address liquidator,\r\n bool receiveAToken\r\n );\r\n\r\n /**\r\n * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared\r\n * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,\r\n * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it\r\n * gets added to the LendingPool ABI\r\n * @param reserve The address of the underlying asset of the reserve\r\n * @param liquidityRate The new liquidity rate\r\n * @param stableBorrowRate The new stable borrow rate\r\n * @param variableBorrowRate The new variable borrow rate\r\n * @param liquidityIndex The new liquidity index\r\n * @param variableBorrowIndex The new variable borrow index\r\n **/\r\n event ReserveDataUpdated(\r\n address indexed reserve,\r\n uint256 liquidityRate,\r\n uint256 stableBorrowRate,\r\n uint256 variableBorrowRate,\r\n uint256 liquidityIndex,\r\n uint256 variableBorrowIndex\r\n );\r\n\r\n /**\r\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\r\n * - E.g. User deposits 100 USDC and gets in return 100 aUSDC\r\n * @param asset The address of the underlying asset to deposit\r\n * @param amount The amount to be deposited\r\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\r\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\r\n * is a different wallet\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n **/\r\n function deposit(\r\n address asset,\r\n uint256 amount,\r\n address onBehalfOf,\r\n uint16 referralCode\r\n ) external;\r\n\r\n /**\r\n * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\r\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\r\n * @param asset The address of the underlying asset to withdraw\r\n * @param amount The underlying amount to be withdrawn\r\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\r\n * @param to Address that will receive the underlying, same as msg.sender if the user\r\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\r\n * different wallet\r\n * @return The final amount withdrawn\r\n **/\r\n function withdraw(\r\n address asset,\r\n uint256 amount,\r\n address to\r\n ) external returns (uint256);\r\n\r\n /**\r\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\r\n * already deposited enough collateral, or he was given enough allowance by a credit delegator on the\r\n * corresponding debt token (StableDebtToken or VariableDebtToken)\r\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\r\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\r\n * @param asset The address of the underlying asset to borrow\r\n * @param amount The amount to be borrowed\r\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself\r\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\r\n * if he has been given credit delegation allowance\r\n **/\r\n function borrow(\r\n address asset,\r\n uint256 amount,\r\n uint256 interestRateMode,\r\n uint16 referralCode,\r\n address onBehalfOf\r\n ) external;\r\n\r\n /**\r\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\r\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\r\n * @param asset The address of the borrowed underlying asset previously borrowed\r\n * @param amount The amount to repay\r\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\r\n * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\r\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\r\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\r\n * other borrower whose debt should be removed\r\n * @return The final amount repaid\r\n **/\r\n function repay(\r\n address asset,\r\n uint256 amount,\r\n uint256 rateMode,\r\n address onBehalfOf\r\n ) external returns (uint256);\r\n\r\n /**\r\n * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa\r\n * @param asset The address of the underlying asset borrowed\r\n * @param rateMode The rate mode that the user wants to swap to\r\n **/\r\n function swapBorrowRateMode(address asset, uint256 rateMode) external;\r\n\r\n /**\r\n * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\r\n * - Users can be rebalanced if the following conditions are satisfied:\r\n * 1. Usage ratio is above 95%\r\n * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been\r\n * borrowed at a stable rate and depositors are not earning enough\r\n * @param asset The address of the underlying asset borrowed\r\n * @param user The address of the user to be rebalanced\r\n **/\r\n function rebalanceStableBorrowRate(address asset, address user) external;\r\n\r\n /**\r\n * @dev Allows depositors to enable/disable a specific deposited asset as collateral\r\n * @param asset The address of the underlying asset deposited\r\n * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise\r\n **/\r\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\r\n\r\n /**\r\n * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\r\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\r\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\r\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\r\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\r\n * @param user The address of the borrower getting liquidated\r\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\r\n * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants\r\n * to receive the underlying collateral asset directly\r\n **/\r\n function liquidationCall(\r\n address collateralAsset,\r\n address debtAsset,\r\n address user,\r\n uint256 debtToCover,\r\n bool receiveAToken\r\n ) external;\r\n\r\n /**\r\n * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,\r\n * as long as the amount taken plus a fee is returned.\r\n * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\r\n * For further details please visit https://developers.aave.com\r\n * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface\r\n * @param assets The addresses of the assets being flash-borrowed\r\n * @param amounts The amounts amounts being flash-borrowed\r\n * @param modes Types of the debt to open if the flash loan is not returned:\r\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\r\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\r\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\r\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\r\n * @param params Variadic packed params to pass to the receiver as extra information\r\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\r\n * 0 if the action is executed directly by the user, without any middle-man\r\n **/\r\n function flashLoan(\r\n address receiverAddress,\r\n address[] calldata assets,\r\n uint256[] calldata amounts,\r\n uint256[] calldata modes,\r\n address onBehalfOf,\r\n bytes calldata params,\r\n uint16 referralCode\r\n ) external;\r\n\r\n /**\r\n * @dev Returns the user account data across all the reserves\r\n * @param user The address of the user\r\n * @return totalCollateralETH the total collateral in ETH of the user\r\n * @return totalDebtETH the total debt in ETH of the user\r\n * @return availableBorrowsETH the borrowing power left of the user\r\n * @return currentLiquidationThreshold the liquidation threshold of the user\r\n * @return ltv the loan to value of the user\r\n * @return healthFactor the current health factor of the user\r\n **/\r\n function getUserAccountData(address user)\r\n external\r\n view\r\n returns (\r\n uint256 totalCollateralETH,\r\n uint256 totalDebtETH,\r\n uint256 availableBorrowsETH,\r\n uint256 currentLiquidationThreshold,\r\n uint256 ltv,\r\n uint256 healthFactor\r\n );\r\n\r\n function initReserve(\r\n address reserve,\r\n address aTokenAddress,\r\n address stableDebtAddress,\r\n address variableDebtAddress,\r\n address interestRateStrategyAddress\r\n ) external;\r\n\r\n function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external;\r\n\r\n function setConfiguration(address reserve, uint256 configuration) external;\r\n\r\n /**\r\n * @dev Returns the normalized income normalized income of the reserve\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The reserve's normalized income\r\n */\r\n function getReserveNormalizedIncome(address asset) external view returns (uint256);\r\n\r\n /**\r\n * @dev Returns the normalized variable debt per unit of asset\r\n * @param asset The address of the underlying asset of the reserve\r\n * @return The reserve normalized variable debt\r\n */\r\n function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\r\n\r\n function finalizeTransfer(\r\n address asset,\r\n address from,\r\n address to,\r\n uint256 amount,\r\n uint256 balanceFromAfter,\r\n uint256 balanceToBefore\r\n ) external;\r\n\r\n function getReservesList() external view returns (address[] memory);\r\n\r\n function setPause(bool val) external;\r\n\r\n function paused() external view returns (bool);\r\n\r\n function getReserveData(address asset) external view returns (ReserveData memory);\r\n}\r\n" }, "contracts/external/interfaces/balancer/IAsset.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\r\n// This program is free software: you can redistribute it and/or modify\r\n// it under the terms of the GNU General Public License as published by\r\n// the Free Software Foundation, either version 3 of the License, or\r\n// (at your option) any later version.\r\n\r\n// This program is distributed in the hope that it will be useful,\r\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n// GNU General Public License for more details.\r\n\r\n// You should have received a copy of the GNU General Public License\r\n// along with this program. If not, see .\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero\r\n * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like\r\n * types.\r\n *\r\n * This concept is unrelated to a Pool's Asset Managers.\r\n */\r\ninterface IAsset {\r\n // solhint-disable-previous-line no-empty-blocks\r\n}\r\n" }, "contracts/external/interfaces/balancer/IBalancerVault.sol": { "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./IAsset.sol\";\r\n\r\nenum SwapKind { GIVEN_IN, GIVEN_OUT }\r\n\r\nstruct BatchSwapStep {\r\n bytes32 poolId;\r\n uint256 assetInIndex;\r\n uint256 assetOutIndex;\r\n uint256 amount;\r\n bytes userData;\r\n}\r\n\r\nstruct FundManagement {\r\n address sender;\r\n bool fromInternalBalance;\r\n address payable recipient;\r\n bool toInternalBalance;\r\n}\r\n\r\nstruct JoinPoolRequest {\r\n IAsset[] assets;\r\n uint256[] maxAmountsIn;\r\n bytes userData;\r\n bool fromInternalBalance;\r\n}\r\n\r\nstruct ExitPoolRequest {\r\n IAsset[] assets;\r\n uint256[] minAmountsOut;\r\n bytes userData;\r\n bool toInternalBalance;\r\n}\r\n\r\n\r\ninterface IBalancerVault {\r\n\r\n\r\n function batchSwap (SwapKind kind,\r\n BatchSwapStep[] memory swaps,\r\n IAsset[] memory assets, \r\n FundManagement memory funds, \r\n int256[] memory limits, \r\n uint256 deadline) \r\n external returns (int256[] memory assetDeltas);\r\n\r\n function exitPool ( bytes32 poolId, address sender, address recipient, ExitPoolRequest memory request ) external;\r\n //function getActionId ( bytes4 selector ) external view returns ( bytes32 );\r\n //function getAuthorizer ( ) external view returns ( address );\r\n //function getDomainSeparator ( ) external view returns ( bytes32 );\r\n //function getInternalBalance ( address user, address[] tokens ) external view returns ( uint256[] balances );\r\n //function getNextNonce ( address user ) external view returns ( uint256 );\r\n //function getPausedState ( ) external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime );\r\n //function getPool ( bytes32 poolId ) external view returns ( address, uint8 );\r\n //function getPoolTokenInfo ( bytes32 poolId, address token ) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager );\r\n function getPoolTokens ( bytes32 poolId ) external view returns ( IAsset[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock );\r\n //function getProtocolFeesCollector ( ) external view returns ( address );\r\n //function hasApprovedRelayer ( address user, address relayer ) external view returns ( bool );\r\n function joinPool ( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external;\r\n //function managePoolBalance ( tuple[] ops ) external;\r\n //function manageUserBalance ( tuple[] ops ) external;\r\n //function queryBatchSwap ( uint8 kind, tuple[] swaps, address[] assets, tuple funds ) external returns ( int256[] );\r\n //function registerPool ( uint8 specialization ) external returns ( bytes32 );\r\n //function registerTokens ( bytes32 poolId, address[] tokens, address[] assetManagers ) external;\r\n //function setAuthorizer ( address newAuthorizer ) external;\r\n //function setPaused ( bool paused ) external;\r\n //function setRelayerApproval ( address sender, address relayer, bool approved ) external;\r\n //function swap ( tuple singleSwap, tuple funds, uint256 limit, uint256 deadline ) external returns ( uint256 amountCalculated );\r\n}\r\n\r\n" }, "contracts/external/interfaces/idle-finance/IIdleToken.sol": { "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.11;\r\n\r\ninterface IIdleToken {\r\n function decimals() external view returns (uint8);\r\n\r\n function getGovTokens() external view returns (address[] memory);\r\n\r\n function tokenPriceWithFee(address user) external view returns (uint256);\r\n\r\n function balanceOf(address user) external view returns (uint256);\r\n\r\n function redeemIdleToken(uint256 amount) external;\r\n\r\n function redeemInterestBearingTokens(uint256 _amount) external;\r\n\r\n function mintIdleToken(\r\n uint256 amount,\r\n bool,\r\n address referral\r\n ) external returns (uint256);\r\n}\r\n" }, "contracts/external/uniswap/interfaces/ISwapRouter02.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.7.5;\r\npragma abicoder v2;\r\n\r\nimport './IV2SwapRouter.sol';\r\nimport './IV3SwapRouter.sol';\r\n\r\n/// @title Router token swapping functionality\r\ninterface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter {\r\n\r\n}\r\n" }, "contracts/external/uniswap/interfaces/IV2SwapRouter.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.7.5;\r\npragma abicoder v2;\r\n\r\n/// @title Router token swapping functionality\r\n/// @notice Functions for swapping tokens via Uniswap V2\r\ninterface IV2SwapRouter {\r\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\r\n /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,\r\n /// and swap the entire amount, enabling contracts to send tokens before calling this function.\r\n /// @param amountIn The amount of token to swap\r\n /// @param amountOutMin The minimum amount of output that must be received\r\n /// @param path The ordered list of tokens to swap through\r\n /// @param to The recipient address\r\n /// @return amountOut The amount of the received token\r\n function swapExactTokensForTokens(\r\n uint256 amountIn,\r\n uint256 amountOutMin,\r\n address[] calldata path,\r\n address to\r\n ) external payable returns (uint256 amountOut);\r\n\r\n /// @notice Swaps as little as possible of one token for an exact amount of another token\r\n /// @param amountOut The amount of token to swap for\r\n /// @param amountInMax The maximum amount of input that the caller will pay\r\n /// @param path The ordered list of tokens to swap through\r\n /// @param to The recipient address\r\n /// @return amountIn The amount of token to pay\r\n function swapTokensForExactTokens(\r\n uint256 amountOut,\r\n uint256 amountInMax,\r\n address[] calldata path,\r\n address to\r\n ) external payable returns (uint256 amountIn);\r\n}\r\n" }, "contracts/external/uniswap/interfaces/IV3SwapRouter.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\r\npragma solidity >=0.7.5;\r\npragma abicoder v2;\r\n\r\n/// @title Router token swapping functionality\r\n/// @notice Functions for swapping tokens via Uniswap V3\r\ninterface IV3SwapRouter{\r\n struct ExactInputSingleParams {\r\n address tokenIn;\r\n address tokenOut;\r\n uint24 fee;\r\n address recipient;\r\n uint256 amountIn;\r\n uint256 amountOutMinimum;\r\n uint160 sqrtPriceLimitX96;\r\n }\r\n\r\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\r\n /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,\r\n /// and swap the entire amount, enabling contracts to send tokens before calling this function.\r\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\r\n /// @return amountOut The amount of the received token\r\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\r\n\r\n struct ExactInputParams {\r\n bytes path;\r\n address recipient;\r\n uint256 amountIn;\r\n uint256 amountOutMinimum;\r\n }\r\n\r\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\r\n /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,\r\n /// and swap the entire amount, enabling contracts to send tokens before calling this function.\r\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\r\n /// @return amountOut The amount of the received token\r\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\r\n\r\n struct ExactOutputSingleParams {\r\n address tokenIn;\r\n address tokenOut;\r\n uint24 fee;\r\n address recipient;\r\n uint256 amountOut;\r\n uint256 amountInMaximum;\r\n uint160 sqrtPriceLimitX96;\r\n }\r\n\r\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\r\n /// that may remain in the router after the swap.\r\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\r\n /// @return amountIn The amount of the input token\r\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\r\n\r\n struct ExactOutputParams {\r\n bytes path;\r\n address recipient;\r\n uint256 amountOut;\r\n uint256 amountInMaximum;\r\n }\r\n\r\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\r\n /// that may remain in the router after the swap.\r\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\r\n /// @return amountIn The amount of the input token\r\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\r\n}\r\n" }, "contracts/interfaces/IBaseStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../external/@openzeppelin/token/ERC20/IERC20.sol\";\r\nimport \"./ISwapData.sol\";\r\n\r\ninterface IBaseStrategy {\r\n function underlying() external view returns (IERC20);\r\n\r\n function getStrategyBalance() external view returns (uint128);\r\n\r\n function getStrategyPrice() external view returns (uint128);\r\n\r\n function getStrategyUnderlyingWithRewards() external view returns(uint128);\r\n\r\n function process(uint256[] calldata, bool, SwapData[] calldata) external;\r\n\r\n function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128);\r\n\r\n function processDeposit(uint256[] calldata) external;\r\n\r\n function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128);\r\n\r\n function claimRewards(SwapData[] calldata) external;\r\n\r\n function emergencyWithdraw(address recipient, uint256[] calldata data) external;\r\n\r\n function initialize() external;\r\n\r\n function disable() external;\r\n\r\n /* ========== EVENTS ========== */\r\n\r\n event Slippage(address strategy, IERC20 underlying, bool isDeposit, uint256 amountIn, uint256 amountOut);\r\n}\r\n\r\nstruct ProcessReallocationData {\r\n uint128 sharesToWithdraw;\r\n uint128 optimizedShares;\r\n uint128 optimizedWithdrawnAmount;\r\n}\r\n" }, "contracts/interfaces/ISwapData.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\n/**\r\n * @notice Strict holding information how to swap the asset\r\n * @member slippage minumum output amount\r\n * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path\r\n */\r\nstruct SwapData {\r\n uint256 slippage; // min amount out\r\n bytes path; // 1st byte is action, then path \r\n}" }, "contracts/libraries/Math.sol": { "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../external/@openzeppelin/utils/SafeCast.sol\";\r\n\r\n\r\n/**\r\n * @notice A collection of custom math ustils used throughout the system\r\n */\r\nlibrary Math {\r\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\r\n return a > b ? b : a;\r\n }\r\n\r\n function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {\r\n return SafeCast.toUint128(((mul1 * mul2) / div));\r\n }\r\n\r\n function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {\r\n unchecked {\r\n return uint128((mul1 * mul2) / div);\r\n }\r\n }\r\n}\r\n\r\n" }, "contracts/libraries/Max/128Bit.sol": { "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity 0.8.11;\r\n\r\n/** @notice Handle setting zero value in a storage word as uint128 max value.\r\n *\r\n * @dev\r\n * The purpose of this is to avoid resetting a storage word to the zero value; \r\n * the gas cost of re-initializing the value is the same as setting the word originally.\r\n * so instead, if word is to be set to zero, we set it to uint128 max.\r\n *\r\n * - anytime a word is loaded from storage: call \"get\"\r\n * - anytime a word is written to storage: call \"set\"\r\n * - common operations on uints are also bundled here.\r\n *\r\n * NOTE: This library should ONLY be used when reading or writing *directly* from storage.\r\n */\r\nlibrary Max128Bit {\r\n uint128 internal constant ZERO = type(uint128).max;\r\n\r\n function get(uint128 a) internal pure returns(uint128) {\r\n return (a == ZERO) ? 0 : a;\r\n }\r\n\r\n function set(uint128 a) internal pure returns(uint128){\r\n return (a == 0) ? ZERO : a;\r\n }\r\n\r\n function add(uint128 a, uint128 b) internal pure returns(uint128 c){\r\n a = get(a);\r\n c = set(a + b);\r\n }\r\n}\r\n" }, "contracts/shared/BaseStorage.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\nimport \"../interfaces/ISwapData.sol\";\r\n\r\npragma solidity 0.8.11;\r\n\r\n/// @notice Strategy struct for all strategies\r\nstruct Strategy {\r\n uint128 totalShares;\r\n\r\n /// @notice Denotes strategy completed index\r\n uint24 index;\r\n\r\n /// @notice Denotes whether strategy is removed\r\n /// @dev after removing this value can never change, hence strategy cannot be added back again\r\n bool isRemoved;\r\n\r\n /// @notice Pending geposit amount and pending shares withdrawn by all users for next index \r\n Pending pendingUser;\r\n\r\n /// @notice Used if strategies \"dohardwork\" hasn't been executed yet in the current index\r\n Pending pendingUserNext;\r\n\r\n /// @dev Usually a temp variable when compounding\r\n mapping(address => uint256) pendingRewards;\r\n\r\n /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it\r\n uint256 lpTokens;\r\n\r\n /// @dev Usually a temp variable when compounding\r\n uint128 pendingDepositReward;\r\n\r\n // ----- REALLOCATION VARIABLES -----\r\n\r\n bool isInDepositPhase;\r\n\r\n /// @notice Used to store amount of optimized shares, so they can be substracted at the end\r\n /// @dev Only for temporary use, should be reset to 0 in same transaction\r\n uint128 optimizedSharesWithdrawn;\r\n\r\n /// @dev Underlying amount pending to be deposited from other strategies at reallocation \r\n /// @dev Actual amount needed to be deposited and was withdrawn from others for reallocation\r\n /// @dev resets after the strategy reallocation DHW is finished\r\n uint128 pendingReallocateDeposit;\r\n\r\n /// @notice Stores amount of optimized underlying amount when reallocating\r\n /// @dev resets after the strategy reallocation DHW is finished\r\n /// @dev This is \"virtual\" amount that was matched between this strategy and others when reallocating\r\n uint128 pendingReallocateOptimizedDeposit;\r\n\r\n /// @notice Average oprimized and non-optimized deposit\r\n /// @dev Deposit from all strategies by taking the average of optimizedna dn non-optimized deposit\r\n /// @dev Used as reallocation deposit recieved\r\n uint128 pendingReallocateAverageDeposit;\r\n\r\n // ------------------------------------\r\n\r\n /// @notice Total underlying amoung at index\r\n mapping(uint256 => TotalUnderlying) totalUnderlying;\r\n\r\n /// @notice Batches stored after each DHW with index as a key\r\n /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users\r\n mapping(uint256 => Batch) batches;\r\n\r\n /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate)\r\n /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation\r\n mapping(uint256 => BatchReallocation) reallocationBatches;\r\n\r\n /// @notice Vaults holding this strategy shares\r\n mapping(address => Vault) vaults;\r\n\r\n /// @notice Future proof storage\r\n mapping(bytes32 => AdditionalStorage) additionalStorage;\r\n\r\n /// @dev Make sure to reset it to 0 after emergency withdrawal\r\n uint256 emergencyPending;\r\n}\r\n\r\n/// @notice Unprocessed deposit underlying amount and strategy share amount from users\r\nstruct Pending {\r\n uint128 deposit;\r\n uint128 sharesToWithdraw;\r\n}\r\n\r\n/// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index\r\nstruct TotalUnderlying {\r\n uint128 amount;\r\n uint128 totalShares;\r\n}\r\n\r\n/// @notice Stored after executing DHW for each index.\r\n/// @dev This is used for vaults to redeem their deposit.\r\nstruct Batch {\r\n /// @notice total underlying deposited in index\r\n uint128 deposited;\r\n uint128 depositedReceived;\r\n uint128 depositedSharesReceived;\r\n uint128 withdrawnShares;\r\n uint128 withdrawnReceived;\r\n}\r\n\r\n/// @notice Stored after executing reallocation DHW each index.\r\nstruct BatchReallocation {\r\n /// @notice Deposited amount received from reallocation\r\n uint128 depositedReallocation;\r\n\r\n /// @notice Received shares from reallocation\r\n uint128 depositedReallocationSharesReceived;\r\n\r\n /// @notice Used to know how much tokens was received for reallocating\r\n uint128 withdrawnReallocationReceived;\r\n\r\n /// @notice Amount of shares to withdraw for reallocation\r\n uint128 withdrawnReallocationShares;\r\n}\r\n\r\n/// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working)\r\nstruct Vault {\r\n uint128 shares;\r\n\r\n /// @notice Withdrawn amount as part of the reallocation\r\n uint128 withdrawnReallocationShares;\r\n\r\n /// @notice Index to action\r\n mapping(uint256 => VaultBatch) vaultBatches;\r\n}\r\n\r\n/// @notice Stores deposited and withdrawn shares by the vault\r\nstruct VaultBatch {\r\n /// @notice Vault index to deposited amount mapping\r\n uint128 deposited;\r\n\r\n /// @notice Vault index to withdrawn user shares mapping\r\n uint128 withdrawnShares;\r\n}\r\n\r\n/// @notice Used for reallocation calldata\r\nstruct VaultData {\r\n address vault;\r\n uint8 strategiesCount;\r\n uint256 strategiesBitwise;\r\n uint256 newProportions;\r\n}\r\n\r\n/// @notice Calldata when executing reallocatin DHW\r\n/// @notice Used in the withdraw part of the reallocation DHW\r\nstruct ReallocationWithdrawData {\r\n uint256[][] reallocationTable;\r\n StratUnderlyingSlippage[] priceSlippages;\r\n RewardSlippages[] rewardSlippages;\r\n uint256[] stratIndexes;\r\n uint256[][] slippages;\r\n}\r\n\r\n/// @notice Calldata when executing reallocatin DHW\r\n/// @notice Used in the deposit part of the reallocation DHW\r\nstruct ReallocationData {\r\n uint256[] stratIndexes;\r\n uint256[][] slippages;\r\n}\r\n\r\n/// @notice In case some adapters need extra storage\r\nstruct AdditionalStorage {\r\n uint256 value;\r\n address addressValue;\r\n uint96 value96;\r\n}\r\n\r\n/// @notice Strategy total underlying slippage, to verify validity of the strategy state\r\nstruct StratUnderlyingSlippage {\r\n uint256 min;\r\n uint256 max;\r\n}\r\n\r\n/// @notice Containig information if and how to swap strategy rewards at the DHW\r\n/// @dev Passed in by the do-hard-worker\r\nstruct RewardSlippages {\r\n bool doClaim;\r\n SwapData[] swapData;\r\n}\r\n\r\n/// @notice Helper struct to compare strategy share between eachother\r\n/// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating)\r\nstruct PriceData {\r\n uint256 totalValue;\r\n uint256 totalShares;\r\n}\r\n\r\n/// @notice Strategy reallocation values after reallocation optimization of shares was calculated \r\nstruct ReallocationShares {\r\n uint128[] optimizedWithdraws;\r\n uint128[] optimizedShares;\r\n uint128[] totalSharesWithdrawn;\r\n uint256[][] optimizedReallocationTable;\r\n}\r\n\r\n/// @notice Shared storage for multiple strategies\r\n/// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool)\r\nstruct StrategiesShared {\r\n uint184 value;\r\n uint32 lastClaimBlock;\r\n uint32 lastUpdateBlock;\r\n uint8 stratsCount;\r\n mapping(uint256 => address) stratAddresses;\r\n mapping(bytes32 => uint256) bytesValues;\r\n}\r\n\r\n/// @notice Base storage shared betweek Spool contract and Strategies\r\n/// @dev this way we can use same values when performing delegate call\r\n/// to strategy implementations from the Spool contract\r\nabstract contract BaseStorage {\r\n // ----- DHW VARIABLES -----\r\n\r\n /// @notice Force while DHW (all strategies) to be executed in only one transaction\r\n /// @dev This is enforced to increase the gas efficiency of the system\r\n /// Can be removed by the DAO if gas gost of the strategies goes over the block limit\r\n bool internal forceOneTxDoHardWork;\r\n\r\n /// @notice Global index of the system\r\n /// @dev Insures the correct strategy DHW execution.\r\n /// Every strategy in the system must be equal or one less than global index value\r\n /// Global index increments by 1 on every do-hard-work\r\n uint24 public globalIndex;\r\n\r\n /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed\r\n uint8 internal doHardWorksLeft;\r\n\r\n // ----- REALLOCATION VARIABLES -----\r\n\r\n /// @notice Used for offchain execution to get the new reallocation table.\r\n bool internal logReallocationTable;\r\n\r\n /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index\r\n /// @dev only used when reallocating\r\n /// after it reaches 0, deposit phase of the reallocation can begin\r\n uint8 public withdrawalDoHardWorksLeft;\r\n\r\n /// @notice Index at which next reallocation is set\r\n uint24 public reallocationIndex;\r\n\r\n /// @notice 2D table hash containing information of how strategies should be reallocated between eachother\r\n /// @dev Created when allocation provider sets reallocation for the vaults\r\n /// This table is stored as a hash in the system and verified on reallocation DHW\r\n /// Resets to 0 after reallocation DHW is completed\r\n bytes32 internal reallocationTableHash;\r\n\r\n /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index\r\n /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating.\r\n /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton\r\n /// Resets when DHW is completed\r\n bytes32 internal reallocationStrategiesHash;\r\n\r\n // -----------------------------------\r\n\r\n /// @notice Denoting if an address is the do-hard-worker\r\n mapping(address => bool) public isDoHardWorker;\r\n\r\n /// @notice Denoting if an address is the allocation provider\r\n mapping(address => bool) public isAllocationProvider;\r\n\r\n /// @notice Strategies shared storage\r\n /// @dev used as a helper storage to save common inoramation\r\n mapping(bytes32 => StrategiesShared) internal strategiesShared;\r\n\r\n /// @notice Mapping of strategy implementation address to strategy system values\r\n mapping(address => Strategy) public strategies;\r\n\r\n /// @notice Flag showing if disable was skipped when a strategy has been removed\r\n /// @dev If true disable can still be run \r\n mapping(address => bool) internal _skippedDisable;\r\n\r\n /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed\r\n /// @dev If true emergency withdraw can still be executed\r\n mapping(address => bool) internal _awaitingEmergencyWithdraw;\r\n}" }, "contracts/shared/Constants.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../external/@openzeppelin/token/ERC20/IERC20.sol\";\r\n\r\n/// @title Common Spool contracts constants\r\nabstract contract BaseConstants {\r\n /// @dev 2 digits precision\r\n uint256 internal constant FULL_PERCENT = 100_00;\r\n\r\n /// @dev Accuracy when doing shares arithmetics\r\n uint256 internal constant ACCURACY = 10**30;\r\n}\r\n\r\n/// @title Contains USDC token related values\r\nabstract contract USDC {\r\n /// @notice USDC token contract address\r\n IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);\r\n}" }, "contracts/shared/SwapHelper.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./SwapHelperUniswap.sol\";\r\nimport \"./SwapHelperBalancer.sol\";\r\n\r\n/// @title Contains logic facilitating swapping using Uniswap / Balancer\r\nabstract contract SwapHelper is SwapHelperBalancer, SwapHelperUniswap {\r\n using BytesLib for bytes;\r\n\r\n /**\r\n * @notice Sets initial values\r\n * @param _uniswapRouter Uniswap router address\r\n * @param _WETH WETH token address\r\n */\r\n constructor(ISwapRouter02 _uniswapRouter, address _WETH)\r\n SwapHelperUniswap(_uniswapRouter, _WETH)\r\n SwapHelperBalancer()\r\n {}\r\n\r\n /**\r\n * @notice Approve reward token and swap the `amount` to a strategy underlying asset\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param swapData Swap details showing the path of the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _approveAndSwap(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n SwapData calldata swapData\r\n ) internal virtual returns (uint256) {\r\n // If first byte is les or equal to 6, we swap via the Uniswap\r\n if (swapData.path.toUint8(0) <= 6) {\r\n return _approveAndSwapUniswap(from, to, amount, swapData);\r\n }\r\n return _approveAndSwapBalancer(from, to, amount, swapData);\r\n }\r\n}\r\n" }, "contracts/shared/SwapHelperBalancer.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../external/GNSPS-solidity-bytes-utils/BytesLib.sol\";\r\nimport \"../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol\";\r\n\r\nimport \"../external/interfaces/balancer/IBalancerVault.sol\";\r\nimport \"../interfaces/ISwapData.sol\";\r\n\r\n/// @title Contains logic facilitating swapping using Balancer\r\nabstract contract SwapHelperBalancer {\r\n using BytesLib for bytes;\r\n using SafeERC20 for IERC20;\r\n\r\n /// @dev The length of the bytes encoded swap size\r\n uint256 private constant NUM_SWAPS_SIZE = 1;\r\n\r\n /// @dev The length of the bytes encoded address\r\n uint256 private constant ADDR_SIZE = 20;\r\n\r\n /// @dev The length of the bytes encoded pool ID\r\n uint256 private constant POOLID_SIZE = 32;\r\n\r\n /// @dev The length of the indexes size\r\n uint256 private constant INDEXES_SIZE = 2;\r\n\r\n /// @dev The length of the maximum swap size\r\n uint256 private constant MAX_SWAPS = 4;\r\n\r\n /// @dev The length of the bytes encoded poolID and indexes size\r\n uint256 private constant SWAPS_SIZE = POOLID_SIZE + INDEXES_SIZE;\r\n\r\n /// @notice Balancer master vault\r\n IBalancerVault private immutable vault = IBalancerVault(0xBA12222222228d8Ba445958a75a0704d566BF2C8);\r\n\r\n /**\r\n * @notice Approve reward token and swap the `amount` to a strategy underlying asset\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param swapData Swap details showing the path of the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _approveAndSwapBalancer(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n SwapData calldata swapData\r\n ) internal virtual returns (uint256) {\r\n // if there is nothing to swap, return\r\n if (amount == 0) return 0;\r\n\r\n // if amount is not uint256 max approve vault to spend tokens\r\n // otherwise rewards were already sent to the vault\r\n bool fromInternalBalance;\r\n if (amount < type(uint256).max) {\r\n from.safeApprove(address(vault), amount);\r\n } else {\r\n fromInternalBalance = true;\r\n }\r\n\r\n (BatchSwapStep[] memory swaps, IAsset[] memory assets) = _getBatchSwapsAndAssets(amount, swapData.path[1:]);\r\n\r\n FundManagement memory funds = FundManagement({\r\n sender: address(this),\r\n fromInternalBalance: fromInternalBalance,\r\n recipient: payable(address(this)),\r\n toInternalBalance: false\r\n });\r\n\r\n uint256 result = _swapBal(from, to, swaps, assets, funds, swapData.slippage);\r\n\r\n if (from.allowance(address(this), address(vault)) > 0) {\r\n from.safeApprove(address(vault), 0);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * @notice Swaps tokens using Balancer\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param swaps pools with asset indexes\r\n * @param slippage assets used in the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _swapBal(\r\n IERC20 from,\r\n IERC20 to,\r\n BatchSwapStep[] memory swaps,\r\n IAsset[] memory assets,\r\n FundManagement memory funds,\r\n uint256 slippage\r\n ) internal virtual returns (uint256) {\r\n // we need to verify that the first and last index in and index out in the swaps is the 'from' and 'to' address respectively\r\n require(\r\n address(assets[swaps[0].assetInIndex]) == address(from),\r\n \"SwapHelperBalancer:_swapBal:: from token incorrect.\"\r\n );\r\n require(\r\n address(assets[swaps[swaps.length - 1].assetOutIndex]) == address(to),\r\n \"SwapHelperBalancer:_swapBal:: to token incorrect.\"\r\n );\r\n\r\n int256[] memory limits = new int256[](assets.length);\r\n limits[0] = int256(swaps[0].amount);\r\n\r\n uint256 toBalance = to.balanceOf(address(this));\r\n vault.batchSwap(SwapKind.GIVEN_IN, swaps, assets, funds, limits, type(uint256).max);\r\n uint256 toBalanceAfter = to.balanceOf(address(this)) - toBalance;\r\n require(toBalanceAfter >= slippage, \"SwapHelperBalancer:_swapBal:: Insufficient Amount Swapped\");\r\n\r\n return toBalanceAfter;\r\n }\r\n\r\n /**\r\n * @notice Convert bytes path into swaps and assets for batchSwap\r\n * @param amount Token amount to swap (for first swap only)\r\n * @param pathBytes bytes encoded swaps and assets\r\n */\r\n function _getBatchSwapsAndAssets(uint256 amount, bytes calldata pathBytes)\r\n internal\r\n pure\r\n returns (BatchSwapStep[] memory swaps, IAsset[] memory assets)\r\n {\r\n // assert swap data\r\n uint256 numSwaps = pathBytes.toUint8(0);\r\n require(numSwaps > 0 && numSwaps <= MAX_SWAPS);\r\n\r\n // assert asset data\r\n uint256 startAssets = NUM_SWAPS_SIZE + (numSwaps * SWAPS_SIZE);\r\n uint256 assetsPathSize = pathBytes.length - startAssets;\r\n uint256 numAssets = assetsPathSize / ADDR_SIZE;\r\n require(assetsPathSize % ADDR_SIZE == 0 && numAssets <= (numSwaps + 1));\r\n\r\n // Get swaps\r\n swaps = new BatchSwapStep[](numSwaps);\r\n swaps[0].amount = amount;\r\n for (uint256 i = 0; i < numSwaps; i++) {\r\n swaps[i].poolId = pathBytes.toBytes32(NUM_SWAPS_SIZE + (i * SWAPS_SIZE));\r\n swaps[i].assetInIndex = pathBytes.toUint8(NUM_SWAPS_SIZE + (i * SWAPS_SIZE) + POOLID_SIZE);\r\n swaps[i].assetOutIndex = pathBytes.toUint8(NUM_SWAPS_SIZE + (i * SWAPS_SIZE) + POOLID_SIZE + 1);\r\n }\r\n\r\n // Get assets\r\n assets = new IAsset[](numAssets);\r\n for (uint256 i = 0; i < numAssets; i++) {\r\n assets[i] = IAsset(pathBytes.toAddress(startAssets + (i * ADDR_SIZE)));\r\n }\r\n\r\n return (swaps, assets);\r\n }\r\n}\r\n" }, "contracts/shared/SwapHelperMainnet.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./SwapHelper.sol\";\r\n\r\n/// @title Swap helper implementation with SwapRouter02 on Mainnet\r\ncontract SwapHelperMainnet is SwapHelper {\r\n constructor()\r\n SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)\r\n {}\r\n}\r\n" }, "contracts/shared/SwapHelperUniswap.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../external/GNSPS-solidity-bytes-utils/BytesLib.sol\";\r\nimport \"../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol\";\r\n\r\nimport \"../external/uniswap/interfaces/ISwapRouter02.sol\";\r\nimport \"../interfaces/ISwapData.sol\";\r\n\r\n/// @notice Denotes swap action mode\r\nenum SwapAction {\r\n NONE,\r\n UNI_V2_DIRECT,\r\n UNI_V2_WETH,\r\n UNI_V2,\r\n UNI_V3_DIRECT,\r\n UNI_V3_WETH,\r\n UNI_V3\r\n}\r\n\r\n/// @title Contains logic facilitating swapping using Uniswap\r\nabstract contract SwapHelperUniswap {\r\n using BytesLib for bytes;\r\n using SafeERC20 for IERC20;\r\n\r\n /// @dev The length of the bytes encoded swap action\r\n uint256 internal constant ACTION_SIZE = 1;\r\n\r\n /// @dev The length of the bytes encoded address\r\n uint256 internal constant ADDR_SIZE = 20;\r\n\r\n /// @dev The length of the bytes encoded fee\r\n uint256 internal constant FEE_SIZE = 3;\r\n\r\n /// @dev The offset of a single token address and pool fee\r\n uint256 internal constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;\r\n\r\n /// @dev Maximum V2 path length (4 swaps)\r\n uint256 internal constant MAX_V2_PATH = ADDR_SIZE * 3;\r\n\r\n /// @dev V3 WETH path length\r\n uint256 internal constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE;\r\n\r\n /// @dev Minimum V3 custom path length (2 swaps)\r\n uint256 internal constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET;\r\n\r\n /// @dev Maximum V3 path length (4 swaps)\r\n uint256 internal constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3;\r\n\r\n /// @notice Uniswap router supporting Uniswap V2 and V3\r\n ISwapRouter02 internal immutable uniswapRouter;\r\n\r\n /// @notice Address of WETH token\r\n address private immutable WETH;\r\n\r\n /**\r\n * @notice Sets initial values\r\n * @param _uniswapRouter Uniswap router address\r\n * @param _WETH WETH token address\r\n */\r\n constructor(ISwapRouter02 _uniswapRouter, address _WETH) {\r\n uniswapRouter = _uniswapRouter;\r\n WETH = _WETH;\r\n }\r\n\r\n /**\r\n * @notice Approve reward token and swap the `amount` to a strategy underlying asset\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param swapData Swap details showing the path of the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _approveAndSwapUniswap(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n SwapData calldata swapData\r\n ) internal virtual returns (uint256) {\r\n\r\n // if there is nothing to swap, return\r\n if(amount == 0)\r\n return 0;\r\n\r\n // if amount is not uint256 max approve unswap router to spend tokens\r\n // otherwise rewards were already sent to the router\r\n if(amount < type(uint256).max) {\r\n from.safeApprove(address(uniswapRouter), amount);\r\n } else {\r\n amount = 0;\r\n }\r\n\r\n // get swap action from first byte\r\n SwapAction action = SwapAction(swapData.path.toUint8(0));\r\n uint256 result;\r\n\r\n if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct\r\n address[] memory path = new address[](2);\r\n result = _swapV2(from, to, amount, swapData.slippage, path);\r\n } else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH\r\n address[] memory path = new address[](3);\r\n path[1] = WETH;\r\n result = _swapV2(from, to, amount, swapData.slippage, path);\r\n } else if (action == SwapAction.UNI_V2) { // V2 Custom\r\n address[] memory path = _getV2Path(swapData.path);\r\n result = _swapV2(from, to, amount, swapData.slippage, path);\r\n } else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct\r\n result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path);\r\n } else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH\r\n bytes memory wethPath = _getV3WethPath(swapData.path);\r\n result = _swapV3(from, to, amount, swapData.slippage, wethPath);\r\n } else if (action == SwapAction.UNI_V3) { // V3 Custom\r\n require(swapData.path.length > MIN_V3_PATH, \"SwapHelper::_approveAndSwap: Path too short\");\r\n uint256 actualpathSize = swapData.path.length - ACTION_SIZE;\r\n require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 &&\r\n actualpathSize <= MAX_V3_PATH,\r\n \"SwapHelper::_approveAndSwap: Bad V3 path\");\r\n\r\n result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]);\r\n } else {\r\n revert(\"SwapHelper::_approveAndSwap: No action\");\r\n }\r\n\r\n if (from.allowance(address(this), address(uniswapRouter)) > 0) {\r\n from.safeApprove(address(uniswapRouter), 0);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * @notice Swaps tokens using Uniswap V2\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param slippage Allowed slippage\r\n * @param path Steps to complete the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _swapV2(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n uint256 slippage,\r\n address[] memory path\r\n ) internal virtual returns (uint256) {\r\n path[0] = address(from);\r\n path[path.length - 1] = address(to);\r\n\r\n return uniswapRouter.swapExactTokensForTokens(\r\n amount,\r\n slippage,\r\n path,\r\n address(this)\r\n );\r\n }\r\n\r\n /**\r\n * @notice Swaps tokens using Uniswap V3\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param slippage Allowed slippage\r\n * @param path Steps to complete the swap\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _swapV3(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n uint256 slippage,\r\n bytes memory path\r\n ) internal virtual returns (uint256) {\r\n IV3SwapRouter.ExactInputParams memory params =\r\n IV3SwapRouter.ExactInputParams({\r\n path: abi.encodePacked(address(from), path, address(to)),\r\n recipient: address(this),\r\n amountIn: amount,\r\n amountOutMinimum: slippage\r\n });\r\n\r\n // Executes the swap.\r\n uint received = uniswapRouter.exactInput(params);\r\n\r\n return received;\r\n }\r\n\r\n /**\r\n * @notice Does a direct swap from `from` address to the `to` address using Uniswap V3\r\n * @param from Token to swap from\r\n * @param to Token to swap to\r\n * @param amount Amount of tokens to swap\r\n * @param slippage Allowed slippage\r\n * @param fee V3 direct fee configuration\r\n * @return result Amount of underlying (`to`) tokens recieved\r\n */\r\n function _swapDirectV3(\r\n IERC20 from,\r\n IERC20 to,\r\n uint256 amount,\r\n uint256 slippage,\r\n bytes memory fee\r\n ) internal virtual returns (uint256) {\r\n require(fee.length == FEE_SIZE + ACTION_SIZE, \"SwapHelper::_swapDirectV3: Bad V3 direct fee\");\r\n\r\n IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams(\r\n address(from),\r\n address(to),\r\n // ignore first byte\r\n fee.toUint24(ACTION_SIZE),\r\n address(this),\r\n amount,\r\n slippage,\r\n 0\r\n );\r\n\r\n return uniswapRouter.exactInputSingle(params);\r\n }\r\n\r\n /**\r\n * @notice Converts passed bytes to V2 path\r\n * @param pathBytes Swap path in bytes, converted to addresses\r\n * @return path list of addresses in the swap path (skipping first and last element)\r\n */\r\n function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) {\r\n require(pathBytes.length > ACTION_SIZE, \"SwapHelper::_getV2Path: No path provided\");\r\n uint256 actualpathSize = pathBytes.length - ACTION_SIZE;\r\n require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, \"SwapHelper::_getV2Path: Bad V2 path\");\r\n\r\n uint256 pathLength = actualpathSize / ADDR_SIZE;\r\n address[] memory path = new address[](pathLength + 2);\r\n\r\n // ignore first byte\r\n path[1] = pathBytes.toAddress(ACTION_SIZE);\r\n for (uint256 i = 1; i < pathLength; i++) {\r\n path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE);\r\n }\r\n\r\n return path;\r\n }\r\n\r\n /**\r\n * @notice Get Unswap V3 path to swap tokens via WETH LP pool\r\n * @param pathBytes Swap path in bytes\r\n * @return wethPath Unswap V3 path routing via WETH pool\r\n */\r\n function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) {\r\n require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, \"SwapHelper::_getV3WethPath: Bad V3 WETH path\");\r\n // ignore first byte as it's used for swap action\r\n return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]);\r\n }\r\n}\r\n" }, "contracts/strategies/BaseStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../interfaces/IBaseStrategy.sol\";\r\nimport \"../shared/BaseStorage.sol\";\r\nimport \"../shared/Constants.sol\";\r\n\r\nimport \"../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol\";\r\nimport \"../libraries/Math.sol\";\r\nimport \"../libraries/Max/128Bit.sol\";\r\n\r\n/**\r\n * @notice Implementation of the {IBaseStrategy} interface.\r\n *\r\n * @dev\r\n * This implementation of the {IBaseStrategy} is meant to operate\r\n * on single-collateral strategies and uses a delta system to calculate\r\n * whether a withdrawal or deposit needs to be performed for a particular\r\n * strategy.\r\n */\r\nabstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants {\r\n using SafeERC20 for IERC20;\r\n using Max128Bit for uint128;\r\n\r\n /* ========== CONSTANTS ========== */\r\n\r\n /// @notice Value to multiply new deposit recieved to get the share amount\r\n uint128 private constant SHARES_MULTIPLIER = 10**6;\r\n \r\n /// @notice number of locked shares when initial shares are added\r\n /// @dev This is done to prevent rounding errors and share manipulation\r\n uint128 private constant INITIAL_SHARES_LOCKED = 10**11;\r\n\r\n /// @notice minimum shares size to avoid loss of share due to computation precision\r\n /// @dev If total shares go unders this value, new deposit is multiplied by the `SHARES_MULTIPLIER` again\r\n uint256 private constant MIN_SHARES_FOR_ACCURACY = INITIAL_SHARES_LOCKED * 10;\r\n\r\n /* ========== STATE VARIABLES ========== */\r\n\r\n /// @notice The total slippage slots the strategy supports, used for validation of provided slippage\r\n uint256 internal immutable rewardSlippageSlots;\r\n\r\n /// @notice Slots for processing\r\n uint256 internal immutable processSlippageSlots;\r\n\r\n /// @notice Slots for reallocation\r\n uint256 internal immutable reallocationSlippageSlots;\r\n\r\n /// @notice Slots for deposit\r\n uint256 internal immutable depositSlippageSlots;\r\n\r\n /** \r\n * @notice do force claim of rewards.\r\n *\r\n * @dev\r\n * Some strategies auto claim on deposit/withdraw,\r\n * so execute the claim actions to store the reward amounts.\r\n */\r\n bool internal immutable forceClaim;\r\n\r\n /// @notice flag to force balance validation before running process strategy\r\n /// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system\r\n bool internal immutable doValidateBalance;\r\n\r\n /// @notice The self address, set at initialization to allow proper share accounting\r\n address internal immutable self;\r\n\r\n /// @notice The underlying asset of the strategy\r\n IERC20 public immutable override underlying;\r\n\r\n /* ========== CONSTRUCTOR ========== */\r\n\r\n /**\r\n * @notice Initializes the base strategy values.\r\n *\r\n * @dev\r\n * It performs certain pre-conditional validations to ensure the contract\r\n * has been initialized properly, such as that the address argument of the\r\n * underlying asset is valid.\r\n *\r\n * Slippage slots for certain strategies may be zero if there is no compounding\r\n * work to be done.\r\n * \r\n * @param _underlying token used for deposits\r\n * @param _rewardSlippageSlots slots for rewards\r\n * @param _processSlippageSlots slots for processing\r\n * @param _reallocationSlippageSlots slots for reallocation\r\n * @param _depositSlippageSlots slots for deposits\r\n * @param _forceClaim force claim of rewards\r\n * @param _doValidateBalance force balance validation\r\n */\r\n constructor(\r\n IERC20 _underlying,\r\n uint256 _rewardSlippageSlots,\r\n uint256 _processSlippageSlots,\r\n uint256 _reallocationSlippageSlots,\r\n uint256 _depositSlippageSlots,\r\n bool _forceClaim,\r\n bool _doValidateBalance,\r\n address _self\r\n ) {\r\n require(\r\n _underlying != IERC20(address(0)),\r\n \"BaseStrategy::constructor: Underlying address cannot be 0\"\r\n );\r\n\r\n self = _self == address(0) ? address(this) : _self;\r\n\r\n underlying = _underlying;\r\n rewardSlippageSlots = _rewardSlippageSlots;\r\n processSlippageSlots = _processSlippageSlots;\r\n reallocationSlippageSlots = _reallocationSlippageSlots;\r\n depositSlippageSlots = _depositSlippageSlots;\r\n forceClaim = _forceClaim;\r\n doValidateBalance = _doValidateBalance;\r\n }\r\n\r\n /* ========== MUTATIVE FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Process the latest pending action of the strategy\r\n *\r\n * @dev\r\n * it yields amount of funds processed as well as the reward buffer of the strategy.\r\n * The function will auto-compound rewards if requested and supported.\r\n *\r\n * Requirements:\r\n *\r\n * - the slippages provided must be valid in length\r\n * - if the redeposit flag is set to true, the strategy must support\r\n * compounding of rewards\r\n *\r\n * @param slippages slippages to process\r\n * @param redeposit if redepositing is to occur\r\n * @param swapData swap data for processing\r\n */\r\n function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override\r\n {\r\n slippages = _validateStrategyBalance(slippages);\r\n\r\n if (forceClaim || redeposit) {\r\n _validateRewardsSlippage(swapData);\r\n _processRewards(swapData);\r\n }\r\n\r\n if (processSlippageSlots != 0)\r\n _validateProcessSlippage(slippages);\r\n \r\n _process(slippages, 0);\r\n }\r\n\r\n /**\r\n * @notice Process first part of the reallocation DHW\r\n * @dev Withdraws for reallocation, depositn and withdraww for a user\r\n *\r\n * @param slippages Parameters to apply when performing a deposit or a withdraw\r\n * @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw\r\n * @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw\r\n */\r\n function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128) {\r\n slippages = _validateStrategyBalance(slippages);\r\n\r\n if (reallocationSlippageSlots != 0)\r\n _validateReallocationSlippage(slippages);\r\n\r\n _process(slippages, processReallocationData.sharesToWithdraw);\r\n\r\n uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData);\r\n\r\n return withdrawnReallocationReceived;\r\n }\r\n\r\n /**\r\n * @dev Update reallocation batch storage for index after withdrawing reallocated shares\r\n * @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw\r\n * @return Withdrawn reallocation received\r\n */\r\n function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) {\r\n Strategy storage strategy = strategies[self];\r\n uint24 stratIndex = _getProcessingIndex();\r\n BatchReallocation storage batch = strategy.reallocationBatches[stratIndex];\r\n\r\n // save actual withdrawn amount, without optimized one \r\n uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived;\r\n\r\n strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares;\r\n batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount;\r\n batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw;\r\n\r\n return withdrawnReallocationReceived;\r\n }\r\n\r\n /**\r\n * @notice Process deposit\r\n * @param slippages Array of slippage parameters to apply when depositing\r\n */\r\n function processDeposit(uint256[] calldata slippages)\r\n external\r\n override\r\n {\r\n slippages = _validateStrategyBalance(slippages);\r\n\r\n if (depositSlippageSlots != 0)\r\n _validateDepositSlippage(slippages);\r\n _processDeposit(slippages);\r\n }\r\n\r\n /**\r\n * @notice Returns total starategy balance includign pending rewards\r\n * @return strategyBalance total starategy balance includign pending rewards\r\n */\r\n function getStrategyUnderlyingWithRewards() public view override returns(uint128)\r\n {\r\n return _getStrategyUnderlyingWithRewards();\r\n }\r\n\r\n /**\r\n * @notice Fast withdraw\r\n * @param shares Shares to fast withdraw\r\n * @param slippages Array of slippage parameters to apply when withdrawing\r\n * @param swapData Swap slippage and path array\r\n * @return Withdrawn amount withdawn\r\n */\r\n function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128)\r\n {\r\n slippages = _validateStrategyBalance(slippages);\r\n\r\n _validateRewardsSlippage(swapData);\r\n\r\n if (processSlippageSlots != 0)\r\n _validateProcessSlippage(slippages);\r\n\r\n uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData);\r\n strategies[self].totalShares -= shares;\r\n return withdrawnAmount;\r\n }\r\n\r\n /**\r\n * @notice Claims and possibly compounds strategy rewards.\r\n *\r\n * @param swapData swap data for processing\r\n */\r\n function claimRewards(SwapData[] calldata swapData) external override\r\n {\r\n _validateRewardsSlippage(swapData);\r\n _processRewards(swapData);\r\n }\r\n\r\n /**\r\n * @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process.\r\n *\r\n * @param recipient recipient of the withdrawn funds\r\n * @param data data necessary execute the emergency withdraw\r\n */\r\n function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override {\r\n uint256 balanceBefore = underlying.balanceOf(address(this));\r\n _emergencyWithdraw(recipient, data);\r\n uint256 balanceAfter = underlying.balanceOf(address(this));\r\n\r\n uint256 withdrawnAmount = 0;\r\n if (balanceAfter > balanceBefore) {\r\n withdrawnAmount = balanceAfter - balanceBefore;\r\n }\r\n \r\n Strategy storage strategy = strategies[self];\r\n if (strategy.emergencyPending > 0) {\r\n withdrawnAmount += strategy.emergencyPending;\r\n strategy.emergencyPending = 0;\r\n }\r\n\r\n // also withdraw all unprocessed deposit for a strategy\r\n if (strategy.pendingUser.deposit.get() > 0) {\r\n withdrawnAmount += strategy.pendingUser.deposit.get();\r\n strategy.pendingUser.deposit = 0;\r\n }\r\n\r\n if (strategy.pendingUserNext.deposit.get() > 0) {\r\n withdrawnAmount += strategy.pendingUserNext.deposit.get();\r\n strategy.pendingUserNext.deposit = 0;\r\n }\r\n \r\n strategy.pendingUser.deposit = strategy.pendingUser.deposit.set();\r\n strategy.pendingUserNext.deposit = strategy.pendingUserNext.deposit.set();\r\n\r\n // if strategy was already processed in the current index that hasn't finished yet,\r\n // transfer the withdrawn amount\r\n // reset total underlying to 0\r\n if (strategy.index == globalIndex && doHardWorksLeft > 0) {\r\n uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived;\r\n withdrawnAmount += withdrawnReceived;\r\n strategy.batches[strategy.index].withdrawnReceived = 0;\r\n\r\n strategy.totalUnderlying[strategy.index].amount = 0;\r\n }\r\n\r\n if (withdrawnAmount > 0) {\r\n // check if the balance is high enough to withdraw the total withdrawnAmount\r\n if (balanceAfter < withdrawnAmount) {\r\n // if not withdraw the current balance\r\n withdrawnAmount = balanceAfter;\r\n }\r\n\r\n underlying.safeTransfer(recipient, withdrawnAmount);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Initialize a strategy.\r\n * @dev Execute strategy specific one-time actions if needed.\r\n */\r\n function initialize() external virtual override {}\r\n\r\n /**\r\n * @notice Disables a strategy.\r\n * @dev Cleans strategy specific values if needed.\r\n */\r\n function disable() external virtual override {}\r\n\r\n /* ========== INTERNAL FUNCTIONS ========== */\r\n\r\n /**\r\n * @dev Validate strategy balance\r\n * @param slippages Check if the strategy balance is within defined min and max values\r\n * @return slippages Same array without first 2 slippages\r\n */\r\n function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) {\r\n if (doValidateBalance) {\r\n require(slippages.length >= 4, \"BaseStrategy:: _validateStrategyBalance: Invalid number of slippages\");\r\n uint128 strategyBalance = getStrategyBalance();\r\n\r\n require(\r\n slippages[0] <= strategyBalance &&\r\n slippages[1] >= strategyBalance,\r\n \"BaseStrategy::_validateStrategyBalance: Bad strategy balance\"\r\n );\r\n\r\n uint128 strategyPrice = getStrategyPrice();\r\n\r\n require(\r\n slippages[2] <= strategyPrice &&\r\n slippages[3] >= strategyPrice,\r\n \"BaseStrategy::_validateStrategyBalance: Bad strategy price\"\r\n );\r\n\r\n return slippages[4:];\r\n }\r\n\r\n return slippages;\r\n }\r\n\r\n /**\r\n * @dev Validate reards slippage\r\n * @param swapData Swap slippage and path array\r\n */\r\n function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual {\r\n if (swapData.length > 0) {\r\n require(\r\n swapData.length == _getRewardSlippageSlots(),\r\n \"BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined\"\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * @dev Retrieve reward slippage slots\r\n * @return Reward slippage slots\r\n */\r\n function _getRewardSlippageSlots() internal view virtual returns(uint256) {\r\n return rewardSlippageSlots;\r\n }\r\n\r\n /**\r\n * @dev Validate process slippage\r\n * @param slippages parameters to verify validity of the strategy state\r\n */\r\n function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual {\r\n _validateSlippage(slippages.length, processSlippageSlots);\r\n }\r\n\r\n /**\r\n * @dev Validate reallocation slippage\r\n * @param slippages parameters to verify validity of the strategy state\r\n */\r\n function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual {\r\n _validateSlippage(slippages.length, reallocationSlippageSlots);\r\n }\r\n\r\n /**\r\n * @dev Validate deposit slippage\r\n * @param slippages parameters to verify validity of the strategy state\r\n */\r\n function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual {\r\n _validateSlippage(slippages.length, depositSlippageSlots);\r\n }\r\n\r\n /**\r\n * @dev Validates the provided slippage in length.\r\n * @param currentLength actual slippage array length\r\n * @param shouldBeLength expected slippages array length\r\n */\r\n function _validateSlippage(uint256 currentLength, uint256 shouldBeLength)\r\n internal\r\n view\r\n virtual\r\n {\r\n require(\r\n currentLength == shouldBeLength,\r\n \"BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined\"\r\n );\r\n }\r\n\r\n /**\r\n * @dev Retrieve processing index\r\n * @return Processing index\r\n */\r\n function _getProcessingIndex() internal view returns(uint24) {\r\n return strategies[self].index + 1;\r\n }\r\n\r\n /**\r\n * @dev Calculates shares before they are added to the total shares\r\n * @param strategyTotalShares Total shares for strategy\r\n * @param stratTotalUnderlying Total underlying for strategy\r\n * @param depositAmount Deposit amount recieved\r\n * @return newShares New shares calculated\r\n */\r\n function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128, uint128){\r\n uint128 oldUnderlying;\r\n if (stratTotalUnderlying > depositAmount) {\r\n unchecked {\r\n oldUnderlying = stratTotalUnderlying - depositAmount;\r\n }\r\n }\r\n\r\n return _getNewShares(strategyTotalShares, oldUnderlying, depositAmount);\r\n }\r\n\r\n /**\r\n * @dev Calculates shares when they are already part of the total shares\r\n *\r\n * @param strategyTotalShares Total shares\r\n * @param stratTotalUnderlying Total underlying\r\n * @param depositAmount Deposit amount recieved\r\n * @return newShares New shares calculated\r\n */\r\n function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares, uint128){\r\n if (strategyTotalShares <= MIN_SHARES_FOR_ACCURACY || stratTotalUnderlying == 0) {\r\n (newShares, strategyTotalShares) = _setNewShares(strategyTotalShares, depositAmount);\r\n } else {\r\n newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying);\r\n }\r\n\r\n strategyTotalShares += newShares;\r\n\r\n return (newShares, strategyTotalShares);\r\n }\r\n\r\n /**\r\n * @notice Sets new shares if strategy does not have enough locked shares and calculated new shares based on deposit recieved\r\n * @dev\r\n * This is used when a strategy is new and does not have enough shares locked.\r\n * Shares are locked to prevent rounding errors and to keep share to underlying amount\r\n * ratio correct, to ensure the normal working of the share system._awaitingEmergencyWithdraw\r\n * We always want to have more shares than the underlying value of the strategy.\r\n *\r\n * @param strategyTotalShares Total shares\r\n * @param depositAmount Deposit amount recieved\r\n * @return newShares New shares calculated\r\n */\r\n function _setNewShares(uint128 strategyTotalShares, uint128 depositAmount) private pure returns(uint128, uint128) {\r\n // Enforce minimum shares size to avoid loss of share due to computation precision\r\n uint128 newShares = depositAmount * SHARES_MULTIPLIER;\r\n\r\n if (strategyTotalShares < INITIAL_SHARES_LOCKED) {\r\n if (newShares + strategyTotalShares >= INITIAL_SHARES_LOCKED) {\r\n unchecked {\r\n uint128 newLockedShares = INITIAL_SHARES_LOCKED - strategyTotalShares;\r\n strategyTotalShares += newLockedShares;\r\n newShares -= newLockedShares;\r\n }\r\n } else {\r\n newShares = 0;\r\n }\r\n }\r\n\r\n return (newShares, strategyTotalShares);\r\n }\r\n\r\n /**\r\n * @dev Reset allowance to zero if previously set to a higher value.\r\n * @param token Asset\r\n * @param spender Spender address\r\n */\r\n function _resetAllowance(IERC20 token, address spender) internal {\r\n if (token.allowance(address(this), spender) > 0) {\r\n token.safeApprove(spender, 0);\r\n }\r\n }\r\n\r\n /* ========== VIRTUAL FUNCTIONS ========== */\r\n\r\n function getStrategyBalance()\r\n public\r\n view\r\n virtual\r\n override\r\n returns (uint128);\r\n\r\n function getStrategyPrice()\r\n public\r\n view\r\n virtual\r\n override\r\n returns (uint128){\r\n return 0;\r\n }\r\n\r\n function _processRewards(SwapData[] calldata) internal virtual;\r\n function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual;\r\n function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual;\r\n function _processDeposit(uint256[] memory) internal virtual;\r\n function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128);\r\n function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128);\r\n}\r\n" }, "contracts/strategies/MultipleRewardStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./RewardStrategy.sol\";\r\nimport \"../shared/SwapHelperMainnet.sol\";\r\n\r\n/**\r\n * @notice Multiple reward strategy logic\r\n */\r\nabstract contract MultipleRewardStrategy is RewardStrategy, SwapHelperMainnet {\r\n /* ========== OVERRIDDEN FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Claim rewards\r\n * @param swapData Slippage and path array\r\n * @return Rewards\r\n */\r\n function _claimRewards(SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) {\r\n return _claimMultipleRewards(type(uint128).max, swapData);\r\n }\r\n\r\n /**\r\n * @dev Claim fast withdraw rewards\r\n * @param shares Amount of shares\r\n * @param swapData Swap slippage and path\r\n * @return Rewards\r\n */\r\n function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) {\r\n return _claimMultipleRewards(shares, swapData);\r\n }\r\n\r\n /* ========== VIRTUAL FUNCTIONS ========== */\r\n\r\n function _claimMultipleRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);\r\n}\r\n" }, "contracts/strategies/ProcessStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./BaseStrategy.sol\";\r\n\r\nimport \"../libraries/Max/128Bit.sol\";\r\nimport \"../libraries/Math.sol\";\r\n\r\nstruct ProcessInfo {\r\n uint128 totalWithdrawReceived;\r\n uint128 userDepositReceived;\r\n}\r\n\r\n/**\r\n * @notice Process strategy logic\r\n */\r\nabstract contract ProcessStrategy is BaseStrategy {\r\n using Max128Bit for uint128;\r\n\r\n /* ========== OVERRIDDEN FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards\r\n * @dev\r\n * Deposit amount amd withdrawal shares are matched between eachother, effecively only one of\r\n * those 2 is called. Shares are converted to the dollar value, based on the current strategy\r\n * total balance. This ensures the minimum amount of assets are moved around to lower the price\r\n * drift and total fees paid to the protocols the strategy is interacting with (if there are any)\r\n *\r\n * @param slippages Strategy slippage values verifying the validity of the strategy state\r\n * @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0)\r\n */\r\n function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual {\r\n // PREPARE\r\n Strategy storage strategy = strategies[self];\r\n uint24 processingIndex = _getProcessingIndex();\r\n Batch storage batch = strategy.batches[processingIndex];\r\n uint128 strategyTotalShares = strategy.totalShares;\r\n uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get();\r\n uint128 userDeposit = strategy.pendingUser.deposit.get();\r\n\r\n // CALCULATE THE ACTION\r\n\r\n // if withdrawing for reallocating, add shares to total withdraw shares\r\n if (reallocateSharesToWithdraw > 0) {\r\n pendingSharesToWithdraw += reallocateSharesToWithdraw;\r\n }\r\n\r\n // total deposit received from users + compound reward (if there are any)\r\n uint128 totalPendingDeposit = userDeposit;\r\n \r\n // add compound reward (pendingDepositReward) to deposit\r\n uint128 withdrawalReward = 0;\r\n if (strategy.pendingDepositReward > 0) {\r\n uint128 pendingDepositReward = strategy.pendingDepositReward;\r\n\r\n totalPendingDeposit += pendingDepositReward;\r\n\r\n // calculate compound reward (withdrawalReward) for users withdrawing in this batch\r\n if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) {\r\n withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares);\r\n\r\n // substract withdrawal reward from total deposit\r\n totalPendingDeposit -= withdrawalReward;\r\n }\r\n\r\n // Reset pendingDepositReward\r\n strategy.pendingDepositReward = 0;\r\n }\r\n\r\n // if there is no pending deposit or withdrawals, return\r\n if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) {\r\n // Set underlying at index\r\n strategy.totalUnderlying[processingIndex].amount = getStrategyBalance();\r\n return;\r\n }\r\n\r\n uint128 pendingWithdrawalAmount = 0;\r\n if (pendingSharesToWithdraw > 0) {\r\n pendingWithdrawalAmount = \r\n Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares);\r\n }\r\n\r\n // ACTION: DEPOSIT OR WITHDRAW\r\n ProcessInfo memory processInfo;\r\n if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT\r\n // uint128 amount = totalPendingDeposit - pendingWithdrawalAmount;\r\n uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages);\r\n\r\n processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;\r\n\r\n // pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount;\r\n uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount;\r\n \r\n // calculate user deposit received, excluding compound rewards\r\n processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit);\r\n } else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW\r\n // uint128 amount = pendingWithdrawalAmount - totalPendingDeposit;\r\n\r\n uint128 withdrawReceived = _withdraw(\r\n // calculate back the shares from actual withdraw amount\r\n // NOTE: we can do unchecked calculation and casting as\r\n // the multiplier is always smaller than the divisor\r\n Math.getProportion128Unchecked(\r\n (pendingWithdrawalAmount - totalPendingDeposit),\r\n pendingSharesToWithdraw,\r\n pendingWithdrawalAmount\r\n ),\r\n slippages\r\n );\r\n\r\n // optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit;\r\n processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward;\r\n processInfo.userDepositReceived = userDeposit;\r\n } else {\r\n processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;\r\n processInfo.userDepositReceived = userDeposit;\r\n }\r\n \r\n // UPDATE STORAGE AFTER\r\n {\r\n uint128 stratTotalUnderlying = getStrategyBalance();\r\n\r\n // Update withdraw batch\r\n if (pendingSharesToWithdraw > 0) {\r\n batch.withdrawnReceived = processInfo.totalWithdrawReceived;\r\n batch.withdrawnShares = pendingSharesToWithdraw;\r\n \r\n strategyTotalShares -= pendingSharesToWithdraw;\r\n\r\n // update reallocation batch\r\n if (reallocateSharesToWithdraw > 0) {\r\n BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];\r\n\r\n uint128 withdrawnReallocationReceived =\r\n Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw);\r\n reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived;\r\n\r\n // substract reallocation values from user values\r\n batch.withdrawnReceived -= withdrawnReallocationReceived;\r\n batch.withdrawnShares -= reallocateSharesToWithdraw;\r\n }\r\n }\r\n\r\n // Update deposit batch\r\n if (userDeposit > 0) {\r\n uint128 newShares;\r\n (newShares, strategyTotalShares) = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived);\r\n\r\n batch.deposited = userDeposit;\r\n batch.depositedReceived = processInfo.userDepositReceived;\r\n batch.depositedSharesReceived = newShares;\r\n }\r\n\r\n // Update shares\r\n if (strategyTotalShares != strategy.totalShares) {\r\n strategy.totalShares = strategyTotalShares;\r\n }\r\n\r\n // Set underlying at index\r\n strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;\r\n strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;\r\n }\r\n }\r\n\r\n /**\r\n * @notice Process deposit\r\n * @param slippages Slippages array\r\n */\r\n function _processDeposit(uint256[] memory slippages) internal override virtual {\r\n Strategy storage strategy = strategies[self];\r\n \r\n uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit;\r\n uint128 depositAverageAmount = strategy.pendingReallocateAverageDeposit;\r\n uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn;\r\n uint128 depositAmount = strategy.pendingReallocateDeposit;\r\n\r\n // if a strategy is not part of reallocation return\r\n if (\r\n depositOptimizedAmount == 0 &&\r\n optimizedSharesWithdrawn == 0 &&\r\n depositAverageAmount == 0 &&\r\n depositAmount == 0\r\n ) {\r\n return;\r\n }\r\n\r\n uint24 processingIndex = _getProcessingIndex();\r\n BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];\r\n \r\n uint128 strategyTotalShares = strategy.totalShares;\r\n \r\n // add shares from optimized deposit\r\n if (depositOptimizedAmount > 0) {\r\n uint128 stratTotalUnderlying = getStrategyBalance();\r\n uint128 newShares;\r\n (newShares, strategyTotalShares) = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount);\r\n\r\n // update reallocation batch deposit shares\r\n reallocationBatch.depositedReallocationSharesReceived = newShares;\r\n\r\n strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;\r\n\r\n // reset\r\n strategy.pendingReallocateOptimizedDeposit = 0;\r\n }\r\n\r\n if (depositAverageAmount > 0) {\r\n reallocationBatch.depositedReallocation += depositAverageAmount;\r\n strategy.pendingReallocateAverageDeposit = 0;\r\n }\r\n\r\n // remove optimized withdraw shares\r\n if (optimizedSharesWithdrawn > 0) {\r\n strategyTotalShares -= optimizedSharesWithdrawn;\r\n\r\n // reset\r\n strategy.optimizedSharesWithdrawn = 0;\r\n }\r\n\r\n // add shares from actual deposit\r\n if (depositAmount > 0) {\r\n // deposit\r\n uint128 depositReceived = _deposit(depositAmount, slippages);\r\n\r\n // NOTE: might return it from _deposit (only certain strategies need it)\r\n uint128 stratTotalUnderlying = getStrategyBalance();\r\n\r\n if (depositReceived > 0) {\r\n uint128 newShares;\r\n (newShares, strategyTotalShares) = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived);\r\n\r\n // update reallocation batch deposit shares\r\n reallocationBatch.depositedReallocationSharesReceived += newShares;\r\n }\r\n\r\n strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;\r\n\r\n // reset\r\n strategy.pendingReallocateDeposit = 0;\r\n }\r\n\r\n // update share storage\r\n strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;\r\n strategy.totalShares = strategyTotalShares;\r\n }\r\n\r\n /* ========== INTERNAL FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice get the value of the strategy shares in the underlying tokens\r\n * @param shares Number of shares\r\n * @return amount Underling amount representing the `share` value of the strategy\r\n */\r\n function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) {\r\n amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares );\r\n }\r\n\r\n /**\r\n * @notice get slippage amount, and action type (withdraw/deposit).\r\n * @dev\r\n * Most significant bit represents an action, 0 for a withdrawal and 1 for deposit.\r\n *\r\n * This ensures the slippage will be used for the action intended by the do-hard-worker,\r\n * otherwise the transavtion will revert.\r\n *\r\n * @param slippageAction number containing the slippage action and the actual slippage amount\r\n * @return isDeposit Flag showing if the slippage is for the deposit action\r\n * @return slippage the slippage value cleaned of the most significant bit\r\n */\r\n function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) {\r\n // remove most significant bit\r\n slippage = (slippageAction << 1) >> 1;\r\n\r\n // if values are not the same (the removed bit was 1) set action to deposit\r\n if (slippageAction != slippage) {\r\n isDeposit = true;\r\n }\r\n }\r\n\r\n /* ========== VIRTUAL FUNCTIONS ========== */\r\n\r\n function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived);\r\n function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived);\r\n}\r\n" }, "contracts/strategies/RewardStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"./ProcessStrategy.sol\";\r\nimport \"../shared/SwapHelper.sol\";\r\n\r\nstruct Reward {\r\n uint256 amount;\r\n IERC20 token;\r\n}\r\n\r\n/**\r\n * @notice Reward strategy logic\r\n */\r\nabstract contract RewardStrategy is ProcessStrategy, SwapHelper {\r\n\r\n /* ========== OVERRIDDEN FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Gey strategy underlying asset with rewards\r\n * @return Total underlying\r\n */\r\n function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) {\r\n Strategy storage strategy = strategies[self];\r\n\r\n uint128 totalUnderlying = getStrategyBalance();\r\n totalUnderlying += strategy.pendingDepositReward;\r\n\r\n return totalUnderlying;\r\n }\r\n\r\n /**\r\n * @notice Process an instant withdrawal from the protocol per users request.\r\n *\r\n * @param shares Amount of shares\r\n * @param slippages Array of slippages\r\n * @param swapData Data used in processing\r\n * @return Withdrawn amount\r\n */\r\n function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) {\r\n uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData);\r\n\r\n uint128 withdrawReceived = _withdraw(shares, slippages);\r\n\r\n return withdrawReceived + withdrawRewards;\r\n }\r\n\r\n /**\r\n * @notice Process rewards\r\n * @param swapData Data used in processing\r\n */\r\n function _processRewards(SwapData[] calldata swapData) internal override virtual {\r\n Strategy storage strategy = strategies[self];\r\n\r\n Reward[] memory rewards = _claimRewards(swapData);\r\n\r\n uint128 collectedAmount = _sellRewards(rewards, swapData);\r\n\r\n if (collectedAmount > 0) {\r\n strategy.pendingDepositReward += collectedAmount;\r\n }\r\n }\r\n\r\n /* ========== INTERNAL FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Process fast withdrawal rewards\r\n * @param shares Amount of shares\r\n * @param swapData Values used for swapping the rewards\r\n * @return withdrawalRewards Withdrawal rewards\r\n */\r\n function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) {\r\n Strategy storage strategy = strategies[self];\r\n\r\n Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData);\r\n \r\n withdrawalRewards += _sellRewards(rewards, swapData);\r\n \r\n if (strategy.pendingDepositReward > 0) {\r\n uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares);\r\n if (fastWithdrawCompound > 0) {\r\n strategy.pendingDepositReward -= fastWithdrawCompound;\r\n withdrawalRewards += fastWithdrawCompound;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Sell rewards to the underlying token\r\n * @param rewards Rewards to sell\r\n * @param swapData Values used for swapping the rewards\r\n * @return collectedAmount Collected underlying amount\r\n */\r\n function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) {\r\n for (uint256 i = 0; i < rewards.length; i++) {\r\n // add compound amount from current batch to the fast withdraw\r\n if (rewards[i].amount > 0) { \r\n uint128 compoundAmount = SafeCast.toUint128(\r\n _approveAndSwap(\r\n rewards[i].token,\r\n underlying,\r\n rewards[i].amount,\r\n swapData[i]\r\n )\r\n );\r\n\r\n // add to pending reward\r\n collectedAmount += compoundAmount;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Get reward claim amount for `shares`\r\n * @param shares Amount of shares\r\n * @param rewardAmount Total reward amount\r\n * @return rewardAmount Amount of reward for the shares\r\n */\r\n function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) {\r\n // for do hard work claim everything\r\n if (shares == type(uint128).max) {\r\n return SafeCast.toUint128(rewardAmount);\r\n } else { // for fast withdrawal claim calculate user withdraw amount\r\n return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares);\r\n }\r\n }\r\n\r\n /* ========== VIRTUAL FUNCTIONS ========== */\r\n \r\n function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);\r\n function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);\r\n}\r\n" }, "contracts/strategies/idle/IdleStrategy.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\r\n\r\npragma solidity 0.8.11;\r\n\r\nimport \"../MultipleRewardStrategy.sol\";\r\nimport \"../../external/interfaces/idle-finance/IIdleToken.sol\";\r\nimport \"../../external/interfaces/aave/ILendingPool.sol\";\r\n\r\n/**\r\n * @notice Idle strategy implementation\r\n */\r\ncontract IdleStrategy is MultipleRewardStrategy {\r\n using SafeERC20 for IERC20;\r\n\r\n /* ========== STATE VARIABLES ========== */\r\n\r\n /// @notice Idle token contract\r\n IIdleToken public immutable idleToken;\r\n\r\n /// @notice One idle token shares amount\r\n uint256 public immutable oneShare;\r\n\r\n /* ========== CONSTRUCTOR ========== */\r\n\r\n /**\r\n * @notice Set initial values\r\n * @param _idleToken Idle token contract\r\n * @param _underlying Underlying asset\r\n */\r\n constructor(\r\n IIdleToken _idleToken,\r\n IERC20 _underlying,\r\n address _self\r\n )\r\n BaseStrategy(_underlying, 0, 1, 1, 1, true, false, _self)\r\n {\r\n require(address(_idleToken) != address(0), \"IdleStrategy::constructor: Token address cannot be 0\");\r\n idleToken = _idleToken;\r\n oneShare = 10 ** uint256(_idleToken.decimals());\r\n }\r\n\r\n /* ========== VIEWS ========== */\r\n\r\n /**\r\n * @notice Get strategy balance\r\n * @return strategyBalance Strategy balance in strategy underlying tokens\r\n */\r\n function getStrategyBalance() public view override returns(uint128) {\r\n uint256 idleTokenBalance = idleToken.balanceOf(address(this));\r\n return SafeCast.toUint128(_getIdleTokenValue(idleTokenBalance));\r\n }\r\n\r\n /* ========== OVERRIDDEN FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Dynamically return reward slippage length\r\n * @dev Reward slippage lenght corresponds with amount of reward tokens a strategy provides\r\n */\r\n function _getRewardSlippageSlots() internal view override returns(uint256) {\r\n return idleToken.getGovTokens().length;\r\n }\r\n\r\n /**\r\n * @notice Deposit to Idle (mint idle tokens)\r\n * @param amount Amount to deposit\r\n * @param slippages Slippages array\r\n * @return Minted idle amount\r\n */\r\n function _deposit(uint128 amount, uint256[] memory slippages) internal override returns(uint128) {\r\n (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]);\r\n require(isDeposit, \"IdleStrategy::_deposit: Withdraw slippage provided\");\r\n\r\n // deposit underlying\r\n underlying.safeApprove(address(idleToken), amount);\r\n // NOTE: Middle Flag is unused so can be anything\r\n uint256 mintedIdleAmount = idleToken.mintIdleToken(\r\n amount,\r\n true,\r\n address(this)\r\n );\r\n _resetAllowance(underlying, address(idleToken));\r\n\r\n require(\r\n mintedIdleAmount >= slippage,\r\n \"IdleStrategy::_deposit: Insufficient Idle Amount Minted\"\r\n );\r\n\r\n emit Slippage(self, underlying, true, amount, mintedIdleAmount);\r\n\r\n return SafeCast.toUint128(_getIdleTokenValue(mintedIdleAmount));\r\n }\r\n\r\n /**\r\n * @notice Withdraw from the Idle strategy\r\n * @param shares Amount of shares to withdraw\r\n * @param slippages Slippage values\r\n * @return undelyingWithdrawn Withdrawn underlying recieved amount\r\n */\r\n function _withdraw(uint128 shares, uint256[] memory slippages) internal override returns(uint128) {\r\n (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]);\r\n require(!isDeposit, \"IdleStrategy::_withdraw: Deposit slippage provided\");\r\n\r\n uint256 idleTokensTotal = idleToken.balanceOf(address(this));\r\n\r\n uint256 redeemIdleAmount = (idleTokensTotal * shares) / strategies[self].totalShares;\r\n\r\n // withdraw idle tokens from vault\r\n uint256 undelyingBefore = underlying.balanceOf(address(this));\r\n idleToken.redeemIdleToken(redeemIdleAmount);\r\n uint256 underlyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore;\r\n\r\n require(\r\n underlyingWithdrawn >= slippage,\r\n \"IdleStrategy::_withdraw: Insufficient withdrawn amount\"\r\n );\r\n\r\n emit Slippage(self, underlying, false, shares, underlyingWithdrawn);\r\n\r\n return SafeCast.toUint128(underlyingWithdrawn);\r\n }\r\n\r\n /**\r\n * @notice Emergency withdraw all the balance from the idle strategy\r\n */\r\n function _emergencyWithdraw(address recipient, uint256[] calldata data) internal override {\r\n if(data.length == 0){\r\n idleToken.redeemIdleToken(idleToken.balanceOf(address(this)));\r\n } else {\r\n IERC20 aToken = IERC20(address(uint160(data[0])));\r\n ILendingPool lendingPool = ILendingPool(address(uint160(data[1])));\r\n\r\n uint aTokenBalanceBefore = aToken.balanceOf(address(this));\r\n idleToken.redeemInterestBearingTokens(idleToken.balanceOf(address(this)));\r\n uint aTokenWithdrawn = aToken.balanceOf(address(this)) - aTokenBalanceBefore;\r\n\r\n lendingPool.withdraw(\r\n address(underlying),\r\n aTokenWithdrawn,\r\n recipient\r\n );\r\n }\r\n }\r\n\r\n /* ========== PRIVATE FUNCTIONS ========== */\r\n\r\n /**\r\n * @notice Get idle token value for the given token amount\r\n * @param idleAmount Idle token amount\r\n * @return Token value for given amount\r\n */\r\n function _getIdleTokenValue(uint256 idleAmount) private view returns(uint256) {\r\n if (idleAmount == 0)\r\n return 0;\r\n \r\n return (idleAmount * idleToken.tokenPriceWithFee(address(this))) / oneShare;\r\n }\r\n\r\n /**\r\n * @notice Claim all idle governance reward tokens\r\n * @dev Force claiming tokens on every strategy interaction\r\n * @param shares amount of shares to claim for\r\n * @param _swapData Swap values, representing paths to swap the tokens to underlying\r\n * @return rewards Claimed reward tokens\r\n */\r\n function _claimMultipleRewards(uint128 shares, SwapData[] calldata _swapData) internal override returns(Reward[] memory rewards) {\r\n address[] memory rewardTokens = idleToken.getGovTokens();\r\n\r\n SwapData[] memory swapData = _swapData;\r\n if (swapData.length == 0) {\r\n // if no slippages provided we just loop over the rewards to save them\r\n swapData = new SwapData[](rewardTokens.length);\r\n } else {\r\n // init rewards array, to compound them\r\n rewards = new Reward[](rewardTokens.length);\r\n }\r\n\r\n uint256[] memory newRewardTokenAmounts = _claimStrategyRewards(rewardTokens);\r\n\r\n Strategy storage strategy = strategies[self];\r\n for (uint256 i = 0; i < rewardTokens.length; i++) {\r\n if (swapData[i].slippage > 0) {\r\n uint256 rewardTokenAmount = newRewardTokenAmounts[i] + strategy.pendingRewards[rewardTokens[i]];\r\n if (rewardTokenAmount > 0) {\r\n uint256 claimedAmount = _getRewardClaimAmount(shares, rewardTokenAmount);\r\n\r\n if (rewardTokenAmount > claimedAmount) {\r\n // if we don't swap all the tokens (fast withdraw), save the rest\r\n uint256 rewardAmountLeft = rewardTokenAmount - claimedAmount;\r\n strategy.pendingRewards[rewardTokens[i]] = rewardAmountLeft;\r\n } else if (rewardTokenAmount > newRewardTokenAmounts[i]) {\r\n // if reward amount is more than new rewards, we reset pendng to 0, otherwise it was 0 already\r\n strategy.pendingRewards[rewardTokens[i]] = 0;\r\n }\r\n\r\n rewards[i] = Reward(claimedAmount, IERC20(rewardTokens[i]));\r\n }\r\n } else if (newRewardTokenAmounts[i] > 0) {\r\n strategy.pendingRewards[rewardTokens[i]] += newRewardTokenAmounts[i];\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Claim strategy rewards\r\n * @param rewardTokens Tokens to claim\r\n * @return Reward token amounts\r\n */\r\n function _claimStrategyRewards(address[] memory rewardTokens) private returns(uint256[] memory) {\r\n uint256[] memory rewardTokenAmountsBefore = _getRewardTokenAmounts(rewardTokens);\r\n \r\n // claim\r\n idleToken.redeemIdleToken(0);\r\n\r\n uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length);\r\n\r\n // calculate reward token amounts\r\n for (uint256 i = 0; i < rewardTokenAmountsBefore.length; i++) {\r\n rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this)) - rewardTokenAmountsBefore[i];\r\n }\r\n\r\n return rewardTokenAmounts;\r\n }\r\n\r\n /**\r\n * @notice Get reward token amounts\r\n * @param rewardTokens Reward token address array\r\n * @return Reward token amounts\r\n */\r\n function _getRewardTokenAmounts(address[] memory rewardTokens) private view returns(uint256[] memory) {\r\n uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length);\r\n\r\n for (uint256 i = 0; i < rewardTokenAmounts.length; i++) {\r\n rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this));\r\n }\r\n\r\n return rewardTokenAmounts;\r\n }\r\n}\r\n" } } }