zellic-audit
Initial commit
f998fcd
raw
history blame
86 kB
{
"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": {
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"contracts/Config.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ncontract Config {\n // function signature of \"postProcess()\"\n bytes4 public constant POSTPROCESS_SIG = 0xc2722916;\n\n // The base amount of percentage function\n uint256 public constant PERCENTAGE_BASE = 1 ether;\n\n // Handler post-process type. Others should not happen now.\n enum HandlerType {\n Token,\n Custom,\n Others\n }\n}\n"
},
"contracts/Storage.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./lib/LibCache.sol\";\nimport \"./lib/LibStack.sol\";\n\n/// @notice A cache structure composed by a bytes32 array\ncontract Storage {\n using LibCache for mapping(bytes32 => bytes32);\n using LibStack for bytes32[];\n\n bytes32[] public stack;\n mapping(bytes32 => bytes32) public cache;\n\n // keccak256 hash of \"msg.sender\"\n // prettier-ignore\n bytes32 public constant MSG_SENDER_KEY = 0xb2f2618cecbbb6e7468cc0f2aa43858ad8d153e0280b22285e28e853bb9d453a;\n\n modifier isStackEmpty() {\n require(stack.length == 0, \"Stack not empty\");\n _;\n }\n\n modifier isInitialized() {\n require(_getSender() != address(0), \"Sender is not initialized\");\n _;\n }\n\n modifier isNotInitialized() {\n require(_getSender() == address(0), \"Sender is initialized\");\n _;\n }\n\n function _setSender() internal isNotInitialized {\n cache.setAddress(MSG_SENDER_KEY, msg.sender);\n }\n\n function _resetSender() internal {\n cache.setAddress(MSG_SENDER_KEY, address(0));\n }\n\n function _getSender() internal view returns (address) {\n return cache.getAddress(MSG_SENDER_KEY);\n }\n}\n"
},
"contracts/handlers/HandlerBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../interface/IERC20Usdt.sol\";\n\nimport \"../Config.sol\";\nimport \"../Storage.sol\";\n\nabstract contract HandlerBase is Storage, Config {\n using SafeERC20 for IERC20;\n using LibStack for bytes32[];\n\n address public constant NATIVE_TOKEN_ADDRESS =\n 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n\n function postProcess() external payable virtual {\n revert(\"Invalid post process\");\n /* Implementation template\n bytes4 sig = stack.getSig();\n if (sig == bytes4(keccak256(bytes(\"handlerFunction_1()\")))) {\n // Do something\n } else if (sig == bytes4(keccak256(bytes(\"handlerFunction_2()\")))) {\n bytes32 temp = stack.get();\n // Do something\n } else revert(\"Invalid post process\");\n */\n }\n\n function _updateToken(address token) internal {\n stack.setAddress(token);\n // Ignore token type to fit old handlers\n // stack.setHandlerType(uint256(HandlerType.Token));\n }\n\n function _updatePostProcess(bytes32[] memory params) internal {\n for (uint256 i = params.length; i > 0; i--) {\n stack.set(params[i - 1]);\n }\n stack.set(msg.sig);\n stack.setHandlerType(HandlerType.Custom);\n }\n\n function getContractName() public pure virtual returns (string memory);\n\n function _revertMsg(\n string memory functionName,\n string memory reason\n ) internal pure {\n revert(\n string(\n abi.encodePacked(\n getContractName(),\n \"_\",\n functionName,\n \": \",\n reason\n )\n )\n );\n }\n\n function _revertMsg(string memory functionName) internal pure {\n _revertMsg(functionName, \"Unspecified\");\n }\n\n function _requireMsg(\n bool condition,\n string memory functionName,\n string memory reason\n ) internal pure {\n if (!condition) _revertMsg(functionName, reason);\n }\n\n function _uint2String(uint256 n) internal pure returns (string memory) {\n if (n == 0) {\n return \"0\";\n } else {\n uint256 len = 0;\n for (uint256 temp = n; temp > 0; temp /= 10) {\n len++;\n }\n bytes memory str = new bytes(len);\n for (uint256 i = len; i > 0; i--) {\n str[i - 1] = bytes1(uint8(48 + (n % 10)));\n n /= 10;\n }\n return string(str);\n }\n }\n\n function _getBalance(\n address token,\n uint256 amount\n ) internal view returns (uint256) {\n if (amount != type(uint256).max) {\n return amount;\n }\n\n // ETH case\n if (token == address(0) || token == NATIVE_TOKEN_ADDRESS) {\n return address(this).balance;\n }\n // ERC20 token case\n return IERC20(token).balanceOf(address(this));\n }\n\n function _tokenApprove(\n address token,\n address spender,\n uint256 amount\n ) internal {\n try IERC20Usdt(token).approve(spender, amount) {} catch {\n IERC20(token).safeApprove(spender, 0);\n IERC20(token).safeApprove(spender, amount);\n }\n }\n\n function _tokenApproveZero(address token, address spender) internal {\n if (IERC20Usdt(token).allowance(address(this), spender) > 0) {\n try IERC20Usdt(token).approve(spender, 0) {} catch {\n IERC20Usdt(token).approve(spender, 1);\n }\n }\n }\n\n function _isNotNativeToken(address token) internal pure returns (bool) {\n return (token != address(0) && token != NATIVE_TOKEN_ADDRESS);\n }\n}\n"
},
"contracts/handlers/aaveV3/HAaveProtocolV3.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"../../interface/IProxy.sol\";\nimport \"../HandlerBase.sol\";\nimport \"../wrappednativetoken/IWrappedNativeToken.sol\";\nimport \"./IPool.sol\";\nimport \"./IFlashLoanReceiver.sol\";\n\ncontract HAaveProtocolV3 is HandlerBase, IFlashLoanReceiver {\n // prettier-ignore\n uint16 public constant REFERRAL_CODE = 56;\n\n address public immutable wrappedNativeToken;\n address public immutable provider;\n\n constructor(address wrappedNativeToken_, address provider_) {\n wrappedNativeToken = wrappedNativeToken_;\n provider = provider_;\n }\n\n function getContractName() public pure override returns (string memory) {\n return \"HAaveProtocolV3\";\n }\n\n function supply(address asset, uint256 amount) external payable {\n amount = _getBalance(asset, amount);\n _supply(asset, amount);\n }\n\n function supplyETH(uint256 amount) external payable {\n amount = _getBalance(NATIVE_TOKEN_ADDRESS, amount);\n IWrappedNativeToken(wrappedNativeToken).deposit{value: amount}();\n\n _supply(wrappedNativeToken, amount);\n\n _updateToken(wrappedNativeToken);\n }\n\n function withdraw(\n address asset,\n uint256 amount\n ) external payable returns (uint256 withdrawAmount) {\n withdrawAmount = _withdraw(asset, amount);\n\n _updateToken(asset);\n }\n\n function withdrawETH(\n uint256 amount\n ) external payable returns (uint256 withdrawAmount) {\n withdrawAmount = _withdraw(wrappedNativeToken, amount);\n\n IWrappedNativeToken(wrappedNativeToken).withdraw(withdrawAmount);\n }\n\n function borrow(\n address asset,\n uint256 amount,\n uint256 rateMode\n ) external payable {\n address onBehalfOf = _getSender();\n _borrow(asset, amount, rateMode, onBehalfOf);\n _updateToken(asset);\n }\n\n function borrowETH(uint256 amount, uint256 rateMode) external payable {\n address onBehalfOf = _getSender();\n _borrow(wrappedNativeToken, amount, rateMode, onBehalfOf);\n\n IWrappedNativeToken(wrappedNativeToken).withdraw(amount);\n }\n\n function repay(\n address asset,\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) external payable returns (uint256 remainDebt) {\n remainDebt = _repay(asset, amount, rateMode, onBehalfOf);\n }\n\n function repayETH(\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) external payable returns (uint256 remainDebt) {\n IWrappedNativeToken(wrappedNativeToken).deposit{value: amount}();\n\n remainDebt = _repay(wrappedNativeToken, amount, rateMode, onBehalfOf);\n\n _updateToken(wrappedNativeToken);\n }\n\n function flashLoan(\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata modes,\n bytes calldata params\n ) external payable {\n _requireMsg(\n assets.length == amounts.length,\n \"flashLoan\",\n \"assets and amounts do not match\"\n );\n\n _requireMsg(\n assets.length == modes.length,\n \"flashLoan\",\n \"assets and modes do not match\"\n );\n\n address onBehalfOf = _getSender();\n address pool = IPoolAddressesProvider(provider).getPool();\n\n try\n IPool(pool).flashLoan(\n address(this),\n assets,\n amounts,\n modes,\n onBehalfOf,\n params,\n REFERRAL_CODE\n )\n {} catch Error(string memory reason) {\n _revertMsg(\"flashLoan\", reason);\n } catch {\n _revertMsg(\"flashLoan\");\n }\n\n // approve pool zero\n for (uint256 i = 0; i < assets.length; i++) {\n _tokenApproveZero(assets[i], pool);\n if (modes[i] != 0) _updateToken(assets[i]);\n }\n }\n\n function executeOperation(\n address[] memory assets,\n uint256[] memory amounts,\n uint256[] memory premiums,\n address initiator,\n bytes memory params\n ) external override returns (bool) {\n _requireMsg(\n msg.sender == IPoolAddressesProvider(provider).getPool(),\n \"executeOperation\",\n \"invalid caller\"\n );\n\n _requireMsg(\n initiator == address(this),\n \"executeOperation\",\n \"not initiated by the proxy\"\n );\n\n (\n address[] memory tos,\n bytes32[] memory configs,\n bytes[] memory datas\n ) = abi.decode(params, (address[], bytes32[], bytes[]));\n IProxy(address(this)).execs(tos, configs, datas);\n\n address pool = IPoolAddressesProvider(provider).getPool();\n for (uint256 i = 0; i < assets.length; i++) {\n uint256 amountOwing = amounts[i] + premiums[i];\n _tokenApprove(assets[i], pool, amountOwing);\n }\n return true;\n }\n\n /* ========== INTERNAL FUNCTIONS ========== */\n\n function _supply(address asset, uint256 amount) internal {\n (address pool, address aToken) = _getPoolAndAToken(asset);\n _tokenApprove(asset, pool, amount);\n try\n IPool(pool).supply(asset, amount, address(this), REFERRAL_CODE)\n {} catch Error(string memory reason) {\n _revertMsg(\"supply\", reason);\n } catch {\n _revertMsg(\"supply\");\n }\n _tokenApproveZero(asset, pool);\n _updateToken(aToken);\n }\n\n function _withdraw(\n address asset,\n uint256 amount\n ) internal returns (uint256 withdrawAmount) {\n (address pool, address aToken) = _getPoolAndAToken(asset);\n amount = _getBalance(aToken, amount);\n\n try IPool(pool).withdraw(asset, amount, address(this)) returns (\n uint256 ret\n ) {\n withdrawAmount = ret;\n } catch Error(string memory reason) {\n _revertMsg(\"withdraw\", reason);\n } catch {\n _revertMsg(\"withdraw\");\n }\n }\n\n function _borrow(\n address asset,\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) internal {\n address pool = IPoolAddressesProvider(provider).getPool();\n\n try\n IPool(pool).borrow(\n asset,\n amount,\n rateMode,\n REFERRAL_CODE,\n onBehalfOf\n )\n {} catch Error(string memory reason) {\n _revertMsg(\"borrow\", reason);\n } catch {\n _revertMsg(\"borrow\");\n }\n }\n\n function _repay(\n address asset,\n uint256 amount,\n uint256 rateMode,\n address onBehalfOf\n ) internal returns (uint256 remainDebt) {\n address pool = IPoolAddressesProvider(provider).getPool();\n _tokenApprove(asset, pool, amount);\n\n try\n IPool(pool).repay(asset, amount, rateMode, onBehalfOf)\n {} catch Error(string memory reason) {\n _revertMsg(\"repay\", reason);\n } catch {\n _revertMsg(\"repay\");\n }\n\n _tokenApproveZero(asset, pool);\n\n DataTypes.ReserveData memory reserve = IPool(pool).getReserveData(\n asset\n );\n remainDebt = DataTypes.InterestRateMode(rateMode) ==\n DataTypes.InterestRateMode.STABLE\n ? IERC20(reserve.stableDebtTokenAddress).balanceOf(onBehalfOf)\n : IERC20(reserve.variableDebtTokenAddress).balanceOf(onBehalfOf);\n }\n\n function _getPoolAndAToken(\n address underlying\n ) internal view returns (address pool, address aToken) {\n pool = IPoolAddressesProvider(provider).getPool();\n try IPool(pool).getReserveData(underlying) returns (\n DataTypes.ReserveData memory data\n ) {\n aToken = data.aTokenAddress;\n _requireMsg(\n aToken != address(0),\n \"General\",\n \"aToken should not be zero address\"\n );\n } catch Error(string memory reason) {\n _revertMsg(\"General\", reason);\n } catch {\n _revertMsg(\"General\");\n }\n }\n}\n"
},
"contracts/handlers/aaveV3/IFlashLoanReceiver.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IFlashLoanReceiver\n * @author Aave\n * @notice Defines the basic interface of a flashloan-receiver contract.\n * @dev Implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n **/\ninterface IFlashLoanReceiver {\n /**\n * @notice Executes an operation after receiving the flash-borrowed assets\n * @dev Ensure that the contract can return the debt + premium, e.g., has\n * enough funds to repay and has approved the Pool to pull the total amount\n * @param assets The addresses of the flash-borrowed assets\n * @param amounts The amounts of the flash-borrowed assets\n * @param premiums The fee of each flash-borrowed asset\n * @param initiator The address of the flashloan initiator\n * @param params The byte-encoded params passed when initiating the flashloan\n * @return True if the execution of the operation succeeds, false otherwise\n */\n function executeOperation(\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata premiums,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n}"
},
"contracts/handlers/aaveV3/IPool.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"./libraries/DataTypes.sol\";\n\n/**\n * @title IPool\n * @author Aave\n * @notice Defines the basic interface for an Aave Pool.\n **/\ninterface IPool {\n /**\n * @dev Emitted on mintUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens\n * @param amount The amount of supplied assets\n * @param referralCode The referral code used\n **/\n event MintUnbacked(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on backUnbacked()\n * @param reserve The address of the underlying asset of the reserve\n * @param backer The address paying for the backing\n * @param amount The amount added as backing\n * @param fee The amount paid in fees\n **/\n event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);\n\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the aTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n **/\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of aTokens\n * @param to The address that will receive the underlying\n * @param amount The amount to be withdrawn\n **/\n event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n **/\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly\n **/\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool useATokens\n );\n\n /**\n * @dev Emitted on swapBorrowRateMode()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user swapping his rate mode\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n **/\n event SwapBorrowRateMode(\n address indexed reserve,\n address indexed user,\n DataTypes.InterestRateMode interestRateMode\n );\n\n /**\n * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets\n * @param asset The address of the underlying asset of the reserve\n * @param totalDebt The total isolation mode debt for the reserve\n */\n event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);\n\n /**\n * @dev Emitted when the user selects a certain asset category for eMode\n * @param user The address of the user\n * @param categoryId The category id\n **/\n event UserEModeSet(address indexed user, uint8 categoryId);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);\n\n /**\n * @dev Emitted on setUserUseReserveAsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);\n\n /**\n * @dev Emitted on rebalanceStableBorrowRate()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user for which the rebalance has been executed\n **/\n event RebalanceStableBorrowRate(address indexed reserve, address indexed user);\n\n /**\n * @dev Emitted on flashLoan()\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash loan\n * @param asset The address of the asset being flash borrowed\n * @param amount The amount flash borrowed\n * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt\n * @param premium The fee flash borrowed\n * @param referralCode The referral code used\n **/\n event FlashLoan(\n address indexed target,\n address initiator,\n address indexed asset,\n uint256 amount,\n DataTypes.InterestRateMode interestRateMode,\n uint256 premium,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n event LiquidationCall(\n address indexed collateralAsset,\n address indexed debtAsset,\n address indexed user,\n uint256 debtToCover,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receiveAToken\n );\n\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param stableBorrowRate The next stable borrow rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 stableBorrowRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.\n * @param reserve The address of the reserve\n * @param amountMinted The amount minted to the treasury\n **/\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @dev Mints an `amount` of aTokens to the `onBehalfOf`\n * @param asset The address of the underlying asset to mint\n * @param amount The amount to mint\n * @param onBehalfOf The address that will receive the aTokens\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function mintUnbacked(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Back the current unbacked underlying with `amount` and pay `fee`.\n * @param asset The address of the underlying asset to back\n * @param amount The amount to back\n * @param fee The amount paid in fees\n **/\n function backUnbacked(\n address asset,\n uint256 amount,\n uint256 fee\n ) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n **/\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned\n * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole aToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdraw(\n address asset,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (StableDebtToken or VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens, depending on the `interestRateMode`\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n **/\n function borrow(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n **/\n function repay(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n **/\n function repayWithPermit(\n address asset,\n uint256 amount,\n uint256 interestRateMode,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable\n * @return The final amount repaid\n **/\n function repayWithATokens(\n address asset,\n uint256 amount,\n uint256 interestRateMode\n ) external returns (uint256);\n\n /**\n * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa\n * @param asset The address of the underlying asset borrowed\n * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable\n **/\n function swapBorrowRateMode(address asset, uint256 interestRateMode) external;\n\n /**\n * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.\n * - Users can be rebalanced if the following conditions are satisfied:\n * 1. Usage ratio is above 95%\n * 2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too\n * much has been borrowed at a stable rate and suppliers are not earning enough\n * @param asset The address of the underlying asset borrowed\n * @param user The address of the user to be rebalanced\n **/\n function rebalanceStableBorrowRate(address asset, address user) external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n **/\n function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n function liquidationCall(\n address collateralAsset,\n address debtAsset,\n address user,\n uint256 debtToCover,\n bool receiveAToken\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://developers.aave.com\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts of the assets being flash-borrowed\n * @param interestRateModes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata interestRateModes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept\n * into consideration. For further details please visit https://developers.aave.com\n * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface\n * @param asset The address of the asset being flash-borrowed\n * @param amount The amount of the asset being flash-borrowed\n * @param params Variadic packed params to pass to the receiver as extra information\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function flashLoanSimple(\n address receiverAddress,\n address asset,\n uint256 amount,\n bytes calldata params,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n **/\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param aTokenAddress The address of the aToken that will be assigned to the reserve\n * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n **/\n function initReserve(\n address asset,\n address aTokenAddress,\n address stableDebtAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n **/\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n **/\n function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)\n external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n **/\n function setConfiguration(address asset, DataTypes.ReserveConfigurationMap calldata configuration)\n external;\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n **/\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset) external view returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n **/\n function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an aToken transfer\n * @dev Only callable by the overlying aToken of the `asset`\n * @param asset The address of the underlying asset of the aToken\n * @param from The user from which the aTokens are transferred\n * @param to The user receiving the aTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The aToken balance of the `from` user before the transfer\n * @param balanceToBefore The aToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n **/\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n **/\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n **/\n function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);\n\n /**\n * @notice Updates the protocol fee on the bridging\n * @param bridgeProtocolFee The part of the premium sent to the protocol treasury\n */\n function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;\n\n /**\n * @notice Updates flash loan premiums. Flash loan premium consists of two parts:\n * - A part is sent to aToken holders as extra, one time accumulated interest\n * - A part is collected by the protocol treasury\n * @dev The total premium is calculated on the total borrowed amount\n * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`\n * @dev Only callable by the PoolConfigurator contract\n * @param flashLoanPremiumTotal The total premium, expressed in bps\n * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps\n */\n function updateFlashloanPremiums(\n uint128 flashLoanPremiumTotal,\n uint128 flashLoanPremiumToProtocol\n ) external;\n\n /**\n * @notice Configures a new category for the eMode.\n * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.\n * The category 0 is reserved as it's the default for volatile assets\n * @param id The id of the category\n * @param config The configuration of the category\n */\n function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory config) external;\n\n /**\n * @notice Returns the data of an eMode category\n * @param id The id of the category\n * @return The configuration data of the category\n */\n function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);\n\n /**\n * @notice Allows a user to use the protocol in eMode\n * @param categoryId The id of the category\n */\n function setUserEMode(uint8 categoryId) external;\n\n /**\n * @notice Returns the eMode the user is using\n * @param user The address of the user\n * @return The eMode id\n */\n function getUserEMode(address user) external view returns (uint256);\n\n /**\n * @notice Resets the isolation mode total debt of the given asset to zero\n * @dev It requires the given asset has zero debt ceiling\n * @param asset The address of the underlying asset to reset the isolationModeTotalDebt\n */\n function resetIsolationModeTotalDebt(address asset) external;\n\n /**\n * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate\n * @return The percentage of available liquidity to borrow, expressed in bps\n */\n function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);\n\n /**\n * @notice Returns the total fee on flash loans\n * @return The total fee on flashloans\n */\n function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);\n\n /**\n * @notice Returns the part of the bridge fees sent to protocol\n * @return The bridge fee sent to the protocol treasury\n */\n function BRIDGE_PROTOCOL_FEE() external view returns (uint256);\n\n /**\n * @notice Returns the part of the flashloan fees sent to protocol\n * @return The flashloan fee sent to the protocol treasury\n */\n function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens\n * @param assets The list of reserves for which the minting needs to be executed\n **/\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(\n address token,\n address to,\n uint256 amount\n ) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 aUSDC\n * @dev Deprecated: Use the `supply` function instead\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function deposit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}"
},
"contracts/handlers/aaveV3/IPoolAddressesProvider.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.0;\n\n/**\n * @title IPoolAddressesProvider\n * @author Aave\n * @notice Defines the basic interface for a Pool Addresses Provider.\n **/\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param oldAddress The old address of the Pool\n * @param newAddress The new address of the Pool\n */\n event PoolUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @notice Returns the id of the Aave market to which this contract points to.\n * @return The market id\n **/\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple Aave markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n **/\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param newPoolImpl The new Pool implementation\n **/\n function setPoolImpl(address newPoolImpl) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n **/\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n **/\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n **/\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n **/\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n **/\n function setPoolDataProvider(address newDataProvider) external;\n}"
},
"contracts/handlers/aaveV3/libraries/DataTypes.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nlibrary DataTypes {\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //the current stable borrow rate. Expressed in ray\n uint128 currentStableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //aToken address\n address aTokenAddress;\n //stableDebtToken address\n address stableDebtTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n //the outstanding unbacked aTokens minted through the bridging feature\n uint128 unbacked;\n //the outstanding debt borrowed against this asset in isolation mode\n uint128 isolationModeTotalDebt;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62-63: reserved\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n }\n\n struct EModeCategory {\n // each eMode category has a custom ltv and liquidation threshold\n uint16 ltv;\n uint16 liquidationThreshold;\n uint16 liquidationBonus;\n // each eMode category may or may not have a custom oracle to override the individual assets price oracles\n address priceSource;\n string label;\n }\n\n enum InterestRateMode {\n NONE,\n STABLE,\n VARIABLE\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currPrincipalStableDebt;\n uint256 currAvgStableBorrowRate;\n uint256 currTotalStableDebt;\n uint256 nextAvgStableBorrowRate;\n uint256 nextTotalStableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address aTokenAddress;\n address stableDebtTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n uint40 stableDebtLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidationCallParams {\n uint256 reservesCount;\n uint256 debtToCover;\n address collateralAsset;\n address debtAsset;\n address user;\n bool receiveAToken;\n address priceOracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n InterestRateMode interestRateMode;\n address onBehalfOf;\n bool useATokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ExecuteSetUserEModeParams {\n uint256 reservesCount;\n address oracle;\n uint8 categoryId;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n uint8 fromEModeCategory;\n }\n\n struct FlashloanParams {\n address receiverAddress;\n address[] assets;\n uint256[] amounts;\n uint256[] interestRateModes;\n address onBehalfOf;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n uint256 maxStableRateBorrowSizePercent;\n uint256 reservesCount;\n address addressesProvider;\n uint8 userEModeCategory;\n bool isAuthorizedFlashBorrower;\n }\n\n struct FlashloanSimpleParams {\n address receiverAddress;\n address asset;\n uint256 amount;\n bytes params;\n uint16 referralCode;\n uint256 flashLoanPremiumToProtocol;\n uint256 flashLoanPremiumTotal;\n }\n\n struct FlashLoanRepaymentParams {\n uint256 amount;\n uint256 totalPremium;\n uint256 flashLoanPremiumToProtocol;\n address asset;\n address receiverAddress;\n uint16 referralCode;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n uint8 userEModeCategory;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n InterestRateMode interestRateMode;\n uint256 maxStableLoanPercent;\n uint256 reservesCount;\n address oracle;\n uint8 userEModeCategory;\n address priceOracleSentinel;\n bool isolationModeActive;\n address isolationModeCollateralAddress;\n uint256 isolationModeDebtCeiling;\n }\n\n struct ValidateLiquidationCallParams {\n ReserveCache debtReserveCache;\n uint256 totalDebt;\n uint256 healthFactor;\n address priceOracleSentinel;\n }\n\n struct CalculateInterestRatesParams {\n uint256 unbacked;\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalStableDebt;\n uint256 totalVariableDebt;\n uint256 averageStableBorrowRate;\n uint256 reserveFactor;\n address reserve;\n address aToken;\n }\n\n struct InitReserveParams {\n address asset;\n address aTokenAddress;\n address stableDebtAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n}\n"
},
"contracts/handlers/wrappednativetoken/IWrappedNativeToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IWrappedNativeToken {\n function deposit() external payable;\n function withdraw(uint256 wad) external;\n}\n"
},
"contracts/interface/IERC20Usdt.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IERC20Usdt {\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function transfer(address recipient, uint256 amount) external;\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function approve(address spender, uint256 amount) external;\n\n function transferFrom(address sender, address recipient, uint256 amount) external;\n\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/interface/IProxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IProxy {\n function batchExec(address[] calldata tos, bytes32[] calldata configs, bytes[] memory datas, uint256[] calldata ruleIndexes) external payable;\n function execs(address[] calldata tos, bytes32[] calldata configs, bytes[] memory datas) external payable;\n}\n"
},
"contracts/lib/LibCache.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nlibrary LibCache {\n function set(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key,\n bytes32 _value\n ) internal {\n _cache[_key] = _value;\n }\n\n function setAddress(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key,\n address _value\n ) internal {\n _cache[_key] = bytes32(uint256(uint160(_value)));\n }\n\n function setUint256(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key,\n uint256 _value\n ) internal {\n _cache[_key] = bytes32(_value);\n }\n\n function getAddress(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key\n ) internal view returns (address ret) {\n ret = address(uint160(uint256(_cache[_key])));\n }\n\n function getUint256(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key\n ) internal view returns (uint256 ret) {\n ret = uint256(_cache[_key]);\n }\n\n function get(\n mapping(bytes32 => bytes32) storage _cache,\n bytes32 _key\n ) internal view returns (bytes32 ret) {\n ret = _cache[_key];\n }\n}\n"
},
"contracts/lib/LibStack.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../Config.sol\";\n\nlibrary LibStack {\n function setAddress(bytes32[] storage _stack, address _input) internal {\n _stack.push(bytes32(uint256(uint160(_input))));\n }\n\n function set(bytes32[] storage _stack, bytes32 _input) internal {\n _stack.push(_input);\n }\n\n function setHandlerType(\n bytes32[] storage _stack,\n Config.HandlerType _input\n ) internal {\n _stack.push(bytes12(uint96(_input)));\n }\n\n function getAddress(\n bytes32[] storage _stack\n ) internal returns (address ret) {\n ret = address(uint160(uint256(peek(_stack))));\n _stack.pop();\n }\n\n function getSig(bytes32[] storage _stack) internal returns (bytes4 ret) {\n ret = bytes4(peek(_stack));\n _stack.pop();\n }\n\n function get(bytes32[] storage _stack) internal returns (bytes32 ret) {\n ret = peek(_stack);\n _stack.pop();\n }\n\n function peek(\n bytes32[] storage _stack\n ) internal view returns (bytes32 ret) {\n uint256 length = _stack.length;\n require(length > 0, \"stack empty\");\n ret = _stack[length - 1];\n }\n\n function peek(\n bytes32[] storage _stack,\n uint256 _index\n ) internal view returns (bytes32 ret) {\n uint256 length = _stack.length;\n require(length > 0, \"stack empty\");\n require(length > _index, \"not enough elements in stack\");\n ret = _stack[length - _index - 1];\n }\n}\n"
}
}
}