{ "language": "Solidity", "settings": { "evmVersion": "istanbul", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "sources": { "@openzeppelin/contracts/math/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" }, "@openzeppelin/contracts/math/SignedSafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary SignedSafeMath {\n int256 constant private _INT256_MIN = -2**255;\n\n /**\n * @dev Returns the multiplication of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(int256 a, int256 b) internal pure returns (int256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n require(!(a == -1 && b == _INT256_MIN), \"SignedSafeMath: multiplication overflow\");\n\n int256 c = a * b;\n require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two signed integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"SignedSafeMath: division by zero\");\n require(!(b == -1 && a == _INT256_MIN), \"SignedSafeMath: division overflow\");\n\n int256 c = a / b;\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the addition of two signed integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n return c;\n }\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <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(address sender, address recipient, uint256 amount) 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/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"../../math/SafeMath.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 SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) 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(IERC20 token, address spender, uint256 value) 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 // solhint-disable-next-line max-line-length\n require((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(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\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) { // Return data is optional\n // solhint-disable-next-line max-line-length\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.6.2 <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 // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\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 // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\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(address target, bytes memory data, string memory errorMessage) 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(address target, bytes memory data, uint256 value) 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(address target, bytes memory data, uint256 value, string memory errorMessage) 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 // solhint-disable-next-line avoid-low-level-calls\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(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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 // solhint-disable-next-line no-inline-assembly\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" }, "@openzeppelin/contracts/utils/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor () internal {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n" }, "@openzeppelin/contracts/utils/SafeCast.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value < 2**128, \"SafeCast: value doesn\\'t fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value < 2**64, \"SafeCast: value doesn\\'t fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value < 2**32, \"SafeCast: value doesn\\'t fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value < 2**16, \"SafeCast: value doesn\\'t fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value < 2**8, \"SafeCast: value doesn\\'t fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= -2**127 && value < 2**127, \"SafeCast: value doesn\\'t fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= -2**63 && value < 2**63, \"SafeCast: value doesn\\'t fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= -2**31 && value < 2**31, \"SafeCast: value doesn\\'t fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= -2**15 && value < 2**15, \"SafeCast: value doesn\\'t fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= -2**7 && value < 2**7, \"SafeCast: value doesn\\'t fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n require(value < 2**255, \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n" }, "contracts/interfaces/IController.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\ninterface IController {\n function addSet(address _setToken) external;\n function feeRecipient() external view returns(address);\n function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);\n function isModule(address _module) external view returns(bool);\n function isSet(address _setToken) external view returns(bool);\n function isSystemContract(address _contractAddress) external view returns (bool);\n function resourceId(uint256 _id) external view returns(address);\n}" }, "contracts/interfaces/IIntegrationRegistry.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\ninterface IIntegrationRegistry {\n function addIntegration(address _module, string memory _id, address _wrapper) external;\n function getIntegrationAdapter(address _module, string memory _id) external view returns(address);\n function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);\n function isValidIntegration(address _module, string memory _id) external view returns(bool);\n}" }, "contracts/interfaces/IManagerIssuanceHook.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\nimport { ISetToken } from \"./ISetToken.sol\";\n\ninterface IManagerIssuanceHook {\n function invokePreIssueHook(ISetToken _setToken, uint256 _issueQuantity, address _sender, address _to) external;\n function invokePreRedeemHook(ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to) external;\n}" }, "contracts/interfaces/IModule.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\n\n/**\n * @title IModule\n * @author Set Protocol\n *\n * Interface for interacting with Modules.\n */\ninterface IModule {\n /**\n * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included\n * in case checks need to be made or state needs to be cleared.\n */\n function removeModule() external;\n}" }, "contracts/interfaces/IModuleIssuanceHook.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { ISetToken } from \"./ISetToken.sol\";\n\n\n/**\n * CHANGELOG:\n * - Added a module level issue hook that can be used to set state ahead of component level\n * issue hooks\n */\ninterface IModuleIssuanceHook {\n\n function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external;\n function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external;\n \n function componentIssueHook(\n ISetToken _setToken,\n uint256 _setTokenQuantity,\n IERC20 _component,\n bool _isEquity\n ) external;\n\n function componentRedeemHook(\n ISetToken _setToken,\n uint256 _setTokenQuantity,\n IERC20 _component,\n bool _isEquity\n ) external;\n}" }, "contracts/interfaces/IPriceOracle.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\n/**\n * @title IPriceOracle\n * @author Set Protocol\n *\n * Interface for interacting with PriceOracle\n */\ninterface IPriceOracle {\n\n /* ============ Functions ============ */\n\n function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);\n function masterQuoteAsset() external view returns (address);\n}" }, "contracts/interfaces/ISetToken.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\npragma experimental \"ABIEncoderV2\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @title ISetToken\n * @author Set Protocol\n *\n * Interface for operating with SetTokens.\n */\ninterface ISetToken is IERC20 {\n\n /* ============ Enums ============ */\n\n enum ModuleState {\n NONE,\n PENDING,\n INITIALIZED\n }\n\n /* ============ Structs ============ */\n /**\n * The base definition of a SetToken Position\n *\n * @param component Address of token in the Position\n * @param module If not in default state, the address of associated module\n * @param unit Each unit is the # of components per 10^18 of a SetToken\n * @param positionState Position ENUM. Default is 0; External is 1\n * @param data Arbitrary data\n */\n struct Position {\n address component;\n address module;\n int256 unit;\n uint8 positionState;\n bytes data;\n }\n\n /**\n * A struct that stores a component's cash position details and external positions\n * This data structure allows O(1) access to a component's cash position units and \n * virtual units.\n *\n * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency\n * updating all units at once via the position multiplier. Virtual units are achieved\n * by dividing a \"real\" value by the \"positionMultiplier\"\n * @param componentIndex \n * @param externalPositionModules List of external modules attached to each external position. Each module\n * maps to an external position\n * @param externalPositions Mapping of module => ExternalPosition struct for a given component\n */\n struct ComponentPosition {\n int256 virtualUnit;\n address[] externalPositionModules;\n mapping(address => ExternalPosition) externalPositions;\n }\n\n /**\n * A struct that stores a component's external position details including virtual unit and any\n * auxiliary data.\n *\n * @param virtualUnit Virtual value of a component's EXTERNAL position.\n * @param data Arbitrary data\n */\n struct ExternalPosition {\n int256 virtualUnit;\n bytes data;\n }\n\n\n /* ============ Functions ============ */\n \n function addComponent(address _component) external;\n function removeComponent(address _component) external;\n function editDefaultPositionUnit(address _component, int256 _realUnit) external;\n function addExternalPositionModule(address _component, address _positionModule) external;\n function removeExternalPositionModule(address _component, address _positionModule) external;\n function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;\n function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;\n\n function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);\n\n function editPositionMultiplier(int256 _newMultiplier) external;\n\n function mint(address _account, uint256 _quantity) external;\n function burn(address _account, uint256 _quantity) external;\n\n function lock() external;\n function unlock() external;\n\n function addModule(address _module) external;\n function removeModule(address _module) external;\n function initializeModule() external;\n\n function setManager(address _manager) external;\n\n function manager() external view returns (address);\n function moduleStates(address _module) external view returns (ModuleState);\n function getModules() external view returns (address[] memory);\n \n function getDefaultPositionRealUnit(address _component) external view returns(int256);\n function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);\n function getComponents() external view returns(address[] memory);\n function getExternalPositionModules(address _component) external view returns(address[] memory);\n function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);\n function isExternalPositionModule(address _component, address _module) external view returns(bool);\n function isComponent(address _component) external view returns(bool);\n \n function positionMultiplier() external view returns (int256);\n function getPositions() external view returns (Position[] memory);\n function getTotalComponentRealUnits(address _component) external view returns(int256);\n\n function isInitializedModule(address _module) external view returns(bool);\n function isPendingModule(address _module) external view returns(bool);\n function isLocked() external view returns (bool);\n}" }, "contracts/interfaces/ISetValuer.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\npragma solidity 0.6.10;\n\nimport { ISetToken } from \"../interfaces/ISetToken.sol\";\n\ninterface ISetValuer {\n function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);\n}" }, "contracts/lib/AddressArrayUtils.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n\n*/\n\npragma solidity 0.6.10;\n\n/**\n * @title AddressArrayUtils\n * @author Set Protocol\n *\n * Utility functions to handle Address Arrays\n *\n * CHANGELOG:\n * - 4/21/21: Added validatePairsWithArray methods\n */\nlibrary AddressArrayUtils {\n\n /**\n * Finds the index of the first occurrence of the given element.\n * @param A The input array to search\n * @param a The value to find\n * @return Returns (index and isIn) for the first occurrence starting from index 0\n */\n function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {\n uint256 length = A.length;\n for (uint256 i = 0; i < length; i++) {\n if (A[i] == a) {\n return (i, true);\n }\n }\n return (uint256(-1), false);\n }\n\n /**\n * Returns true if the value is present in the list. Uses indexOf internally.\n * @param A The input array to search\n * @param a The value to find\n * @return Returns isIn for the first occurrence starting from index 0\n */\n function contains(address[] memory A, address a) internal pure returns (bool) {\n (, bool isIn) = indexOf(A, a);\n return isIn;\n }\n\n /**\n * Returns true if there are 2 elements that are the same in an array\n * @param A The input array to search\n * @return Returns boolean for the first occurrence of a duplicate\n */\n function hasDuplicate(address[] memory A) internal pure returns(bool) {\n require(A.length > 0, \"A is empty\");\n\n for (uint256 i = 0; i < A.length - 1; i++) {\n address current = A[i];\n for (uint256 j = i + 1; j < A.length; j++) {\n if (current == A[j]) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * @param A The input array to search\n * @param a The address to remove\n * @return Returns the array with the object removed.\n */\n function remove(address[] memory A, address a)\n internal\n pure\n returns (address[] memory)\n {\n (uint256 index, bool isIn) = indexOf(A, a);\n if (!isIn) {\n revert(\"Address not in array.\");\n } else {\n (address[] memory _A,) = pop(A, index);\n return _A;\n }\n }\n\n /**\n * @param A The input array to search\n * @param a The address to remove\n */\n function removeStorage(address[] storage A, address a)\n internal\n {\n (uint256 index, bool isIn) = indexOf(A, a);\n if (!isIn) {\n revert(\"Address not in array.\");\n } else {\n uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here\n if (index != lastIndex) { A[index] = A[lastIndex]; }\n A.pop();\n }\n }\n\n /**\n * Removes specified index from array\n * @param A The input array to search\n * @param index The index to remove\n * @return Returns the new array and the removed entry\n */\n function pop(address[] memory A, uint256 index)\n internal\n pure\n returns (address[] memory, address)\n {\n uint256 length = A.length;\n require(index < A.length, \"Index must be < A length\");\n address[] memory newAddresses = new address[](length - 1);\n for (uint256 i = 0; i < index; i++) {\n newAddresses[i] = A[i];\n }\n for (uint256 j = index + 1; j < length; j++) {\n newAddresses[j - 1] = A[j];\n }\n return (newAddresses, A[index]);\n }\n\n /**\n * Returns the combination of the two arrays\n * @param A The first array\n * @param B The second array\n * @return Returns A extended by B\n */\n function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {\n uint256 aLength = A.length;\n uint256 bLength = B.length;\n address[] memory newAddresses = new address[](aLength + bLength);\n for (uint256 i = 0; i < aLength; i++) {\n newAddresses[i] = A[i];\n }\n for (uint256 j = 0; j < bLength; j++) {\n newAddresses[aLength + j] = B[j];\n }\n return newAddresses;\n }\n\n /**\n * Validate that address and uint array lengths match. Validate address array is not empty\n * and contains no duplicate elements.\n *\n * @param A Array of addresses\n * @param B Array of uint\n */\n function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {\n require(A.length == B.length, \"Array length mismatch\");\n _validateLengthAndUniqueness(A);\n }\n\n /**\n * Validate that address and bool array lengths match. Validate address array is not empty\n * and contains no duplicate elements.\n *\n * @param A Array of addresses\n * @param B Array of bool\n */\n function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {\n require(A.length == B.length, \"Array length mismatch\");\n _validateLengthAndUniqueness(A);\n }\n\n /**\n * Validate that address and string array lengths match. Validate address array is not empty\n * and contains no duplicate elements.\n *\n * @param A Array of addresses\n * @param B Array of strings\n */\n function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {\n require(A.length == B.length, \"Array length mismatch\");\n _validateLengthAndUniqueness(A);\n }\n\n /**\n * Validate that address array lengths match, and calling address array are not empty\n * and contain no duplicate elements.\n *\n * @param A Array of addresses\n * @param B Array of addresses\n */\n function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {\n require(A.length == B.length, \"Array length mismatch\");\n _validateLengthAndUniqueness(A);\n }\n\n /**\n * Validate that address and bytes array lengths match. Validate address array is not empty\n * and contains no duplicate elements.\n *\n * @param A Array of addresses\n * @param B Array of bytes\n */\n function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {\n require(A.length == B.length, \"Array length mismatch\");\n _validateLengthAndUniqueness(A);\n }\n\n /**\n * Validate address array is not empty and contains no duplicate elements.\n *\n * @param A Array of addresses\n */\n function _validateLengthAndUniqueness(address[] memory A) internal pure {\n require(A.length > 0, \"Array length must be > 0\");\n require(!hasDuplicate(A), \"Cannot duplicate addresses\");\n }\n}\n" }, "contracts/lib/ExplicitERC20.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\n/**\n * @title ExplicitERC20\n * @author Set Protocol\n *\n * Utility functions for ERC20 transfers that require the explicit amount to be transferred.\n */\nlibrary ExplicitERC20 {\n using SafeMath for uint256;\n\n /**\n * When given allowance, transfers a token from the \"_from\" to the \"_to\" of quantity \"_quantity\".\n * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)\n *\n * @param _token ERC20 token to approve\n * @param _from The account to transfer tokens from\n * @param _to The account to transfer tokens to\n * @param _quantity The quantity to transfer\n */\n function transferFrom(\n IERC20 _token,\n address _from,\n address _to,\n uint256 _quantity\n )\n internal\n {\n // Call specified ERC20 contract to transfer tokens (via proxy).\n if (_quantity > 0) {\n uint256 existingBalance = _token.balanceOf(_to);\n\n SafeERC20.safeTransferFrom(\n _token,\n _from,\n _to,\n _quantity\n );\n\n uint256 newBalance = _token.balanceOf(_to);\n\n // Verify transfer quantity is reflected in balance\n require(\n newBalance == existingBalance.add(_quantity),\n \"Invalid post transfer balance\"\n );\n }\n }\n}\n" }, "contracts/lib/PreciseUnitMath.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\npragma experimental ABIEncoderV2;\n\nimport { SafeCast } from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { SignedSafeMath } from \"@openzeppelin/contracts/math/SignedSafeMath.sol\";\n\n\n/**\n * @title PreciseUnitMath\n * @author Set Protocol\n *\n * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from\n * dYdX's BaseMath library.\n *\n * CHANGELOG:\n * - 9/21/20: Added safePower function\n * - 4/21/21: Added approximatelyEquals function\n * - 12/13/21: Added preciseDivCeil (int overloads) function\n * - 12/13/21: Added abs function\n */\nlibrary PreciseUnitMath {\n using SafeMath for uint256;\n using SignedSafeMath for int256;\n using SafeCast for int256;\n\n // The number One in precise units.\n uint256 constant internal PRECISE_UNIT = 10 ** 18;\n int256 constant internal PRECISE_UNIT_INT = 10 ** 18;\n\n // Max unsigned integer value\n uint256 constant internal MAX_UINT_256 = type(uint256).max;\n // Max and min signed integer value\n int256 constant internal MAX_INT_256 = type(int256).max;\n int256 constant internal MIN_INT_256 = type(int256).min;\n\n /**\n * @dev Getter function since constants can't be read directly from libraries.\n */\n function preciseUnit() internal pure returns (uint256) {\n return PRECISE_UNIT;\n }\n\n /**\n * @dev Getter function since constants can't be read directly from libraries.\n */\n function preciseUnitInt() internal pure returns (int256) {\n return PRECISE_UNIT_INT;\n }\n\n /**\n * @dev Getter function since constants can't be read directly from libraries.\n */\n function maxUint256() internal pure returns (uint256) {\n return MAX_UINT_256;\n }\n\n /**\n * @dev Getter function since constants can't be read directly from libraries.\n */\n function maxInt256() internal pure returns (int256) {\n return MAX_INT_256;\n }\n\n /**\n * @dev Getter function since constants can't be read directly from libraries.\n */\n function minInt256() internal pure returns (int256) {\n return MIN_INT_256;\n }\n\n /**\n * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand\n * of a number with 18 decimals precision.\n */\n function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a.mul(b).div(PRECISE_UNIT);\n }\n\n /**\n * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the\n * significand of a number with 18 decimals precision.\n */\n function preciseMul(int256 a, int256 b) internal pure returns (int256) {\n return a.mul(b).div(PRECISE_UNIT_INT);\n }\n\n /**\n * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand\n * of a number with 18 decimals precision.\n */\n function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);\n }\n\n /**\n * @dev Divides value a by value b (result is rounded down).\n */\n function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n return a.mul(PRECISE_UNIT).div(b);\n }\n\n\n /**\n * @dev Divides value a by value b (result is rounded towards 0).\n */\n function preciseDiv(int256 a, int256 b) internal pure returns (int256) {\n return a.mul(PRECISE_UNIT_INT).div(b);\n }\n\n /**\n * @dev Divides value a by value b (result is rounded up or away from 0).\n */\n function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0, \"Cant divide by 0\");\n\n return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;\n }\n\n /**\n * @dev Divides value a by value b (result is rounded up or away from 0). When `a` is 0, 0 is\n * returned. When `b` is 0, method reverts with divide-by-zero error.\n */\n function preciseDivCeil(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"Cant divide by 0\");\n \n a = a.mul(PRECISE_UNIT_INT);\n int256 c = a.div(b);\n\n if (a % b != 0) {\n // a ^ b == 0 case is covered by the previous if statement, hence it won't resolve to --c\n (a ^ b > 0) ? ++c : --c;\n }\n\n return c;\n }\n\n /**\n * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).\n */\n function divDown(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"Cant divide by 0\");\n require(a != MIN_INT_256 || b != -1, \"Invalid input\");\n\n int256 result = a.div(b);\n if (a ^ b < 0 && a % b != 0) {\n result -= 1;\n }\n\n return result;\n }\n\n /**\n * @dev Multiplies value a by value b where rounding is towards the lesser number.\n * (positive values are rounded towards zero and negative values are rounded away from 0).\n */\n function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {\n return divDown(a.mul(b), PRECISE_UNIT_INT);\n }\n\n /**\n * @dev Divides value a by value b where rounding is towards the lesser number.\n * (positive values are rounded towards zero and negative values are rounded away from 0).\n */\n function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {\n return divDown(a.mul(PRECISE_UNIT_INT), b);\n }\n\n /**\n * @dev Performs the power on a specified value, reverts on overflow.\n */\n function safePower(\n uint256 a,\n uint256 pow\n )\n internal\n pure\n returns (uint256)\n {\n require(a > 0, \"Value must be positive\");\n\n uint256 result = 1;\n for (uint256 i = 0; i < pow; i++){\n uint256 previousResult = result;\n\n // Using safemath multiplication prevents overflows\n result = previousResult.mul(a);\n }\n\n return result;\n }\n\n /**\n * @dev Returns true if a =~ b within range, false otherwise.\n */\n function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) {\n return a <= b.add(range) && a >= b.sub(range);\n }\n\n /**\n * Returns the absolute value of int256 `a` as a uint256\n */\n function abs(int256 a) internal pure returns (uint) {\n return a >= 0 ? a.toUint256() : a.mul(-1).toUint256();\n }\n\n /**\n * Returns the negation of a\n */\n function neg(int256 a) internal pure returns (int256) {\n require(a > MIN_INT_256, \"Inversion overflow\");\n return -a;\n }\n}\n" }, "contracts/protocol/lib/Invoke.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\nimport { ISetToken } from \"../../interfaces/ISetToken.sol\";\n\n\n/**\n * @title Invoke\n * @author Set Protocol\n *\n * A collection of common utility functions for interacting with the SetToken's invoke function\n */\nlibrary Invoke {\n using SafeMath for uint256;\n\n /* ============ Internal ============ */\n\n /**\n * Instructs the SetToken to set approvals of the ERC20 token to a spender.\n *\n * @param _setToken SetToken instance to invoke\n * @param _token ERC20 token to approve\n * @param _spender The account allowed to spend the SetToken's balance\n * @param _quantity The quantity of allowance to allow\n */\n function invokeApprove(\n ISetToken _setToken,\n address _token,\n address _spender,\n uint256 _quantity\n )\n internal\n {\n bytes memory callData = abi.encodeWithSignature(\"approve(address,uint256)\", _spender, _quantity);\n _setToken.invoke(_token, 0, callData);\n }\n\n /**\n * Instructs the SetToken to transfer the ERC20 token to a recipient.\n *\n * @param _setToken SetToken instance to invoke\n * @param _token ERC20 token to transfer\n * @param _to The recipient account\n * @param _quantity The quantity to transfer\n */\n function invokeTransfer(\n ISetToken _setToken,\n address _token,\n address _to,\n uint256 _quantity\n )\n internal\n {\n if (_quantity > 0) {\n bytes memory callData = abi.encodeWithSignature(\"transfer(address,uint256)\", _to, _quantity);\n _setToken.invoke(_token, 0, callData);\n }\n }\n\n /**\n * Instructs the SetToken to transfer the ERC20 token to a recipient.\n * The new SetToken balance must equal the existing balance less the quantity transferred\n *\n * @param _setToken SetToken instance to invoke\n * @param _token ERC20 token to transfer\n * @param _to The recipient account\n * @param _quantity The quantity to transfer\n */\n function strictInvokeTransfer(\n ISetToken _setToken,\n address _token,\n address _to,\n uint256 _quantity\n )\n internal\n {\n if (_quantity > 0) {\n // Retrieve current balance of token for the SetToken\n uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));\n\n Invoke.invokeTransfer(_setToken, _token, _to, _quantity);\n\n // Get new balance of transferred token for SetToken\n uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));\n\n // Verify only the transfer quantity is subtracted\n require(\n newBalance == existingBalance.sub(_quantity),\n \"Invalid post transfer balance\"\n );\n }\n }\n\n /**\n * Instructs the SetToken to unwrap the passed quantity of WETH\n *\n * @param _setToken SetToken instance to invoke\n * @param _weth WETH address\n * @param _quantity The quantity to unwrap\n */\n function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {\n bytes memory callData = abi.encodeWithSignature(\"withdraw(uint256)\", _quantity);\n _setToken.invoke(_weth, 0, callData);\n }\n\n /**\n * Instructs the SetToken to wrap the passed quantity of ETH\n *\n * @param _setToken SetToken instance to invoke\n * @param _weth WETH address\n * @param _quantity The quantity to unwrap\n */\n function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {\n bytes memory callData = abi.encodeWithSignature(\"deposit()\");\n _setToken.invoke(_weth, _quantity, callData);\n }\n}" }, "contracts/protocol/lib/IssuanceValidationUtils.sol": { "content": "/*\n Copyright 2021 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\n\nimport { ISetToken } from \"../../interfaces/ISetToken.sol\";\nimport { PreciseUnitMath } from \"../../lib/PreciseUnitMath.sol\";\n\n/**\n * @title IssuanceValidationUtils\n * @author Set Protocol\n *\n * A collection of utility functions to help during issuance/redemption of SetToken.\n */\nlibrary IssuanceValidationUtils {\n using SafeMath for uint256;\n using SafeCast for int256;\n using PreciseUnitMath for uint256;\n\n /**\n * Validates component transfer IN to SetToken during issuance/redemption. Reverts if Set is undercollateralized post transfer.\n * NOTE: Call this function immediately after transfer IN but before calling external hooks (if any).\n *\n * @param _setToken Instance of the SetToken being issued/redeemed\n * @param _component Address of component being transferred in/out\n * @param _initialSetSupply Initial SetToken supply before issuance/redemption\n * @param _componentQuantity Amount of component transferred into SetToken\n */\n function validateCollateralizationPostTransferInPreHook(\n ISetToken _setToken, \n address _component, \n uint256 _initialSetSupply,\n uint256 _componentQuantity\n )\n internal\n view\n {\n uint256 newComponentBalance = IERC20(_component).balanceOf(address(_setToken));\n\n uint256 defaultPositionUnit = _setToken.getDefaultPositionRealUnit(address(_component)).toUint256();\n \n require(\n // Use preciseMulCeil to increase the lower bound and maintain over-collateralization\n newComponentBalance >= _initialSetSupply.preciseMulCeil(defaultPositionUnit).add(_componentQuantity),\n \"Invalid transfer in. Results in undercollateralization\"\n );\n }\n\n /**\n * Validates component transfer OUT of SetToken during issuance/redemption. Reverts if Set is undercollateralized post transfer.\n *\n * @param _setToken Instance of the SetToken being issued/redeemed\n * @param _component Address of component being transferred in/out\n * @param _finalSetSupply Final SetToken supply after issuance/redemption\n */\n function validateCollateralizationPostTransferOut(\n ISetToken _setToken, \n address _component, \n uint256 _finalSetSupply\n )\n internal \n view \n {\n uint256 newComponentBalance = IERC20(_component).balanceOf(address(_setToken));\n\n uint256 defaultPositionUnit = _setToken.getDefaultPositionRealUnit(address(_component)).toUint256();\n\n require(\n // Use preciseMulCeil to increase lower bound and maintain over-collateralization\n newComponentBalance >= _finalSetSupply.preciseMulCeil(defaultPositionUnit),\n \"Invalid transfer out. Results in undercollateralization\"\n );\n }\n}" }, "contracts/protocol/lib/ModuleBase.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport { AddressArrayUtils } from \"../../lib/AddressArrayUtils.sol\";\nimport { ExplicitERC20 } from \"../../lib/ExplicitERC20.sol\";\nimport { IController } from \"../../interfaces/IController.sol\";\nimport { IModule } from \"../../interfaces/IModule.sol\";\nimport { ISetToken } from \"../../interfaces/ISetToken.sol\";\nimport { Invoke } from \"./Invoke.sol\";\nimport { Position } from \"./Position.sol\";\nimport { PreciseUnitMath } from \"../../lib/PreciseUnitMath.sol\";\nimport { ResourceIdentifier } from \"./ResourceIdentifier.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { SignedSafeMath } from \"@openzeppelin/contracts/math/SignedSafeMath.sol\";\n\n/**\n * @title ModuleBase\n * @author Set Protocol\n *\n * Abstract class that houses common Module-related state and functions.\n *\n * CHANGELOG:\n * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size\n *\n */\nabstract contract ModuleBase is IModule {\n using AddressArrayUtils for address[];\n using Invoke for ISetToken;\n using Position for ISetToken;\n using PreciseUnitMath for uint256;\n using ResourceIdentifier for IController;\n using SafeCast for int256;\n using SafeCast for uint256;\n using SafeMath for uint256;\n using SignedSafeMath for int256;\n\n /* ============ State Variables ============ */\n\n // Address of the controller\n IController public controller;\n\n /* ============ Modifiers ============ */\n\n modifier onlyManagerAndValidSet(ISetToken _setToken) {\n _validateOnlyManagerAndValidSet(_setToken);\n _;\n }\n\n modifier onlySetManager(ISetToken _setToken, address _caller) {\n _validateOnlySetManager(_setToken, _caller);\n _;\n }\n\n modifier onlyValidAndInitializedSet(ISetToken _setToken) {\n _validateOnlyValidAndInitializedSet(_setToken);\n _;\n }\n\n /**\n * Throws if the sender is not a SetToken's module or module not enabled\n */\n modifier onlyModule(ISetToken _setToken) {\n _validateOnlyModule(_setToken);\n _;\n }\n\n /**\n * Utilized during module initializations to check that the module is in pending state\n * and that the SetToken is valid\n */\n modifier onlyValidAndPendingSet(ISetToken _setToken) {\n _validateOnlyValidAndPendingSet(_setToken);\n _;\n }\n\n /* ============ Constructor ============ */\n\n /**\n * Set state variables and map asset pairs to their oracles\n *\n * @param _controller Address of controller contract\n */\n constructor(IController _controller) public {\n controller = _controller;\n }\n\n /* ============ Internal Functions ============ */\n\n /**\n * Transfers tokens from an address (that has set allowance on the module).\n *\n * @param _token The address of the ERC20 token\n * @param _from The address to transfer from\n * @param _to The address to transfer to\n * @param _quantity The number of tokens to transfer\n */\n function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {\n ExplicitERC20.transferFrom(_token, _from, _to, _quantity);\n }\n\n /**\n * Gets the integration for the module with the passed in name. Validates that the address is not empty\n */\n function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { \n bytes32 integrationHash = getNameHash(_integrationName);\n return getAndValidateAdapterWithHash(integrationHash);\n }\n\n /**\n * Gets the integration for the module with the passed in hash. Validates that the address is not empty\n */\n function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { \n address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(\n address(this),\n _integrationHash\n );\n\n require(adapter != address(0), \"Must be valid adapter\"); \n return adapter;\n }\n\n /**\n * Gets the total fee for this module of the passed in index (fee % * quantity)\n */\n function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {\n uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);\n return _quantity.preciseMul(feePercentage);\n }\n\n /**\n * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient\n */\n function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {\n if (_feeQuantity > 0) {\n _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); \n }\n }\n\n /**\n * Returns true if the module is in process of initialization on the SetToken\n */\n function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {\n return _setToken.isPendingModule(address(this));\n }\n\n /**\n * Returns true if the address is the SetToken's manager\n */\n function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {\n return _setToken.manager() == _toCheck;\n }\n\n /**\n * Returns true if SetToken must be enabled on the controller \n * and module is registered on the SetToken\n */\n function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {\n return controller.isSet(address(_setToken)) &&\n _setToken.isInitializedModule(address(this));\n }\n\n /**\n * Hashes the string and returns a bytes32 value\n */\n function getNameHash(string memory _name) internal pure returns(bytes32) {\n return keccak256(bytes(_name));\n }\n\n /* ============== Modifier Helpers ===============\n * Internal functions used to reduce bytecode size\n */\n\n /**\n * Caller must SetToken manager and SetToken must be valid and initialized\n */\n function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view {\n require(isSetManager(_setToken, msg.sender), \"Must be the SetToken manager\");\n require(isSetValidAndInitialized(_setToken), \"Must be a valid and initialized SetToken\");\n }\n\n /**\n * Caller must SetToken manager\n */\n function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view {\n require(isSetManager(_setToken, _caller), \"Must be the SetToken manager\");\n }\n\n /**\n * SetToken must be valid and initialized\n */\n function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view {\n require(isSetValidAndInitialized(_setToken), \"Must be a valid and initialized SetToken\");\n }\n\n /**\n * Caller must be initialized module and module must be enabled on the controller\n */\n function _validateOnlyModule(ISetToken _setToken) internal view {\n require(\n _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,\n \"Only the module can call\"\n );\n\n require(\n controller.isModule(msg.sender),\n \"Module must be enabled on controller\"\n );\n }\n\n /**\n * SetToken must be in a pending state and module must be in pending state\n */\n function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {\n require(controller.isSet(address(_setToken)), \"Must be controller-enabled SetToken\");\n require(isSetPendingInitialization(_setToken), \"Must be pending initialization\");\n }\n}" }, "contracts/protocol/lib/Position.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\npragma experimental \"ABIEncoderV2\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { SignedSafeMath } from \"@openzeppelin/contracts/math/SignedSafeMath.sol\";\n\nimport { ISetToken } from \"../../interfaces/ISetToken.sol\";\nimport { PreciseUnitMath } from \"../../lib/PreciseUnitMath.sol\";\n\n\n/**\n * @title Position\n * @author Set Protocol\n *\n * Collection of helper functions for handling and updating SetToken Positions\n *\n * CHANGELOG:\n * - Updated editExternalPosition to work when no external position is associated with module\n */\nlibrary Position {\n using SafeCast for uint256;\n using SafeMath for uint256;\n using SafeCast for int256;\n using SignedSafeMath for int256;\n using PreciseUnitMath for uint256;\n\n /* ============ Helper ============ */\n\n /**\n * Returns whether the SetToken has a default position for a given component (if the real unit is > 0)\n */\n function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {\n return _setToken.getDefaultPositionRealUnit(_component) > 0;\n }\n\n /**\n * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)\n */\n function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {\n return _setToken.getExternalPositionModules(_component).length > 0;\n }\n \n /**\n * Returns whether the SetToken component default position real unit is greater than or equal to units passed in.\n */\n function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {\n return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();\n }\n\n /**\n * Returns whether the SetToken component external position is greater than or equal to the real units passed in.\n */\n function hasSufficientExternalUnits(\n ISetToken _setToken,\n address _component,\n address _positionModule,\n uint256 _unit\n )\n internal\n view\n returns(bool)\n {\n return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); \n }\n\n /**\n * If the position does not exist, create a new Position and add to the SetToken. If it already exists,\n * then set the position units. If the new units is 0, remove the position. Handles adding/removing of \n * components where needed (in light of potential external positions).\n *\n * @param _setToken Address of SetToken being modified\n * @param _component Address of the component\n * @param _newUnit Quantity of Position units - must be >= 0\n */\n function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {\n bool isPositionFound = hasDefaultPosition(_setToken, _component);\n if (!isPositionFound && _newUnit > 0) {\n // If there is no Default Position and no External Modules, then component does not exist\n if (!hasExternalPosition(_setToken, _component)) {\n _setToken.addComponent(_component);\n }\n } else if (isPositionFound && _newUnit == 0) {\n // If there is a Default Position and no external positions, remove the component\n if (!hasExternalPosition(_setToken, _component)) {\n _setToken.removeComponent(_component);\n }\n }\n\n _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());\n }\n\n /**\n * Update an external position and remove and external positions or components if necessary. The logic flows as follows:\n * 1) If component is not already added then add component and external position. \n * 2) If component is added but no existing external position using the passed module exists then add the external position.\n * 3) If the existing position is being added to then just update the unit and data\n * 4) If the position is being closed and no other external positions or default positions are associated with the component\n * then untrack the component and remove external position.\n * 5) If the position is being closed and other existing positions still exist for the component then just remove the\n * external position.\n *\n * @param _setToken SetToken being updated\n * @param _component Component position being updated\n * @param _module Module external position is associated with\n * @param _newUnit Position units of new external position\n * @param _data Arbitrary data associated with the position\n */\n function editExternalPosition(\n ISetToken _setToken,\n address _component,\n address _module,\n int256 _newUnit,\n bytes memory _data\n )\n internal\n {\n if (_newUnit != 0) {\n if (!_setToken.isComponent(_component)) {\n _setToken.addComponent(_component);\n _setToken.addExternalPositionModule(_component, _module);\n } else if (!_setToken.isExternalPositionModule(_component, _module)) {\n _setToken.addExternalPositionModule(_component, _module);\n }\n _setToken.editExternalPositionUnit(_component, _module, _newUnit);\n _setToken.editExternalPositionData(_component, _module, _data);\n } else {\n require(_data.length == 0, \"Passed data must be null\");\n // If no default or external position remaining then remove component from components array\n if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {\n address[] memory positionModules = _setToken.getExternalPositionModules(_component);\n if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {\n require(positionModules[0] == _module, \"External positions must be 0 to remove component\");\n _setToken.removeComponent(_component);\n }\n _setToken.removeExternalPositionModule(_component, _module);\n }\n }\n }\n\n /**\n * Get total notional amount of Default position\n *\n * @param _setTokenSupply Supply of SetToken in precise units (10^18)\n * @param _positionUnit Quantity of Position units\n *\n * @return Total notional amount of units\n */\n function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {\n return _setTokenSupply.preciseMul(_positionUnit);\n }\n\n /**\n * Get position unit from total notional amount\n *\n * @param _setTokenSupply Supply of SetToken in precise units (10^18)\n * @param _totalNotional Total notional amount of component prior to\n * @return Default position unit\n */\n function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {\n return _totalNotional.preciseDiv(_setTokenSupply);\n }\n\n /**\n * Get the total tracked balance - total supply * position unit\n *\n * @param _setToken Address of the SetToken\n * @param _component Address of the component\n * @return Notional tracked balance\n */\n function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {\n int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); \n return _setToken.totalSupply().preciseMul(positionUnit.toUint256());\n }\n\n /**\n * Calculates the new default position unit and performs the edit with the new unit\n *\n * @param _setToken Address of the SetToken\n * @param _component Address of the component\n * @param _setTotalSupply Current SetToken supply\n * @param _componentPreviousBalance Pre-action component balance\n * @return Current component balance\n * @return Previous position unit\n * @return New position unit\n */\n function calculateAndEditDefaultPosition(\n ISetToken _setToken,\n address _component,\n uint256 _setTotalSupply,\n uint256 _componentPreviousBalance\n )\n internal\n returns(uint256, uint256, uint256)\n {\n uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));\n uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();\n\n uint256 newTokenUnit;\n if (currentBalance > 0) {\n newTokenUnit = calculateDefaultEditPositionUnit(\n _setTotalSupply,\n _componentPreviousBalance,\n currentBalance,\n positionUnit\n );\n } else {\n newTokenUnit = 0;\n }\n\n editDefaultPosition(_setToken, _component, newTokenUnit);\n\n return (currentBalance, positionUnit, newTokenUnit);\n }\n\n /**\n * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state\n * The intention is to make updates to the units without accidentally picking up airdropped assets as well.\n *\n * @param _setTokenSupply Supply of SetToken in precise units (10^18)\n * @param _preTotalNotional Total notional amount of component prior to executing action\n * @param _postTotalNotional Total notional amount of component after the executing action\n * @param _prePositionUnit Position unit of SetToken prior to executing action\n * @return New position unit\n */\n function calculateDefaultEditPositionUnit(\n uint256 _setTokenSupply,\n uint256 _preTotalNotional,\n uint256 _postTotalNotional,\n uint256 _prePositionUnit\n )\n internal\n pure\n returns (uint256)\n {\n // If pre action total notional amount is greater then subtract post action total notional and calculate new position units\n uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));\n return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);\n }\n}\n" }, "contracts/protocol/lib/ResourceIdentifier.sol": { "content": "/*\n Copyright 2020 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\n\nimport { IController } from \"../../interfaces/IController.sol\";\nimport { IIntegrationRegistry } from \"../../interfaces/IIntegrationRegistry.sol\";\nimport { IPriceOracle } from \"../../interfaces/IPriceOracle.sol\";\nimport { ISetValuer } from \"../../interfaces/ISetValuer.sol\";\n\n/**\n * @title ResourceIdentifier\n * @author Set Protocol\n *\n * A collection of utility functions to fetch information related to Resource contracts in the system\n */\nlibrary ResourceIdentifier {\n\n // IntegrationRegistry will always be resource ID 0 in the system\n uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;\n // PriceOracle will always be resource ID 1 in the system\n uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;\n // SetValuer resource will always be resource ID 2 in the system\n uint256 constant internal SET_VALUER_RESOURCE_ID = 2;\n\n /* ============ Internal ============ */\n\n /**\n * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on\n * the Controller\n */\n function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {\n return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));\n }\n\n /**\n * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller\n */\n function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {\n return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));\n }\n\n /**\n * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller\n */\n function getSetValuer(IController _controller) internal view returns (ISetValuer) {\n return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));\n }\n}" }, "contracts/protocol/modules/v1/DebtIssuanceModule.sol": { "content": "/*\n Copyright 2021 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\npragma experimental \"ABIEncoderV2\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/SafeCast.sol\";\nimport { SafeMath } from \"@openzeppelin/contracts/math/SafeMath.sol\";\nimport { SignedSafeMath } from \"@openzeppelin/contracts/math/SignedSafeMath.sol\";\n\nimport { AddressArrayUtils } from \"../../../lib/AddressArrayUtils.sol\";\nimport { IController } from \"../../../interfaces/IController.sol\";\nimport { IManagerIssuanceHook } from \"../../../interfaces/IManagerIssuanceHook.sol\";\nimport { IModuleIssuanceHook } from \"../../../interfaces/IModuleIssuanceHook.sol\";\nimport { Invoke } from \"../../lib/Invoke.sol\";\nimport { ISetToken } from \"../../../interfaces/ISetToken.sol\";\nimport { ModuleBase } from \"../../lib/ModuleBase.sol\";\nimport { Position } from \"../../lib/Position.sol\";\nimport { PreciseUnitMath } from \"../../../lib/PreciseUnitMath.sol\";\n\n\n/**\n * @title DebtIssuanceModule\n * @author Set Protocol\n *\n * The DebtIssuanceModule is a module that enables users to issue and redeem SetTokens that contain default and all\n * external positions, including debt positions. Module hooks are added to allow for syncing of positions, and component\n * level hooks are added to ensure positions are replicated correctly. The manager can define arbitrary issuance logic\n * in the manager hook, as well as specify issue and redeem fees.\n */\ncontract DebtIssuanceModule is ModuleBase, ReentrancyGuard {\n\n /* ============ Structs ============ */\n\n // NOTE: moduleIssuanceHooks uses address[] for compatibility with AddressArrayUtils library\n struct IssuanceSettings {\n uint256 maxManagerFee; // Max issue/redeem fee defined on instantiation\n uint256 managerIssueFee; // Current manager issuance fees in precise units (10^16 = 1%)\n uint256 managerRedeemFee; // Current manager redeem fees in precise units (10^16 = 1%)\n address feeRecipient; // Address that receives all manager issue and redeem fees\n IManagerIssuanceHook managerIssuanceHook; // Instance of manager defined hook, can hold arbitrary logic\n address[] moduleIssuanceHooks; // Array of modules that are registered with this module\n mapping(address => bool) isModuleHook; // Mapping of modules to if they've registered a hook\n }\n\n /* ============ Events ============ */\n\n event SetTokenIssued(\n ISetToken indexed _setToken,\n address indexed _issuer,\n address indexed _to,\n address _hookContract,\n uint256 _quantity,\n uint256 _managerFee,\n uint256 _protocolFee\n );\n event SetTokenRedeemed(\n ISetToken indexed _setToken,\n address indexed _redeemer,\n address indexed _to,\n uint256 _quantity,\n uint256 _managerFee,\n uint256 _protocolFee\n );\n event FeeRecipientUpdated(ISetToken indexed _setToken, address _newFeeRecipient);\n event IssueFeeUpdated(ISetToken indexed _setToken, uint256 _newIssueFee);\n event RedeemFeeUpdated(ISetToken indexed _setToken, uint256 _newRedeemFee);\n\n /* ============ Constants ============ */\n\n uint256 private constant ISSUANCE_MODULE_PROTOCOL_FEE_SPLIT_INDEX = 0;\n\n /* ============ State ============ */\n\n mapping(ISetToken => IssuanceSettings) public issuanceSettings;\n\n /* ============ Constructor ============ */\n\n constructor(IController _controller) public ModuleBase(_controller) {}\n\n /* ============ External Functions ============ */\n\n /**\n * Deposits components to the SetToken, replicates any external module component positions and mints\n * the SetToken. If the token has a debt position all collateral will be transferred in first then debt\n * will be returned to the minting address. If specified, a fee will be charged on issuance.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Quantity of SetToken to issue\n * @param _to Address to mint SetToken to\n */\n function issue(\n ISetToken _setToken,\n uint256 _quantity,\n address _to\n )\n external\n virtual\n nonReentrant\n onlyValidAndInitializedSet(_setToken)\n {\n require(_quantity > 0, \"Issue quantity must be > 0\");\n\n address hookContract = _callManagerPreIssueHooks(_setToken, _quantity, msg.sender, _to);\n\n _callModulePreIssueHooks(_setToken, _quantity);\n\n (\n uint256 quantityWithFees,\n uint256 managerFee,\n uint256 protocolFee\n ) = calculateTotalFees(_setToken, _quantity, true);\n\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true);\n\n _resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits);\n _resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits);\n _resolveFees(_setToken, managerFee, protocolFee);\n\n _setToken.mint(_to, _quantity);\n\n emit SetTokenIssued(\n _setToken,\n msg.sender,\n _to,\n hookContract,\n _quantity,\n managerFee,\n protocolFee\n );\n }\n\n /**\n * Returns components from the SetToken, unwinds any external module component positions and burns the SetToken.\n * If the token has debt positions, the module transfers in the required debt amounts from the caller and uses\n * those funds to repay the debts on behalf of the SetToken. All debt will be paid down first then equity positions\n * will be returned to the minting address. If specified, a fee will be charged on redeem.\n *\n * @param _setToken Instance of the SetToken to redeem\n * @param _quantity Quantity of SetToken to redeem\n * @param _to Address to send collateral to\n */\n function redeem(\n ISetToken _setToken,\n uint256 _quantity,\n address _to\n )\n external\n virtual\n nonReentrant\n onlyValidAndInitializedSet(_setToken)\n {\n require(_quantity > 0, \"Redeem quantity must be > 0\");\n\n _callModulePreRedeemHooks(_setToken, _quantity);\n\n // Place burn after pre-redeem hooks because burning tokens may lead to false accounting of synced positions\n _setToken.burn(msg.sender, _quantity);\n\n (\n uint256 quantityNetFees,\n uint256 managerFee,\n uint256 protocolFee\n ) = calculateTotalFees(_setToken, _quantity, false);\n\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityNetFees, false);\n\n _resolveDebtPositions(_setToken, quantityNetFees, false, components, debtUnits);\n _resolveEquityPositions(_setToken, quantityNetFees, _to, false, components, equityUnits);\n _resolveFees(_setToken, managerFee, protocolFee);\n\n emit SetTokenRedeemed(\n _setToken,\n msg.sender,\n _to,\n _quantity,\n managerFee,\n protocolFee\n );\n }\n\n /**\n * MANAGER ONLY: Updates address receiving issue/redeem fees for a given SetToken.\n *\n * @param _setToken Instance of the SetToken to update fee recipient\n * @param _newFeeRecipient New fee recipient address\n */\n function updateFeeRecipient(\n ISetToken _setToken,\n address _newFeeRecipient\n )\n external\n onlyManagerAndValidSet(_setToken)\n {\n require(_newFeeRecipient != address(0), \"Fee Recipient must be non-zero address.\");\n require(_newFeeRecipient != issuanceSettings[_setToken].feeRecipient, \"Same fee recipient passed\");\n\n issuanceSettings[_setToken].feeRecipient = _newFeeRecipient;\n\n emit FeeRecipientUpdated(_setToken, _newFeeRecipient);\n }\n\n /**\n * MANAGER ONLY: Updates issue fee for passed SetToken\n *\n * @param _setToken Instance of the SetToken to update issue fee\n * @param _newIssueFee New fee amount in preciseUnits (1% = 10^16)\n */\n function updateIssueFee(\n ISetToken _setToken,\n uint256 _newIssueFee\n )\n external\n onlyManagerAndValidSet(_setToken)\n {\n require(_newIssueFee <= issuanceSettings[_setToken].maxManagerFee, \"Issue fee can't exceed maximum\");\n require(_newIssueFee != issuanceSettings[_setToken].managerIssueFee, \"Same issue fee passed\");\n\n issuanceSettings[_setToken].managerIssueFee = _newIssueFee;\n\n emit IssueFeeUpdated(_setToken, _newIssueFee);\n }\n\n /**\n * MANAGER ONLY: Updates redeem fee for passed SetToken\n *\n * @param _setToken Instance of the SetToken to update redeem fee\n * @param _newRedeemFee New fee amount in preciseUnits (1% = 10^16)\n */\n function updateRedeemFee(\n ISetToken _setToken,\n uint256 _newRedeemFee\n )\n external\n onlyManagerAndValidSet(_setToken)\n {\n require(_newRedeemFee <= issuanceSettings[_setToken].maxManagerFee, \"Redeem fee can't exceed maximum\");\n require(_newRedeemFee != issuanceSettings[_setToken].managerRedeemFee, \"Same redeem fee passed\");\n\n issuanceSettings[_setToken].managerRedeemFee = _newRedeemFee;\n\n emit RedeemFeeUpdated(_setToken, _newRedeemFee);\n }\n\n /**\n * MODULE ONLY: Adds calling module to array of modules that require they be called before component hooks are\n * called. Can be used to sync debt positions before issuance.\n *\n * @param _setToken Instance of the SetToken to issue\n */\n function registerToIssuanceModule(ISetToken _setToken) external onlyModule(_setToken) onlyValidAndInitializedSet(_setToken) {\n require(!issuanceSettings[_setToken].isModuleHook[msg.sender], \"Module already registered.\");\n issuanceSettings[_setToken].moduleIssuanceHooks.push(msg.sender);\n issuanceSettings[_setToken].isModuleHook[msg.sender] = true;\n }\n\n /**\n * MODULE ONLY: Removes calling module from array of modules that require they be called before component hooks are\n * called.\n *\n * @param _setToken Instance of the SetToken to issue\n */\n function unregisterFromIssuanceModule(ISetToken _setToken) external onlyModule(_setToken) onlyValidAndInitializedSet(_setToken) {\n require(issuanceSettings[_setToken].isModuleHook[msg.sender], \"Module not registered.\");\n issuanceSettings[_setToken].moduleIssuanceHooks.removeStorage(msg.sender);\n issuanceSettings[_setToken].isModuleHook[msg.sender] = false;\n }\n\n /**\n * MANAGER ONLY: Initializes this module to the SetToken with issuance-related hooks and fee information. Only callable\n * by the SetToken's manager. Hook addresses are optional. Address(0) means that no hook will be called\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _maxManagerFee Maximum fee that can be charged on issue and redeem\n * @param _managerIssueFee Fee to charge on issuance\n * @param _managerRedeemFee Fee to charge on redemption\n * @param _feeRecipient Address to send fees to\n * @param _managerIssuanceHook Instance of the Manager Contract with the Pre-Issuance Hook function\n */\n function initialize(\n ISetToken _setToken,\n uint256 _maxManagerFee,\n uint256 _managerIssueFee,\n uint256 _managerRedeemFee,\n address _feeRecipient,\n IManagerIssuanceHook _managerIssuanceHook\n )\n external\n onlySetManager(_setToken, msg.sender)\n onlyValidAndPendingSet(_setToken)\n {\n require(_managerIssueFee <= _maxManagerFee, \"Issue fee can't exceed maximum fee\");\n require(_managerRedeemFee <= _maxManagerFee, \"Redeem fee can't exceed maximum fee\");\n\n issuanceSettings[_setToken] = IssuanceSettings({\n maxManagerFee: _maxManagerFee,\n managerIssueFee: _managerIssueFee,\n managerRedeemFee: _managerRedeemFee,\n feeRecipient: _feeRecipient,\n managerIssuanceHook: _managerIssuanceHook,\n moduleIssuanceHooks: new address[](0)\n });\n\n _setToken.initializeModule();\n }\n\n /**\n * SET TOKEN ONLY: Allows removal of module (and deletion of state) if no other modules are registered.\n */\n function removeModule() external override {\n require(issuanceSettings[ISetToken(msg.sender)].moduleIssuanceHooks.length == 0, \"Registered modules must be removed.\");\n delete issuanceSettings[ISetToken(msg.sender)];\n }\n\n /* ============ External View Functions ============ */\n\n /**\n * Calculates the manager fee, protocol fee and resulting totalQuantity to use when calculating unit amounts. If fees are charged they\n * are added to the total issue quantity, for example 1% fee on 100 Sets means 101 Sets are minted by caller, the _to address receives\n * 100 and the feeRecipient receives 1. Conversely, on redemption the redeemer will only receive the collateral that collateralizes 99\n * Sets, while the additional Set is given to the feeRecipient.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Amount of SetToken issuer wants to receive/redeem\n * @param _isIssue If issuing or redeeming\n *\n * @return totalQuantity Total amount of Sets to be issued/redeemed with fee adjustment\n * @return managerFee Sets minted to the manager\n * @return protocolFee Sets minted to the protocol\n */\n function calculateTotalFees(\n ISetToken _setToken,\n uint256 _quantity,\n bool _isIssue\n )\n public\n view\n returns (uint256 totalQuantity, uint256 managerFee, uint256 protocolFee)\n {\n IssuanceSettings memory setIssuanceSettings = issuanceSettings[_setToken];\n uint256 protocolFeeSplit = controller.getModuleFee(address(this), ISSUANCE_MODULE_PROTOCOL_FEE_SPLIT_INDEX);\n uint256 totalFeeRate = _isIssue ? setIssuanceSettings.managerIssueFee : setIssuanceSettings.managerRedeemFee;\n\n uint256 totalFee = totalFeeRate.preciseMul(_quantity);\n protocolFee = totalFee.preciseMul(protocolFeeSplit);\n managerFee = totalFee.sub(protocolFee);\n\n totalQuantity = _isIssue ? _quantity.add(totalFee) : _quantity.sub(totalFee);\n }\n\n /**\n * Calculates the amount of each component needed to collateralize passed issue quantity plus fees of Sets as well as amount of debt\n * that will be returned to caller. Values DO NOT take into account any updates from pre action manager or module hooks.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Amount of Sets to be issued\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256\n */\n function getRequiredComponentIssuanceUnits(\n ISetToken _setToken,\n uint256 _quantity\n )\n external\n view\n virtual\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n (\n uint256 totalQuantity,,\n ) = calculateTotalFees(_setToken, _quantity, true);\n\n return _calculateRequiredComponentIssuanceUnits(_setToken, totalQuantity, true);\n }\n\n /**\n * Calculates the amount of each component will be returned on redemption net of fees as well as how much debt needs to be paid down to.\n * redeem. Values DO NOT take into account any updates from pre action manager or module hooks.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Amount of Sets to be redeemed\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256\n */\n function getRequiredComponentRedemptionUnits(\n ISetToken _setToken,\n uint256 _quantity\n )\n external\n view\n virtual\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n (\n uint256 totalQuantity,,\n ) = calculateTotalFees(_setToken, _quantity, false);\n\n return _calculateRequiredComponentIssuanceUnits(_setToken, totalQuantity, false);\n }\n\n function getModuleIssuanceHooks(ISetToken _setToken) external view returns(address[] memory) {\n return issuanceSettings[_setToken].moduleIssuanceHooks;\n }\n\n function isModuleIssuanceHook(ISetToken _setToken, address _hook) external view returns(bool) {\n return issuanceSettings[_setToken].isModuleHook[_hook];\n }\n\n /* ============ Internal Functions ============ */\n\n /**\n * Calculates the amount of each component needed to collateralize passed issue quantity of Sets as well as amount of debt that will\n * be returned to caller. Can also be used to determine how much collateral will be returned on redemption as well as how much debt\n * needs to be paid down to redeem.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Amount of Sets to be issued/redeemed\n * @param _isIssue Whether Sets are being issued or redeemed\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256\n */\n function _calculateRequiredComponentIssuanceUnits(\n ISetToken _setToken,\n uint256 _quantity,\n bool _isIssue\n )\n internal\n view\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _getTotalIssuanceUnits(_setToken);\n\n uint256 componentsLength = components.length;\n uint256[] memory totalEquityUnits = new uint256[](componentsLength);\n uint256[] memory totalDebtUnits = new uint256[](componentsLength);\n for (uint256 i = 0; i < components.length; i++) {\n // Use preciseMulCeil to round up to ensure overcollateration when small issue quantities are provided\n // and preciseMul to round down to ensure overcollateration when small redeem quantities are provided\n totalEquityUnits[i] = _isIssue ?\n equityUnits[i].preciseMulCeil(_quantity) :\n equityUnits[i].preciseMul(_quantity);\n\n totalDebtUnits[i] = _isIssue ?\n debtUnits[i].preciseMul(_quantity) :\n debtUnits[i].preciseMulCeil(_quantity);\n }\n\n return (components, totalEquityUnits, totalDebtUnits);\n }\n\n /**\n * Sums total debt and equity units for each component, taking into account default and external positions.\n *\n * @param _setToken Instance of the SetToken to issue\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity unit amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt unit amounts of each component, respectively, represented as uint256\n */\n function _getTotalIssuanceUnits(\n ISetToken _setToken\n )\n internal\n view\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n address[] memory components = _setToken.getComponents();\n uint256 componentsLength = components.length;\n\n uint256[] memory equityUnits = new uint256[](componentsLength);\n uint256[] memory debtUnits = new uint256[](componentsLength);\n\n for (uint256 i = 0; i < components.length; i++) {\n address component = components[i];\n int256 cumulativeEquity = _setToken.getDefaultPositionRealUnit(component);\n int256 cumulativeDebt = 0;\n address[] memory externalPositions = _setToken.getExternalPositionModules(component);\n\n if (externalPositions.length > 0) {\n for (uint256 j = 0; j < externalPositions.length; j++) {\n int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(component, externalPositions[j]);\n\n // If positionUnit <= 0 it will be \"added\" to debt position\n if (externalPositionUnit > 0) {\n cumulativeEquity = cumulativeEquity.add(externalPositionUnit);\n } else {\n cumulativeDebt = cumulativeDebt.add(externalPositionUnit);\n }\n }\n }\n\n equityUnits[i] = cumulativeEquity.toUint256();\n debtUnits[i] = cumulativeDebt.mul(-1).toUint256();\n }\n\n return (components, equityUnits, debtUnits);\n }\n\n /**\n * Resolve equity positions associated with SetToken. On issuance, the total equity position for an asset (including default and external\n * positions) is transferred in. Then any external position hooks are called to transfer the external positions to their necessary place.\n * On redemption all external positions are recalled by the external position hook, then those position plus any default position are\n * transferred back to the _to address.\n */\n function _resolveEquityPositions(\n ISetToken _setToken,\n uint256 _quantity,\n address _to,\n bool _isIssue,\n address[] memory _components,\n uint256[] memory _componentEquityQuantities\n )\n internal\n {\n for (uint256 i = 0; i < _components.length; i++) {\n address component = _components[i];\n uint256 componentQuantity = _componentEquityQuantities[i];\n if (componentQuantity > 0) {\n if (_isIssue) {\n transferFrom(\n IERC20(component),\n msg.sender,\n address(_setToken),\n componentQuantity\n );\n\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, true);\n } else {\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, true);\n\n _setToken.strictInvokeTransfer(\n component,\n _to,\n componentQuantity\n );\n }\n }\n }\n }\n\n /**\n * Resolve debt positions associated with SetToken. On issuance, debt positions are entered into by calling the external position hook. The\n * resulting debt is then returned to the calling address. On redemption, the module transfers in the required debt amount from the caller\n * and uses those funds to repay the debt on behalf of the SetToken.\n */\n function _resolveDebtPositions(\n ISetToken _setToken,\n uint256 _quantity,\n bool _isIssue,\n address[] memory _components,\n uint256[] memory _componentDebtQuantities\n )\n internal\n {\n for (uint256 i = 0; i < _components.length; i++) {\n address component = _components[i];\n uint256 componentQuantity = _componentDebtQuantities[i];\n if (componentQuantity > 0) {\n if (_isIssue) {\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, false);\n _setToken.strictInvokeTransfer(\n component,\n msg.sender,\n componentQuantity\n );\n } else {\n transferFrom(\n IERC20(component),\n msg.sender,\n address(_setToken),\n componentQuantity\n );\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, false);\n }\n }\n }\n }\n\n /**\n * If any manager fees mints Sets to the defined feeRecipient. If protocol fee is enabled mints Sets to protocol\n * feeRecipient.\n */\n function _resolveFees(ISetToken _setToken, uint256 managerFee, uint256 protocolFee) internal {\n if (managerFee > 0) {\n _setToken.mint(issuanceSettings[_setToken].feeRecipient, managerFee);\n\n // Protocol fee check is inside manager fee check because protocol fees are only collected on manager fees\n if (protocolFee > 0) {\n _setToken.mint(controller.feeRecipient(), protocolFee);\n }\n }\n }\n\n /**\n * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic\n * can contain arbitrary logic including validations, external function calls, etc.\n */\n function _callManagerPreIssueHooks(\n ISetToken _setToken,\n uint256 _quantity,\n address _caller,\n address _to\n )\n internal\n returns(address)\n {\n IManagerIssuanceHook preIssueHook = issuanceSettings[_setToken].managerIssuanceHook;\n if (address(preIssueHook) != address(0)) {\n preIssueHook.invokePreIssueHook(_setToken, _quantity, _caller, _to);\n return address(preIssueHook);\n }\n\n return address(0);\n }\n\n /**\n * Calls all modules that have registered with the DebtIssuanceModule that have a moduleIssueHook.\n */\n function _callModulePreIssueHooks(ISetToken _setToken, uint256 _quantity) internal {\n address[] memory issuanceHooks = issuanceSettings[_setToken].moduleIssuanceHooks;\n for (uint256 i = 0; i < issuanceHooks.length; i++) {\n IModuleIssuanceHook(issuanceHooks[i]).moduleIssueHook(_setToken, _quantity);\n }\n }\n\n /**\n * Calls all modules that have registered with the DebtIssuanceModule that have a moduleRedeemHook.\n */\n function _callModulePreRedeemHooks(ISetToken _setToken, uint256 _quantity) internal {\n address[] memory issuanceHooks = issuanceSettings[_setToken].moduleIssuanceHooks;\n for (uint256 i = 0; i < issuanceHooks.length; i++) {\n IModuleIssuanceHook(issuanceHooks[i]).moduleRedeemHook(_setToken, _quantity);\n }\n }\n\n /**\n * For each component's external module positions, calculate the total notional quantity, and\n * call the module's issue hook or redeem hook.\n * Note: It is possible that these hooks can cause the states of other modules to change.\n * It can be problematic if the hook called an external function that called back into a module, resulting in state inconsistencies.\n */\n function _executeExternalPositionHooks(\n ISetToken _setToken,\n uint256 _setTokenQuantity,\n IERC20 _component,\n bool _isIssue,\n bool _isEquity\n )\n internal\n {\n address[] memory externalPositionModules = _setToken.getExternalPositionModules(address(_component));\n uint256 modulesLength = externalPositionModules.length;\n if (_isIssue) {\n for (uint256 i = 0; i < modulesLength; i++) {\n IModuleIssuanceHook(externalPositionModules[i]).componentIssueHook(_setToken, _setTokenQuantity, _component, _isEquity);\n }\n } else {\n for (uint256 i = 0; i < modulesLength; i++) {\n IModuleIssuanceHook(externalPositionModules[i]).componentRedeemHook(_setToken, _setTokenQuantity, _component, _isEquity);\n }\n }\n }\n}" }, "contracts/protocol/modules/v1/DebtIssuanceModuleV2.sol": { "content": "/*\n Copyright 2021 Set Labs Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n SPDX-License-Identifier: Apache License, Version 2.0\n*/\n\npragma solidity 0.6.10;\npragma experimental \"ABIEncoderV2\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/SafeERC20.sol\";\n\nimport { DebtIssuanceModule } from \"./DebtIssuanceModule.sol\";\nimport { IController } from \"../../../interfaces/IController.sol\";\nimport { Invoke } from \"../../lib/Invoke.sol\";\nimport { ISetToken } from \"../../../interfaces/ISetToken.sol\";\nimport { IssuanceValidationUtils } from \"../../lib/IssuanceValidationUtils.sol\";\nimport { Position } from \"../../lib/Position.sol\";\n\n/**\n * @title DebtIssuanceModuleV2\n * @author Set Protocol\n *\n * The DebtIssuanceModuleV2 is a module that enables users to issue and redeem SetTokens that contain default and all\n * external positions, including debt positions. Module hooks are added to allow for syncing of positions, and component\n * level hooks are added to ensure positions are replicated correctly. The manager can define arbitrary issuance logic\n * in the manager hook, as well as specify issue and redeem fees.\n *\n * NOTE:\n * DebtIssuanceModule contract confirms increase/decrease in balance of component held by the SetToken after every transfer in/out\n * for each component during issuance/redemption. This contract replaces those strict checks with slightly looser checks which\n * ensure that the SetToken remains collateralized after every transfer in/out for each component during issuance/redemption.\n * This module should be used to issue/redeem SetToken whose one or more components return a balance value with +/-1 wei error.\n * For example, this module can be used to issue/redeem SetTokens which has one or more aTokens as its components.\n * The new checks do NOT apply to any transfers that are part of an external position. A token that has rounding issues may lead to\n * reverts if it is included as an external position unless explicitly allowed in a module hook.\n *\n * The getRequiredComponentIssuanceUnits function on this module assumes that Default token balances will be synced on every issuance\n * and redemption. If token balances are not being synced it will over-estimate the amount of tokens required to issue a Set.\n */\ncontract DebtIssuanceModuleV2 is DebtIssuanceModule {\n using Position for uint256;\n\n /* ============ Constructor ============ */\n\n constructor(IController _controller) public DebtIssuanceModule(_controller) {}\n\n /* ============ External Functions ============ */\n\n /**\n * Deposits components to the SetToken, replicates any external module component positions and mints\n * the SetToken. If the token has a debt position all collateral will be transferred in first then debt\n * will be returned to the minting address. If specified, a fee will be charged on issuance.\n *\n * NOTE: Overrides DebtIssuanceModule#issue external function and adds undercollateralization checks in place of the\n * previous default strict balances checks. The undercollateralization checks are implemented in IssuanceValidationUtils library and they\n * revert upon undercollateralization of the SetToken post component transfer.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Quantity of SetToken to issue\n * @param _to Address to mint SetToken to\n */\n function issue(\n ISetToken _setToken,\n uint256 _quantity,\n address _to\n )\n external\n override\n nonReentrant\n onlyValidAndInitializedSet(_setToken)\n {\n require(_quantity > 0, \"Issue quantity must be > 0\");\n\n address hookContract = _callManagerPreIssueHooks(_setToken, _quantity, msg.sender, _to);\n\n _callModulePreIssueHooks(_setToken, _quantity);\n\n\n uint256 initialSetSupply = _setToken.totalSupply();\n\n (\n uint256 quantityWithFees,\n uint256 managerFee,\n uint256 protocolFee\n ) = calculateTotalFees(_setToken, _quantity, true);\n\n // Prevent stack too deep\n {\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityWithFees, true);\n\n uint256 finalSetSupply = initialSetSupply.add(quantityWithFees);\n\n _resolveEquityPositions(_setToken, quantityWithFees, _to, true, components, equityUnits, initialSetSupply, finalSetSupply);\n _resolveDebtPositions(_setToken, quantityWithFees, true, components, debtUnits, initialSetSupply, finalSetSupply);\n _resolveFees(_setToken, managerFee, protocolFee);\n }\n\n _setToken.mint(_to, _quantity);\n\n emit SetTokenIssued(\n _setToken,\n msg.sender,\n _to,\n hookContract,\n _quantity,\n managerFee,\n protocolFee\n );\n }\n\n /**\n * Returns components from the SetToken, unwinds any external module component positions and burns the SetToken.\n * If the token has debt positions, the module transfers in the required debt amounts from the caller and uses\n * those funds to repay the debts on behalf of the SetToken. All debt will be paid down first then equity positions\n * will be returned to the minting address. If specified, a fee will be charged on redeem.\n *\n * NOTE: Overrides DebtIssuanceModule#redeem internal function and adds undercollateralization checks in place of the\n * previous default strict balances checks. The undercollateralization checks are implemented in IssuanceValidationUtils library\n * and they revert upon undercollateralization of the SetToken post component transfer.\n *\n * @param _setToken Instance of the SetToken to redeem\n * @param _quantity Quantity of SetToken to redeem\n * @param _to Address to send collateral to\n */\n function redeem(\n ISetToken _setToken,\n uint256 _quantity,\n address _to\n )\n external\n override\n nonReentrant\n onlyValidAndInitializedSet(_setToken)\n {\n require(_quantity > 0, \"Redeem quantity must be > 0\");\n\n _callModulePreRedeemHooks(_setToken, _quantity);\n\n uint256 initialSetSupply = _setToken.totalSupply();\n\n // Place burn after pre-redeem hooks because burning tokens may lead to false accounting of synced positions\n _setToken.burn(msg.sender, _quantity);\n\n (\n uint256 quantityNetFees,\n uint256 managerFee,\n uint256 protocolFee\n ) = calculateTotalFees(_setToken, _quantity, false);\n\n // Prevent stack too deep\n {\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _calculateRequiredComponentIssuanceUnits(_setToken, quantityNetFees, false);\n\n uint256 finalSetSupply = initialSetSupply.sub(quantityNetFees);\n\n _resolveDebtPositions(_setToken, quantityNetFees, false, components, debtUnits, initialSetSupply, finalSetSupply);\n _resolveEquityPositions(_setToken, quantityNetFees, _to, false, components, equityUnits, initialSetSupply, finalSetSupply);\n _resolveFees(_setToken, managerFee, protocolFee);\n }\n\n emit SetTokenRedeemed(\n _setToken,\n msg.sender,\n _to,\n _quantity,\n managerFee,\n protocolFee\n );\n }\n\n /* ============ External View Functions ============ */\n\n /**\n * Calculates the amount of each component needed to collateralize passed issue quantity plus fees of Sets as well as amount of debt\n * that will be returned to caller. Default equity alues are calculated based on token balances and not position units in order to more\n * closely track any accrued tokens that will be synced during issuance. External equity and debt positions will use the stored position\n * units. IF TOKEN VALUES ARE NOT BEING SYNCED DURING ISSUANCE THIS FUNCTION WILL OVER ESTIMATE THE AMOUNT OF REQUIRED TOKENS.\n *\n * @param _setToken Instance of the SetToken to issue\n * @param _quantity Amount of Sets to be issued\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity notional amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt notional amounts of each component, respectively, represented as uint256\n */\n function getRequiredComponentIssuanceUnits(\n ISetToken _setToken,\n uint256 _quantity\n )\n external\n view\n override\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n (\n uint256 totalQuantity,,\n ) = calculateTotalFees(_setToken, _quantity, true);\n\n if(_setToken.totalSupply() == 0) {\n return _calculateRequiredComponentIssuanceUnits(_setToken, totalQuantity, true);\n } else {\n (\n address[] memory components,\n uint256[] memory equityUnits,\n uint256[] memory debtUnits\n ) = _getTotalIssuanceUnitsFromBalances(_setToken);\n\n uint256 componentsLength = components.length;\n uint256[] memory totalEquityUnits = new uint256[](componentsLength);\n uint256[] memory totalDebtUnits = new uint256[](componentsLength);\n for (uint256 i = 0; i < components.length; i++) {\n // Use preciseMulCeil to round up to ensure overcollateration of equity when small issue quantities are provided\n // and use preciseMul to round debt calculations down to make sure we don't return too much debt to issuer\n totalEquityUnits[i] = equityUnits[i].preciseMulCeil(totalQuantity);\n totalDebtUnits[i] = debtUnits[i].preciseMul(totalQuantity);\n }\n\n return (components, totalEquityUnits, totalDebtUnits);\n }\n }\n\n /* ============ Internal Functions ============ */\n\n /**\n * Resolve equity positions associated with SetToken. On issuance, the total equity position for an asset (including default and external\n * positions) is transferred in. Then any external position hooks are called to transfer the external positions to their necessary place.\n * On redemption all external positions are recalled by the external position hook, then those position plus any default position are\n * transferred back to the _to address.\n */\n function _resolveEquityPositions(\n ISetToken _setToken,\n uint256 _quantity,\n address _to,\n bool _isIssue,\n address[] memory _components,\n uint256[] memory _componentEquityQuantities,\n uint256 _initialSetSupply,\n uint256 _finalSetSupply\n )\n internal\n {\n for (uint256 i = 0; i < _components.length; i++) {\n address component = _components[i];\n uint256 componentQuantity = _componentEquityQuantities[i];\n if (componentQuantity > 0) {\n if (_isIssue) {\n // Call SafeERC20#safeTransferFrom instead of ExplicitERC20#transferFrom\n SafeERC20.safeTransferFrom(\n IERC20(component),\n msg.sender,\n address(_setToken),\n componentQuantity\n );\n\n IssuanceValidationUtils.validateCollateralizationPostTransferInPreHook(_setToken, component, _initialSetSupply, componentQuantity);\n\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, true);\n } else {\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, true);\n\n // Call Invoke#invokeTransfer instead of Invoke#strictInvokeTransfer\n _setToken.invokeTransfer(component, _to, componentQuantity);\n\n IssuanceValidationUtils.validateCollateralizationPostTransferOut(_setToken, component, _finalSetSupply);\n }\n }\n }\n }\n\n /**\n * Resolve debt positions associated with SetToken. On issuance, debt positions are entered into by calling the external position hook. The\n * resulting debt is then returned to the calling address. On redemption, the module transfers in the required debt amount from the caller\n * and uses those funds to repay the debt on behalf of the SetToken.\n */\n function _resolveDebtPositions(\n ISetToken _setToken,\n uint256 _quantity,\n bool _isIssue,\n address[] memory _components,\n uint256[] memory _componentDebtQuantities,\n uint256 _initialSetSupply,\n uint256 _finalSetSupply\n )\n internal\n {\n for (uint256 i = 0; i < _components.length; i++) {\n address component = _components[i];\n uint256 componentQuantity = _componentDebtQuantities[i];\n if (componentQuantity > 0) {\n if (_isIssue) {\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), true, false);\n\n // Call Invoke#invokeTransfer instead of Invoke#strictInvokeTransfer\n _setToken.invokeTransfer(component, msg.sender, componentQuantity);\n\n IssuanceValidationUtils.validateCollateralizationPostTransferOut(_setToken, component, _finalSetSupply);\n } else {\n // Call SafeERC20#safeTransferFrom instead of ExplicitERC20#transferFrom\n SafeERC20.safeTransferFrom(\n IERC20(component),\n msg.sender,\n address(_setToken),\n componentQuantity\n );\n\n IssuanceValidationUtils.validateCollateralizationPostTransferInPreHook(_setToken, component, _initialSetSupply, componentQuantity);\n\n _executeExternalPositionHooks(_setToken, _quantity, IERC20(component), false, false);\n }\n }\n }\n }\n /**\n * Reimplementation of _getTotalIssuanceUnits but instead derives Default equity positions from token balances on Set instead of from\n * position units. This function is ONLY to be used in getRequiredComponentIssuanceUnits in order to return more accurate required\n * token amounts to issuers when positions are being synced on issuance.\n *\n * @param _setToken Instance of the SetToken to issue\n *\n * @return address[] Array of component addresses making up the Set\n * @return uint256[] Array of equity unit amounts of each component, respectively, represented as uint256\n * @return uint256[] Array of debt unit amounts of each component, respectively, represented as uint256\n */\n function _getTotalIssuanceUnitsFromBalances(\n ISetToken _setToken\n )\n internal\n view\n returns (address[] memory, uint256[] memory, uint256[] memory)\n {\n address[] memory components = _setToken.getComponents();\n uint256 componentsLength = components.length;\n\n uint256[] memory equityUnits = new uint256[](componentsLength);\n uint256[] memory debtUnits = new uint256[](componentsLength);\n\n uint256 totalSupply = _setToken.totalSupply();\n\n for (uint256 i = 0; i < components.length; i++) {\n address component = components[i];\n int256 cumulativeEquity = totalSupply\n .getDefaultPositionUnit(IERC20(component).balanceOf(address(_setToken)))\n .toInt256();\n int256 cumulativeDebt = 0;\n address[] memory externalPositions = _setToken.getExternalPositionModules(component);\n\n if (externalPositions.length > 0) {\n for (uint256 j = 0; j < externalPositions.length; j++) {\n int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(component, externalPositions[j]);\n\n // If positionUnit <= 0 it will be \"added\" to debt position\n if (externalPositionUnit > 0) {\n cumulativeEquity = cumulativeEquity.add(externalPositionUnit);\n } else {\n cumulativeDebt = cumulativeDebt.add(externalPositionUnit);\n }\n }\n }\n\n equityUnits[i] = cumulativeEquity.toUint256();\n debtUnits[i] = cumulativeDebt.mul(-1).toUint256();\n }\n\n return (components, equityUnits, debtUnits);\n }\n}" } } }