Guest User

setToken.sol

a guest
Dec 8th, 2020 (edited)
55
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // File: @openzeppelin\contracts\utils\Address.sol
  2.  
  3. // SPDX-License-Identifier: MIT
  4.  
  5. pragma solidity ^0.6.2;
  6.  
  7. /**
  8. * @dev Collection of functions related to the address type
  9. */
  10. library Address {
  11. /**
  12. * @dev Returns true if `account` is a contract.
  13. *
  14. * [IMPORTANT]
  15. * ====
  16. * It is unsafe to assume that an address for which this function returns
  17. * false is an externally-owned account (EOA) and not a contract.
  18. *
  19. * Among others, `isContract` will return false for the following
  20. * types of addresses:
  21. *
  22. * - an externally-owned account
  23. * - a contract in construction
  24. * - an address where a contract will be created
  25. * - an address where a contract lived, but was destroyed
  26. * ====
  27. */
  28. function isContract(address account) internal view returns (bool) {
  29. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
  30. // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
  31. // for accounts without code, i.e. `keccak256('')`
  32. bytes32 codehash;
  33. bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
  34. // solhint-disable-next-line no-inline-assembly
  35. assembly { codehash := extcodehash(account) }
  36. return (codehash != accountHash && codehash != 0x0);
  37. }
  38.  
  39. /**
  40. * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
  41. * `recipient`, forwarding all available gas and reverting on errors.
  42. *
  43. * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
  44. * of certain opcodes, possibly making contracts go over the 2300 gas limit
  45. * imposed by `transfer`, making them unable to receive funds via
  46. * `transfer`. {sendValue} removes this limitation.
  47. *
  48. * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
  49. *
  50. * IMPORTANT: because control is transferred to `recipient`, care must be
  51. * taken to not create reentrancy vulnerabilities. Consider using
  52. * {ReentrancyGuard} or the
  53. * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
  54. */
  55. function sendValue(address payable recipient, uint256 amount) internal {
  56. require(address(this).balance >= amount, "Address: insufficient balance");
  57.  
  58. // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
  59. (bool success, ) = recipient.call{ value: amount }("");
  60. require(success, "Address: unable to send value, recipient may have reverted");
  61. }
  62.  
  63. /**
  64. * @dev Performs a Solidity function call using a low level `call`. A
  65. * plain`call` is an unsafe replacement for a function call: use this
  66. * function instead.
  67. *
  68. * If `target` reverts with a revert reason, it is bubbled up by this
  69. * function (like regular Solidity function calls).
  70. *
  71. * Returns the raw returned data. To convert to the expected return value,
  72. * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
  73. *
  74. * Requirements:
  75. *
  76. * - `target` must be a contract.
  77. * - calling `target` with `data` must not revert.
  78. *
  79. * _Available since v3.1._
  80. */
  81. function functionCall(address target, bytes memory data) internal returns (bytes memory) {
  82. return functionCall(target, data, "Address: low-level call failed");
  83. }
  84.  
  85. /**
  86. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
  87. * `errorMessage` as a fallback revert reason when `target` reverts.
  88. *
  89. * _Available since v3.1._
  90. */
  91. function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
  92. return _functionCallWithValue(target, data, 0, errorMessage);
  93. }
  94.  
  95. /**
  96. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
  97. * but also transferring `value` wei to `target`.
  98. *
  99. * Requirements:
  100. *
  101. * - the calling contract must have an ETH balance of at least `value`.
  102. * - the called Solidity function must be `payable`.
  103. *
  104. * _Available since v3.1._
  105. */
  106. function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
  107. return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
  108. }
  109.  
  110. /**
  111. * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
  112. * with `errorMessage` as a fallback revert reason when `target` reverts.
  113. *
  114. * _Available since v3.1._
  115. */
  116. function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
  117. require(address(this).balance >= value, "Address: insufficient balance for call");
  118. return _functionCallWithValue(target, data, value, errorMessage);
  119. }
  120.  
  121. function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
  122. require(isContract(target), "Address: call to non-contract");
  123.  
  124. // solhint-disable-next-line avoid-low-level-calls
  125. (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
  126. if (success) {
  127. return returndata;
  128. } else {
  129. // Look for revert reason and bubble it up if present
  130. if (returndata.length > 0) {
  131. // The easiest way to bubble the revert reason is using memory via assembly
  132.  
  133. // solhint-disable-next-line no-inline-assembly
  134. assembly {
  135. let returndata_size := mload(returndata)
  136. revert(add(32, returndata), returndata_size)
  137. }
  138. } else {
  139. revert(errorMessage);
  140. }
  141. }
  142. }
  143. }
  144.  
  145. // File: node_modules\@openzeppelin\contracts\GSN\Context.sol
  146.  
  147. // free
  148.  
  149. pragma solidity ^0.6.0;
  150.  
  151. /*
  152. * @dev Provides information about the current execution context, including the
  153. * sender of the transaction and its data. While these are generally available
  154. * via msg.sender and msg.data, they should not be accessed in such a direct
  155. * manner, since when dealing with GSN meta-transactions the account sending and
  156. * paying for execution may not be the actual sender (as far as an application
  157. * is concerned).
  158. *
  159. * This contract is only required for intermediate, library-like contracts.
  160. */
  161. abstract contract Context {
  162. function _msgSender() internal view virtual returns (address payable) {
  163. return msg.sender;
  164. }
  165.  
  166. function _msgData() internal view virtual returns (bytes memory) {
  167. this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
  168. return msg.data;
  169. }
  170. }
  171.  
  172. // File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
  173.  
  174. // free
  175.  
  176. pragma solidity ^0.6.0;
  177.  
  178. /**
  179. * @dev Interface of the ERC20 standard as defined in the EIP.
  180. */
  181. interface IERC20 {
  182. /**
  183. * @dev Returns the amount of tokens in existence.
  184. */
  185. function totalSupply() external view returns (uint256);
  186.  
  187. /**
  188. * @dev Returns the amount of tokens owned by `account`.
  189. */
  190. function balanceOf(address account) external view returns (uint256);
  191.  
  192. /**
  193. * @dev Moves `amount` tokens from the caller's account to `recipient`.
  194. *
  195. * Returns a boolean value indicating whether the operation succeeded.
  196. *
  197. * Emits a {Transfer} event.
  198. */
  199. function transfer(address recipient, uint256 amount) external returns (bool);
  200.  
  201. /**
  202. * @dev Returns the remaining number of tokens that `spender` will be
  203. * allowed to spend on behalf of `owner` through {transferFrom}. This is
  204. * zero by default.
  205. *
  206. * This value changes when {approve} or {transferFrom} are called.
  207. */
  208. function allowance(address owner, address spender) external view returns (uint256);
  209.  
  210. /**
  211. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
  212. *
  213. * Returns a boolean value indicating whether the operation succeeded.
  214. *
  215. * IMPORTANT: Beware that changing an allowance with this method brings the risk
  216. * that someone may use both the old and the new allowance by unfortunate
  217. * transaction ordering. One possible solution to mitigate this race
  218. * condition is to first reduce the spender's allowance to 0 and set the
  219. * desired value afterwards:
  220. * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
  221. *
  222. * Emits an {Approval} event.
  223. */
  224. function approve(address spender, uint256 amount) external returns (bool);
  225.  
  226. /**
  227. * @dev Moves `amount` tokens from `sender` to `recipient` using the
  228. * allowance mechanism. `amount` is then deducted from the caller's
  229. * allowance.
  230. *
  231. * Returns a boolean value indicating whether the operation succeeded.
  232. *
  233. * Emits a {Transfer} event.
  234. */
  235. function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
  236.  
  237. /**
  238. * @dev Emitted when `value` tokens are moved from one account (`from`) to
  239. * another (`to`).
  240. *
  241. * Note that `value` may be zero.
  242. */
  243. event Transfer(address indexed from, address indexed to, uint256 value);
  244.  
  245. /**
  246. * @dev Emitted when the allowance of a `spender` for an `owner` is set by
  247. * a call to {approve}. `value` is the new allowance.
  248. */
  249. event Approval(address indexed owner, address indexed spender, uint256 value);
  250. }
  251.  
  252. // File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
  253.  
  254. // free
  255.  
  256. pragma solidity ^0.6.0;
  257.  
  258. /**
  259. * @dev Wrappers over Solidity's arithmetic operations with added overflow
  260. * checks.
  261. *
  262. * Arithmetic operations in Solidity wrap on overflow. This can easily result
  263. * in bugs, because programmers usually assume that an overflow raises an
  264. * error, which is the standard behavior in high level programming languages.
  265. * `SafeMath` restores this intuition by reverting the transaction when an
  266. * operation overflows.
  267. *
  268. * Using this library instead of the unchecked operations eliminates an entire
  269. * class of bugs, so it's recommended to use it always.
  270. */
  271. library SafeMath {
  272. /**
  273. * @dev Returns the addition of two unsigned integers, reverting on
  274. * overflow.
  275. *
  276. * Counterpart to Solidity's `+` operator.
  277. *
  278. * Requirements:
  279. *
  280. * - Addition cannot overflow.
  281. */
  282. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  283. uint256 c = a + b;
  284. require(c >= a, "SafeMath: addition overflow");
  285.  
  286. return c;
  287. }
  288.  
  289. /**
  290. * @dev Returns the subtraction of two unsigned integers, reverting on
  291. * overflow (when the result is negative).
  292. *
  293. * Counterpart to Solidity's `-` operator.
  294. *
  295. * Requirements:
  296. *
  297. * - Subtraction cannot overflow.
  298. */
  299. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  300. return sub(a, b, "SafeMath: subtraction overflow");
  301. }
  302.  
  303. /**
  304. * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
  305. * overflow (when the result is negative).
  306. *
  307. * Counterpart to Solidity's `-` operator.
  308. *
  309. * Requirements:
  310. *
  311. * - Subtraction cannot overflow.
  312. */
  313. function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  314. require(b <= a, errorMessage);
  315. uint256 c = a - b;
  316.  
  317. return c;
  318. }
  319.  
  320. /**
  321. * @dev Returns the multiplication of two unsigned integers, reverting on
  322. * overflow.
  323. *
  324. * Counterpart to Solidity's `*` operator.
  325. *
  326. * Requirements:
  327. *
  328. * - Multiplication cannot overflow.
  329. */
  330. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  331. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  332. // benefit is lost if 'b' is also tested.
  333. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  334. if (a == 0) {
  335. return 0;
  336. }
  337.  
  338. uint256 c = a * b;
  339. require(c / a == b, "SafeMath: multiplication overflow");
  340.  
  341. return c;
  342. }
  343.  
  344. /**
  345. * @dev Returns the integer division of two unsigned integers. Reverts on
  346. * division by zero. The result is rounded towards zero.
  347. *
  348. * Counterpart to Solidity's `/` operator. Note: this function uses a
  349. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  350. * uses an invalid opcode to revert (consuming all remaining gas).
  351. *
  352. * Requirements:
  353. *
  354. * - The divisor cannot be zero.
  355. */
  356. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  357. return div(a, b, "SafeMath: division by zero");
  358. }
  359.  
  360. /**
  361. * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
  362. * division by zero. The result is rounded towards zero.
  363. *
  364. * Counterpart to Solidity's `/` operator. Note: this function uses a
  365. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  366. * uses an invalid opcode to revert (consuming all remaining gas).
  367. *
  368. * Requirements:
  369. *
  370. * - The divisor cannot be zero.
  371. */
  372. function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  373. require(b > 0, errorMessage);
  374. uint256 c = a / b;
  375. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  376.  
  377. return c;
  378. }
  379.  
  380. /**
  381. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  382. * Reverts when dividing by zero.
  383. *
  384. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  385. * opcode (which leaves remaining gas untouched) while Solidity uses an
  386. * invalid opcode to revert (consuming all remaining gas).
  387. *
  388. * Requirements:
  389. *
  390. * - The divisor cannot be zero.
  391. */
  392. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  393. return mod(a, b, "SafeMath: modulo by zero");
  394. }
  395.  
  396. /**
  397. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  398. * Reverts with custom message when dividing by zero.
  399. *
  400. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  401. * opcode (which leaves remaining gas untouched) while Solidity uses an
  402. * invalid opcode to revert (consuming all remaining gas).
  403. *
  404. * Requirements:
  405. *
  406. * - The divisor cannot be zero.
  407. */
  408. function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  409. require(b != 0, errorMessage);
  410. return a % b;
  411. }
  412. }
  413.  
  414. // File: node_modules\@openzeppelin\contracts\utils\Address.sol
  415.  
  416. // free
  417.  
  418. pragma solidity ^0.6.2;
  419.  
  420. /**
  421. * @dev Collection of functions related to the address type
  422. */
  423. library Address {
  424. /**
  425. * @dev Returns true if `account` is a contract.
  426. *
  427. * [IMPORTANT]
  428. * ====
  429. * It is unsafe to assume that an address for which this function returns
  430. * false is an externally-owned account (EOA) and not a contract.
  431. *
  432. * Among others, `isContract` will return false for the following
  433. * types of addresses:
  434. *
  435. * - an externally-owned account
  436. * - a contract in construction
  437. * - an address where a contract will be created
  438. * - an address where a contract lived, but was destroyed
  439. * ====
  440. */
  441. function isContract(address account) internal view returns (bool) {
  442. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
  443. // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
  444. // for accounts without code, i.e. `keccak256('')`
  445. bytes32 codehash;
  446. bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
  447. // solhint-disable-next-line no-inline-assembly
  448. assembly { codehash := extcodehash(account) }
  449. return (codehash != accountHash && codehash != 0x0);
  450. }
  451.  
  452. /**
  453. * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
  454. * `recipient`, forwarding all available gas and reverting on errors.
  455. *
  456. * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
  457. * of certain opcodes, possibly making contracts go over the 2300 gas limit
  458. * imposed by `transfer`, making them unable to receive funds via
  459. * `transfer`. {sendValue} removes this limitation.
  460. *
  461. * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
  462. *
  463. * IMPORTANT: because control is transferred to `recipient`, care must be
  464. * taken to not create reentrancy vulnerabilities. Consider using
  465. * {ReentrancyGuard} or the
  466. * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
  467. */
  468. function sendValue(address payable recipient, uint256 amount) internal {
  469. require(address(this).balance >= amount, "Address: insufficient balance");
  470.  
  471. // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
  472. (bool success, ) = recipient.call{ value: amount }("");
  473. require(success, "Address: unable to send value, recipient may have reverted");
  474. }
  475.  
  476. /**
  477. * @dev Performs a Solidity function call using a low level `call`. A
  478. * plain`call` is an unsafe replacement for a function call: use this
  479. * function instead.
  480. *
  481. * If `target` reverts with a revert reason, it is bubbled up by this
  482. * function (like regular Solidity function calls).
  483. *
  484. * Returns the raw returned data. To convert to the expected return value,
  485. * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
  486. *
  487. * Requirements:
  488. *
  489. * - `target` must be a contract.
  490. * - calling `target` with `data` must not revert.
  491. *
  492. * _Available since v3.1._
  493. */
  494. function functionCall(address target, bytes memory data) internal returns (bytes memory) {
  495. return functionCall(target, data, "Address: low-level call failed");
  496. }
  497.  
  498. /**
  499. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
  500. * `errorMessage` as a fallback revert reason when `target` reverts.
  501. *
  502. * _Available since v3.1._
  503. */
  504. function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
  505. return _functionCallWithValue(target, data, 0, errorMessage);
  506. }
  507.  
  508. /**
  509. * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
  510. * but also transferring `value` wei to `target`.
  511. *
  512. * Requirements:
  513. *
  514. * - the calling contract must have an ETH balance of at least `value`.
  515. * - the called Solidity function must be `payable`.
  516. *
  517. * _Available since v3.1._
  518. */
  519. function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
  520. return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
  521. }
  522.  
  523. /**
  524. * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
  525. * with `errorMessage` as a fallback revert reason when `target` reverts.
  526. *
  527. * _Available since v3.1._
  528. */
  529. function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
  530. require(address(this).balance >= value, "Address: insufficient balance for call");
  531. return _functionCallWithValue(target, data, value, errorMessage);
  532. }
  533.  
  534. function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
  535. require(isContract(target), "Address: call to non-contract");
  536.  
  537. // solhint-disable-next-line avoid-low-level-calls
  538. (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
  539. if (success) {
  540. return returndata;
  541. } else {
  542. // Look for revert reason and bubble it up if present
  543. if (returndata.length > 0) {
  544. // The easiest way to bubble the revert reason is using memory via assembly
  545.  
  546. // solhint-disable-next-line no-inline-assembly
  547. assembly {
  548. let returndata_size := mload(returndata)
  549. revert(add(32, returndata), returndata_size)
  550. }
  551. } else {
  552. revert(errorMessage);
  553. }
  554. }
  555. }
  556. }
  557.  
  558. // File: @openzeppelin\contracts\token\ERC20\ERC20.sol
  559.  
  560. // free
  561.  
  562. pragma solidity ^0.6.0;
  563.  
  564.  
  565.  
  566.  
  567.  
  568. /**
  569. * @dev Implementation of the {IERC20} interface.
  570. *
  571. * This implementation is agnostic to the way tokens are created. This means
  572. * that a supply mechanism has to be added in a derived contract using {_mint}.
  573. * For a generic mechanism see {ERC20PresetMinterPauser}.
  574. *
  575. * TIP: For a detailed writeup see our guide
  576. * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
  577. * to implement supply mechanisms].
  578. *
  579. * We have followed general OpenZeppelin guidelines: functions revert instead
  580. * of returning `false` on failure. This behavior is nonetheless conventional
  581. * and does not conflict with the expectations of ERC20 applications.
  582. *
  583. * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
  584. * This allows applications to reconstruct the allowance for all accounts just
  585. * by listening to said events. Other implementations of the EIP may not emit
  586. * these events, as it isn't required by the specification.
  587. *
  588. * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
  589. * functions have been added to mitigate the well-known issues around setting
  590. * allowances. See {IERC20-approve}.
  591. */
  592. contract ERC20 is Context, IERC20 {
  593. using SafeMath for uint256;
  594. using Address for address;
  595.  
  596. mapping (address => uint256) private _balances;
  597.  
  598. mapping (address => mapping (address => uint256)) private _allowances;
  599.  
  600. uint256 private _totalSupply;
  601.  
  602. string private _name;
  603. string private _symbol;
  604. uint8 private _decimals;
  605.  
  606. /**
  607. * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
  608. * a default value of 18.
  609. *
  610. * To select a different value for {decimals}, use {_setupDecimals}.
  611. *
  612. * All three of these values are immutable: they can only be set once during
  613. * construction.
  614. */
  615. constructor (string memory name, string memory symbol) public {
  616. _name = name;
  617. _symbol = symbol;
  618. _decimals = 18;
  619. }
  620.  
  621. /**
  622. * @dev Returns the name of the token.
  623. */
  624. function name() public view returns (string memory) {
  625. return _name;
  626. }
  627.  
  628. /**
  629. * @dev Returns the symbol of the token, usually a shorter version of the
  630. * name.
  631. */
  632. function symbol() public view returns (string memory) {
  633. return _symbol;
  634. }
  635.  
  636. /**
  637. * @dev Returns the number of decimals used to get its user representation.
  638. * For example, if `decimals` equals `2`, a balance of `505` tokens should
  639. * be displayed to a user as `5,05` (`505 / 10 ** 2`).
  640. *
  641. * Tokens usually opt for a value of 18, imitating the relationship between
  642. * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
  643. * called.
  644. *
  645. * NOTE: This information is only used for _display_ purposes: it in
  646. * no way affects any of the arithmetic of the contract, including
  647. * {IERC20-balanceOf} and {IERC20-transfer}.
  648. */
  649. function decimals() public view returns (uint8) {
  650. return _decimals;
  651. }
  652.  
  653. /**
  654. * @dev See {IERC20-totalSupply}.
  655. */
  656. function totalSupply() public view override returns (uint256) {
  657. return _totalSupply;
  658. }
  659.  
  660. /**
  661. * @dev See {IERC20-balanceOf}.
  662. */
  663. function balanceOf(address account) public view override returns (uint256) {
  664. return _balances[account];
  665. }
  666.  
  667. /**
  668. * @dev See {IERC20-transfer}.
  669. *
  670. * Requirements:
  671. *
  672. * - `recipient` cannot be the zero address.
  673. * - the caller must have a balance of at least `amount`.
  674. */
  675. function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
  676. _transfer(_msgSender(), recipient, amount);
  677. return true;
  678. }
  679.  
  680. /**
  681. * @dev See {IERC20-allowance}.
  682. */
  683. function allowance(address owner, address spender) public view virtual override returns (uint256) {
  684. return _allowances[owner][spender];
  685. }
  686.  
  687. /**
  688. * @dev See {IERC20-approve}.
  689. *
  690. * Requirements:
  691. *
  692. * - `spender` cannot be the zero address.
  693. */
  694. function approve(address spender, uint256 amount) public virtual override returns (bool) {
  695. _approve(_msgSender(), spender, amount);
  696. return true;
  697. }
  698.  
  699. /**
  700. * @dev See {IERC20-transferFrom}.
  701. *
  702. * Emits an {Approval} event indicating the updated allowance. This is not
  703. * required by the EIP. See the note at the beginning of {ERC20};
  704. *
  705. * Requirements:
  706. * - `sender` and `recipient` cannot be the zero address.
  707. * - `sender` must have a balance of at least `amount`.
  708. * - the caller must have allowance for ``sender``'s tokens of at least
  709. * `amount`.
  710. */
  711. function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
  712. _transfer(sender, recipient, amount);
  713. _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
  714. return true;
  715. }
  716.  
  717. /**
  718. * @dev Atomically increases the allowance granted to `spender` by the caller.
  719. *
  720. * This is an alternative to {approve} that can be used as a mitigation for
  721. * problems described in {IERC20-approve}.
  722. *
  723. * Emits an {Approval} event indicating the updated allowance.
  724. *
  725. * Requirements:
  726. *
  727. * - `spender` cannot be the zero address.
  728. */
  729. function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
  730. _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
  731. return true;
  732. }
  733.  
  734. /**
  735. * @dev Atomically decreases the allowance granted to `spender` by the caller.
  736. *
  737. * This is an alternative to {approve} that can be used as a mitigation for
  738. * problems described in {IERC20-approve}.
  739. *
  740. * Emits an {Approval} event indicating the updated allowance.
  741. *
  742. * Requirements:
  743. *
  744. * - `spender` cannot be the zero address.
  745. * - `spender` must have allowance for the caller of at least
  746. * `subtractedValue`.
  747. */
  748. function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
  749. _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
  750. return true;
  751. }
  752.  
  753. /**
  754. * @dev Moves tokens `amount` from `sender` to `recipient`.
  755. *
  756. * This is internal function is equivalent to {transfer}, and can be used to
  757. * e.g. implement automatic token fees, slashing mechanisms, etc.
  758. *
  759. * Emits a {Transfer} event.
  760. *
  761. * Requirements:
  762. *
  763. * - `sender` cannot be the zero address.
  764. * - `recipient` cannot be the zero address.
  765. * - `sender` must have a balance of at least `amount`.
  766. */
  767. function _transfer(address sender, address recipient, uint256 amount) internal virtual {
  768. require(sender != address(0), "ERC20: transfer from the zero address");
  769. require(recipient != address(0), "ERC20: transfer to the zero address");
  770.  
  771. _beforeTokenTransfer(sender, recipient, amount);
  772.  
  773. _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
  774. _balances[recipient] = _balances[recipient].add(amount);
  775. emit Transfer(sender, recipient, amount);
  776. }
  777.  
  778. /** @dev Creates `amount` tokens and assigns them to `account`, increasing
  779. * the total supply.
  780. *
  781. * Emits a {Transfer} event with `from` set to the zero address.
  782. *
  783. * Requirements
  784. *
  785. * - `to` cannot be the zero address.
  786. */
  787. function _mint(address account, uint256 amount) internal virtual {
  788. require(account != address(0), "ERC20: mint to the zero address");
  789.  
  790. _beforeTokenTransfer(address(0), account, amount);
  791.  
  792. _totalSupply = _totalSupply.add(amount);
  793. _balances[account] = _balances[account].add(amount);
  794. emit Transfer(address(0), account, amount);
  795. }
  796.  
  797. /**
  798. * @dev Destroys `amount` tokens from `account`, reducing the
  799. * total supply.
  800. *
  801. * Emits a {Transfer} event with `to` set to the zero address.
  802. *
  803. * Requirements
  804. *
  805. * - `account` cannot be the zero address.
  806. * - `account` must have at least `amount` tokens.
  807. */
  808. function _burn(address account, uint256 amount) internal virtual {
  809. require(account != address(0), "ERC20: burn from the zero address");
  810.  
  811. _beforeTokenTransfer(account, address(0), amount);
  812.  
  813. _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
  814. _totalSupply = _totalSupply.sub(amount);
  815. emit Transfer(account, address(0), amount);
  816. }
  817.  
  818. /**
  819. * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
  820. *
  821. * This is internal function is equivalent to `approve`, and can be used to
  822. * e.g. set automatic allowances for certain subsystems, etc.
  823. *
  824. * Emits an {Approval} event.
  825. *
  826. * Requirements:
  827. *
  828. * - `owner` cannot be the zero address.
  829. * - `spender` cannot be the zero address.
  830. */
  831. function _approve(address owner, address spender, uint256 amount) internal virtual {
  832. require(owner != address(0), "ERC20: approve from the zero address");
  833. require(spender != address(0), "ERC20: approve to the zero address");
  834.  
  835. _allowances[owner][spender] = amount;
  836. emit Approval(owner, spender, amount);
  837. }
  838.  
  839. /**
  840. * @dev Sets {decimals} to a value other than the default one of 18.
  841. *
  842. * WARNING: This function should only be called from the constructor. Most
  843. * applications that interact with token contracts will not expect
  844. * {decimals} to ever change, and may work incorrectly if it does.
  845. */
  846. function _setupDecimals(uint8 decimals_) internal {
  847. _decimals = decimals_;
  848. }
  849.  
  850. /**
  851. * @dev Hook that is called before any transfer of tokens. This includes
  852. * minting and burning.
  853. *
  854. * Calling conditions:
  855. *
  856. * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
  857. * will be to transferred to `to`.
  858. * - when `from` is zero, `amount` tokens will be minted for `to`.
  859. * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
  860. * - `from` and `to` are never both zero.
  861. *
  862. * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
  863. */
  864. function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
  865. }
  866.  
  867. // File: @openzeppelin\contracts\math\SafeMath.sol
  868.  
  869. // free
  870.  
  871. pragma solidity ^0.6.0;
  872.  
  873. /**
  874. * @dev Wrappers over Solidity's arithmetic operations with added overflow
  875. * checks.
  876. *
  877. * Arithmetic operations in Solidity wrap on overflow. This can easily result
  878. * in bugs, because programmers usually assume that an overflow raises an
  879. * error, which is the standard behavior in high level programming languages.
  880. * `SafeMath` restores this intuition by reverting the transaction when an
  881. * operation overflows.
  882. *
  883. * Using this library instead of the unchecked operations eliminates an entire
  884. * class of bugs, so it's recommended to use it always.
  885. */
  886. library SafeMath {
  887. /**
  888. * @dev Returns the addition of two unsigned integers, reverting on
  889. * overflow.
  890. *
  891. * Counterpart to Solidity's `+` operator.
  892. *
  893. * Requirements:
  894. *
  895. * - Addition cannot overflow.
  896. */
  897. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  898. uint256 c = a + b;
  899. require(c >= a, "SafeMath: addition overflow");
  900.  
  901. return c;
  902. }
  903.  
  904. /**
  905. * @dev Returns the subtraction of two unsigned integers, reverting on
  906. * overflow (when the result is negative).
  907. *
  908. * Counterpart to Solidity's `-` operator.
  909. *
  910. * Requirements:
  911. *
  912. * - Subtraction cannot overflow.
  913. */
  914. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  915. return sub(a, b, "SafeMath: subtraction overflow");
  916. }
  917.  
  918. /**
  919. * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
  920. * overflow (when the result is negative).
  921. *
  922. * Counterpart to Solidity's `-` operator.
  923. *
  924. * Requirements:
  925. *
  926. * - Subtraction cannot overflow.
  927. */
  928. function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  929. require(b <= a, errorMessage);
  930. uint256 c = a - b;
  931.  
  932. return c;
  933. }
  934.  
  935. /**
  936. * @dev Returns the multiplication of two unsigned integers, reverting on
  937. * overflow.
  938. *
  939. * Counterpart to Solidity's `*` operator.
  940. *
  941. * Requirements:
  942. *
  943. * - Multiplication cannot overflow.
  944. */
  945. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  946. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  947. // benefit is lost if 'b' is also tested.
  948. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  949. if (a == 0) {
  950. return 0;
  951. }
  952.  
  953. uint256 c = a * b;
  954. require(c / a == b, "SafeMath: multiplication overflow");
  955.  
  956. return c;
  957. }
  958.  
  959. /**
  960. * @dev Returns the integer division of two unsigned integers. Reverts on
  961. * division by zero. The result is rounded towards zero.
  962. *
  963. * Counterpart to Solidity's `/` operator. Note: this function uses a
  964. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  965. * uses an invalid opcode to revert (consuming all remaining gas).
  966. *
  967. * Requirements:
  968. *
  969. * - The divisor cannot be zero.
  970. */
  971. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  972. return div(a, b, "SafeMath: division by zero");
  973. }
  974.  
  975. /**
  976. * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
  977. * division by zero. The result is rounded towards zero.
  978. *
  979. * Counterpart to Solidity's `/` operator. Note: this function uses a
  980. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  981. * uses an invalid opcode to revert (consuming all remaining gas).
  982. *
  983. * Requirements:
  984. *
  985. * - The divisor cannot be zero.
  986. */
  987. function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  988. require(b > 0, errorMessage);
  989. uint256 c = a / b;
  990. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  991.  
  992. return c;
  993. }
  994.  
  995. /**
  996. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  997. * Reverts when dividing by zero.
  998. *
  999. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  1000. * opcode (which leaves remaining gas untouched) while Solidity uses an
  1001. * invalid opcode to revert (consuming all remaining gas).
  1002. *
  1003. * Requirements:
  1004. *
  1005. * - The divisor cannot be zero.
  1006. */
  1007. function mod(uint256 a, uint256 b) internal pure returns (uint256) {
  1008. return mod(a, b, "SafeMath: modulo by zero");
  1009. }
  1010.  
  1011. /**
  1012. * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
  1013. * Reverts with custom message when dividing by zero.
  1014. *
  1015. * Counterpart to Solidity's `%` operator. This function uses a `revert`
  1016. * opcode (which leaves remaining gas untouched) while Solidity uses an
  1017. * invalid opcode to revert (consuming all remaining gas).
  1018. *
  1019. * Requirements:
  1020. *
  1021. * - The divisor cannot be zero.
  1022. */
  1023. function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
  1024. require(b != 0, errorMessage);
  1025. return a % b;
  1026. }
  1027. }
  1028.  
  1029. // File: @openzeppelin\contracts\math\SignedSafeMath.sol
  1030.  
  1031. // free
  1032.  
  1033. pragma solidity ^0.6.0;
  1034.  
  1035. /**
  1036. * @title SignedSafeMath
  1037. * @dev Signed math operations with safety checks that revert on error.
  1038. */
  1039. library SignedSafeMath {
  1040. int256 constant private _INT256_MIN = -2**255;
  1041.  
  1042. /**
  1043. * @dev Returns the multiplication of two signed integers, reverting on
  1044. * overflow.
  1045. *
  1046. * Counterpart to Solidity's `*` operator.
  1047. *
  1048. * Requirements:
  1049. *
  1050. * - Multiplication cannot overflow.
  1051. */
  1052. function mul(int256 a, int256 b) internal pure returns (int256) {
  1053. // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
  1054. // benefit is lost if 'b' is also tested.
  1055. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
  1056. if (a == 0) {
  1057. return 0;
  1058. }
  1059.  
  1060. require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
  1061.  
  1062. int256 c = a * b;
  1063. require(c / a == b, "SignedSafeMath: multiplication overflow");
  1064.  
  1065. return c;
  1066. }
  1067.  
  1068. /**
  1069. * @dev Returns the integer division of two signed integers. Reverts on
  1070. * division by zero. The result is rounded towards zero.
  1071. *
  1072. * Counterpart to Solidity's `/` operator. Note: this function uses a
  1073. * `revert` opcode (which leaves remaining gas untouched) while Solidity
  1074. * uses an invalid opcode to revert (consuming all remaining gas).
  1075. *
  1076. * Requirements:
  1077. *
  1078. * - The divisor cannot be zero.
  1079. */
  1080. function div(int256 a, int256 b) internal pure returns (int256) {
  1081. require(b != 0, "SignedSafeMath: division by zero");
  1082. require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
  1083.  
  1084. int256 c = a / b;
  1085.  
  1086. return c;
  1087. }
  1088.  
  1089. /**
  1090. * @dev Returns the subtraction of two signed integers, reverting on
  1091. * overflow.
  1092. *
  1093. * Counterpart to Solidity's `-` operator.
  1094. *
  1095. * Requirements:
  1096. *
  1097. * - Subtraction cannot overflow.
  1098. */
  1099. function sub(int256 a, int256 b) internal pure returns (int256) {
  1100. int256 c = a - b;
  1101. require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
  1102.  
  1103. return c;
  1104. }
  1105.  
  1106. /**
  1107. * @dev Returns the addition of two signed integers, reverting on
  1108. * overflow.
  1109. *
  1110. * Counterpart to Solidity's `+` operator.
  1111. *
  1112. * Requirements:
  1113. *
  1114. * - Addition cannot overflow.
  1115. */
  1116. function add(int256 a, int256 b) internal pure returns (int256) {
  1117. int256 c = a + b;
  1118. require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
  1119.  
  1120. return c;
  1121. }
  1122. }
  1123.  
  1124. // File: contracts\interfaces\IController.sol
  1125.  
  1126. /*
  1127. Copyright 2020 Set Labs Inc.
  1128.  
  1129. Licensed under the Apache License, Version 2.0 (the "License");
  1130. you may not use this file except in compliance with the License.
  1131. You may obtain a copy of the License at
  1132.  
  1133. http://www.apache.org/licenses/LICENSE-2.0
  1134.  
  1135. Unless required by applicable law or agreed to in writing, software
  1136. distributed under the License is distributed on an "AS IS" BASIS,
  1137. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1138. See the License for the specific language governing permissions and
  1139. limitations under the License.
  1140.  
  1141. SPDX-License-Identifier: Apache License, Version 2.0
  1142. */
  1143. pragma solidity 0.6.10;
  1144.  
  1145. interface IController {
  1146. function addSet(address _setToken) external;
  1147. function feeRecipient() external view returns(address);
  1148. function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
  1149. function isModule(address _module) external view returns(bool);
  1150. function isSet(address _setToken) external view returns(bool);
  1151. function isSystemContract(address _contractAddress) external view returns (bool);
  1152. function resourceId(uint256 _id) external view returns(address);
  1153. }
  1154.  
  1155. // File: contracts\interfaces\IModule.sol
  1156.  
  1157. /*
  1158. Copyright 2020 Set Labs Inc.
  1159.  
  1160. Licensed under the Apache License, Version 2.0 (the "License");
  1161. you may not use this file except in compliance with the License.
  1162. You may obtain a copy of the License at
  1163.  
  1164. http://www.apache.org/licenses/LICENSE-2.0
  1165.  
  1166. Unless required by applicable law or agreed to in writing, software
  1167. distributed under the License is distributed on an "AS IS" BASIS,
  1168. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1169. See the License for the specific language governing permissions and
  1170. limitations under the License.
  1171.  
  1172. SPDX-License-Identifier: Apache License, Version 2.0
  1173. */
  1174. pragma solidity 0.6.10;
  1175.  
  1176.  
  1177. /**
  1178. * @title IModule
  1179. * @author Set Protocol
  1180. *
  1181. * Interface for interacting with Modules.
  1182. */
  1183. interface IModule {
  1184. /**
  1185. * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
  1186. * in case checks need to be made or state needs to be cleared.
  1187. */
  1188. function removeModule() external;
  1189. }
  1190.  
  1191. // File: @openzeppelin\contracts\token\ERC20\IERC20.sol
  1192.  
  1193. // free
  1194.  
  1195. pragma solidity ^0.6.0;
  1196.  
  1197. /**
  1198. * @dev Interface of the ERC20 standard as defined in the EIP.
  1199. */
  1200. interface IERC20 {
  1201. /**
  1202. * @dev Returns the amount of tokens in existence.
  1203. */
  1204. function totalSupply() external view returns (uint256);
  1205.  
  1206. /**
  1207. * @dev Returns the amount of tokens owned by `account`.
  1208. */
  1209. function balanceOf(address account) external view returns (uint256);
  1210.  
  1211. /**
  1212. * @dev Moves `amount` tokens from the caller's account to `recipient`.
  1213. *
  1214. * Returns a boolean value indicating whether the operation succeeded.
  1215. *
  1216. * Emits a {Transfer} event.
  1217. */
  1218. function transfer(address recipient, uint256 amount) external returns (bool);
  1219.  
  1220. /**
  1221. * @dev Returns the remaining number of tokens that `spender` will be
  1222. * allowed to spend on behalf of `owner` through {transferFrom}. This is
  1223. * zero by default.
  1224. *
  1225. * This value changes when {approve} or {transferFrom} are called.
  1226. */
  1227. function allowance(address owner, address spender) external view returns (uint256);
  1228.  
  1229. /**
  1230. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
  1231. *
  1232. * Returns a boolean value indicating whether the operation succeeded.
  1233. *
  1234. * IMPORTANT: Beware that changing an allowance with this method brings the risk
  1235. * that someone may use both the old and the new allowance by unfortunate
  1236. * transaction ordering. One possible solution to mitigate this race
  1237. * condition is to first reduce the spender's allowance to 0 and set the
  1238. * desired value afterwards:
  1239. * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
  1240. *
  1241. * Emits an {Approval} event.
  1242. */
  1243. function approve(address spender, uint256 amount) external returns (bool);
  1244.  
  1245. /**
  1246. * @dev Moves `amount` tokens from `sender` to `recipient` using the
  1247. * allowance mechanism. `amount` is then deducted from the caller's
  1248. * allowance.
  1249. *
  1250. * Returns a boolean value indicating whether the operation succeeded.
  1251. *
  1252. * Emits a {Transfer} event.
  1253. */
  1254. function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
  1255.  
  1256. /**
  1257. * @dev Emitted when `value` tokens are moved from one account (`from`) to
  1258. * another (`to`).
  1259. *
  1260. * Note that `value` may be zero.
  1261. */
  1262. event Transfer(address indexed from, address indexed to, uint256 value);
  1263.  
  1264. /**
  1265. * @dev Emitted when the allowance of a `spender` for an `owner` is set by
  1266. * a call to {approve}. `value` is the new allowance.
  1267. */
  1268. event Approval(address indexed owner, address indexed spender, uint256 value);
  1269. }
  1270.  
  1271. // File: contracts\interfaces\ISetToken.sol
  1272.  
  1273. /*
  1274. Copyright 2020 Set Labs Inc.
  1275.  
  1276. Licensed under the Apache License, Version 2.0 (the "License");
  1277. you may not use this file except in compliance with the License.
  1278. You may obtain a copy of the License at
  1279.  
  1280. http://www.apache.org/licenses/LICENSE-2.0
  1281.  
  1282. Unless required by applicable law or agreed to in writing, software
  1283. distributed under the License is distributed on an "AS IS" BASIS,
  1284. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1285. See the License for the specific language governing permissions and
  1286. limitations under the License.
  1287.  
  1288. SPDX-License-Identifier: Apache License, Version 2.0
  1289. */
  1290. pragma solidity 0.6.10;
  1291. pragma experimental "ABIEncoderV2";
  1292.  
  1293.  
  1294. /**
  1295. * @title ISetToken
  1296. * @author Set Protocol
  1297. *
  1298. * Interface for operating with SetTokens.
  1299. */
  1300. interface ISetToken is IERC20 {
  1301.  
  1302. /* ============ Enums ============ */
  1303.  
  1304. enum ModuleState {
  1305. NONE,
  1306. PENDING,
  1307. INITIALIZED
  1308. }
  1309.  
  1310. /* ============ Structs ============ */
  1311. /**
  1312. * The base definition of a SetToken Position
  1313. *
  1314. * @param component Address of token in the Position
  1315. * @param module If not in default state, the address of associated module
  1316. * @param unit Each unit is the # of components per 10^18 of a SetToken
  1317. * @param positionState Position ENUM. Default is 0; External is 1
  1318. * @param data Arbitrary data
  1319. */
  1320. struct Position {
  1321. address component;
  1322. address module;
  1323. int256 unit;
  1324. uint8 positionState;
  1325. bytes data;
  1326. }
  1327.  
  1328. /**
  1329. * A struct that stores a component's cash position details and external positions
  1330. * This data structure allows O(1) access to a component's cash position units and
  1331. * virtual units.
  1332. *
  1333. * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
  1334. * updating all units at once via the position multiplier. Virtual units are achieved
  1335. * by dividing a "real" value by the "positionMultiplier"
  1336. * @param componentIndex
  1337. * @param externalPositionModules List of external modules attached to each external position. Each module
  1338. * maps to an external position
  1339. * @param externalPositions Mapping of module => ExternalPosition struct for a given component
  1340. */
  1341. struct ComponentPosition {
  1342. int256 virtualUnit;
  1343. address[] externalPositionModules;
  1344. mapping(address => ExternalPosition) externalPositions;
  1345. }
  1346.  
  1347. /**
  1348. * A struct that stores a component's external position details including virtual unit and any
  1349. * auxiliary data.
  1350. *
  1351. * @param virtualUnit Virtual value of a component's EXTERNAL position.
  1352. * @param data Arbitrary data
  1353. */
  1354. struct ExternalPosition {
  1355. int256 virtualUnit;
  1356. bytes data;
  1357. }
  1358.  
  1359.  
  1360. /* ============ Functions ============ */
  1361.  
  1362. function addComponent(address _component) external;
  1363. function removeComponent(address _component) external;
  1364. function editDefaultPositionUnit(address _component, int256 _realUnit) external;
  1365. function addExternalPositionModule(address _component, address _positionModule) external;
  1366. function removeExternalPositionModule(address _component, address _positionModule) external;
  1367. function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
  1368. function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
  1369.  
  1370. function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
  1371.  
  1372. function editPositionMultiplier(int256 _newMultiplier) external;
  1373.  
  1374. function mint(address _account, uint256 _quantity) external;
  1375. function burn(address _account, uint256 _quantity) external;
  1376.  
  1377. function lock() external;
  1378. function unlock() external;
  1379.  
  1380. function addModule(address _module) external;
  1381. function removeModule(address _module) external;
  1382. function initializeModule() external;
  1383.  
  1384. function setManager(address _manager) external;
  1385.  
  1386. function manager() external view returns (address);
  1387. function moduleStates(address _module) external view returns (ModuleState);
  1388. function getModules() external view returns (address[] memory);
  1389.  
  1390. function getDefaultPositionRealUnit(address _component) external view returns(int256);
  1391. function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
  1392. function getComponents() external view returns(address[] memory);
  1393. function getExternalPositionModules(address _component) external view returns(address[] memory);
  1394. function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
  1395. function isExternalPositionModule(address _component, address _module) external view returns(bool);
  1396. function isComponent(address _component) external view returns(bool);
  1397.  
  1398. function positionMultiplier() external view returns (int256);
  1399. function getPositions() external view returns (Position[] memory);
  1400. function getTotalComponentRealUnits(address _component) external view returns(int256);
  1401.  
  1402. function isInitializedModule(address _module) external view returns(bool);
  1403. function isPendingModule(address _module) external view returns(bool);
  1404. function isLocked() external view returns (bool);
  1405. }
  1406.  
  1407. // File: @openzeppelin\contracts\utils\SafeCast.sol
  1408.  
  1409. // free
  1410.  
  1411. pragma solidity ^0.6.0;
  1412.  
  1413.  
  1414. /**
  1415. * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
  1416. * checks.
  1417. *
  1418. * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
  1419. * easily result in undesired exploitation or bugs, since developers usually
  1420. * assume that overflows raise errors. `SafeCast` restores this intuition by
  1421. * reverting the transaction when such an operation overflows.
  1422. *
  1423. * Using this library instead of the unchecked operations eliminates an entire
  1424. * class of bugs, so it's recommended to use it always.
  1425. *
  1426. * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
  1427. * all math on `uint256` and `int256` and then downcasting.
  1428. */
  1429. library SafeCast {
  1430.  
  1431. /**
  1432. * @dev Returns the downcasted uint128 from uint256, reverting on
  1433. * overflow (when the input is greater than largest uint128).
  1434. *
  1435. * Counterpart to Solidity's `uint128` operator.
  1436. *
  1437. * Requirements:
  1438. *
  1439. * - input must fit into 128 bits
  1440. */
  1441. function toUint128(uint256 value) internal pure returns (uint128) {
  1442. require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
  1443. return uint128(value);
  1444. }
  1445.  
  1446. /**
  1447. * @dev Returns the downcasted uint64 from uint256, reverting on
  1448. * overflow (when the input is greater than largest uint64).
  1449. *
  1450. * Counterpart to Solidity's `uint64` operator.
  1451. *
  1452. * Requirements:
  1453. *
  1454. * - input must fit into 64 bits
  1455. */
  1456. function toUint64(uint256 value) internal pure returns (uint64) {
  1457. require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
  1458. return uint64(value);
  1459. }
  1460.  
  1461. /**
  1462. * @dev Returns the downcasted uint32 from uint256, reverting on
  1463. * overflow (when the input is greater than largest uint32).
  1464. *
  1465. * Counterpart to Solidity's `uint32` operator.
  1466. *
  1467. * Requirements:
  1468. *
  1469. * - input must fit into 32 bits
  1470. */
  1471. function toUint32(uint256 value) internal pure returns (uint32) {
  1472. require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
  1473. return uint32(value);
  1474. }
  1475.  
  1476. /**
  1477. * @dev Returns the downcasted uint16 from uint256, reverting on
  1478. * overflow (when the input is greater than largest uint16).
  1479. *
  1480. * Counterpart to Solidity's `uint16` operator.
  1481. *
  1482. * Requirements:
  1483. *
  1484. * - input must fit into 16 bits
  1485. */
  1486. function toUint16(uint256 value) internal pure returns (uint16) {
  1487. require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
  1488. return uint16(value);
  1489. }
  1490.  
  1491. /**
  1492. * @dev Returns the downcasted uint8 from uint256, reverting on
  1493. * overflow (when the input is greater than largest uint8).
  1494. *
  1495. * Counterpart to Solidity's `uint8` operator.
  1496. *
  1497. * Requirements:
  1498. *
  1499. * - input must fit into 8 bits.
  1500. */
  1501. function toUint8(uint256 value) internal pure returns (uint8) {
  1502. require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
  1503. return uint8(value);
  1504. }
  1505.  
  1506. /**
  1507. * @dev Converts a signed int256 into an unsigned uint256.
  1508. *
  1509. * Requirements:
  1510. *
  1511. * - input must be greater than or equal to 0.
  1512. */
  1513. function toUint256(int256 value) internal pure returns (uint256) {
  1514. require(value >= 0, "SafeCast: value must be positive");
  1515. return uint256(value);
  1516. }
  1517.  
  1518. /**
  1519. * @dev Returns the downcasted int128 from int256, reverting on
  1520. * overflow (when the input is less than smallest int128 or
  1521. * greater than largest int128).
  1522. *
  1523. * Counterpart to Solidity's `int128` operator.
  1524. *
  1525. * Requirements:
  1526. *
  1527. * - input must fit into 128 bits
  1528. *
  1529. * _Available since v3.1._
  1530. */
  1531. function toInt128(int256 value) internal pure returns (int128) {
  1532. require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
  1533. return int128(value);
  1534. }
  1535.  
  1536. /**
  1537. * @dev Returns the downcasted int64 from int256, reverting on
  1538. * overflow (when the input is less than smallest int64 or
  1539. * greater than largest int64).
  1540. *
  1541. * Counterpart to Solidity's `int64` operator.
  1542. *
  1543. * Requirements:
  1544. *
  1545. * - input must fit into 64 bits
  1546. *
  1547. * _Available since v3.1._
  1548. */
  1549. function toInt64(int256 value) internal pure returns (int64) {
  1550. require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
  1551. return int64(value);
  1552. }
  1553.  
  1554. /**
  1555. * @dev Returns the downcasted int32 from int256, reverting on
  1556. * overflow (when the input is less than smallest int32 or
  1557. * greater than largest int32).
  1558. *
  1559. * Counterpart to Solidity's `int32` operator.
  1560. *
  1561. * Requirements:
  1562. *
  1563. * - input must fit into 32 bits
  1564. *
  1565. * _Available since v3.1._
  1566. */
  1567. function toInt32(int256 value) internal pure returns (int32) {
  1568. require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
  1569. return int32(value);
  1570. }
  1571.  
  1572. /**
  1573. * @dev Returns the downcasted int16 from int256, reverting on
  1574. * overflow (when the input is less than smallest int16 or
  1575. * greater than largest int16).
  1576. *
  1577. * Counterpart to Solidity's `int16` operator.
  1578. *
  1579. * Requirements:
  1580. *
  1581. * - input must fit into 16 bits
  1582. *
  1583. * _Available since v3.1._
  1584. */
  1585. function toInt16(int256 value) internal pure returns (int16) {
  1586. require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
  1587. return int16(value);
  1588. }
  1589.  
  1590. /**
  1591. * @dev Returns the downcasted int8 from int256, reverting on
  1592. * overflow (when the input is less than smallest int8 or
  1593. * greater than largest int8).
  1594. *
  1595. * Counterpart to Solidity's `int8` operator.
  1596. *
  1597. * Requirements:
  1598. *
  1599. * - input must fit into 8 bits.
  1600. *
  1601. * _Available since v3.1._
  1602. */
  1603. function toInt8(int256 value) internal pure returns (int8) {
  1604. require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
  1605. return int8(value);
  1606. }
  1607.  
  1608. /**
  1609. * @dev Converts an unsigned uint256 into a signed int256.
  1610. *
  1611. * Requirements:
  1612. *
  1613. * - input must be less than or equal to maxInt256.
  1614. */
  1615. function toInt256(uint256 value) internal pure returns (int256) {
  1616. require(value < 2**255, "SafeCast: value doesn't fit in an int256");
  1617. return int256(value);
  1618. }
  1619. }
  1620.  
  1621. // File: contracts\lib\PreciseUnitMath.sol
  1622.  
  1623. /*
  1624. Copyright 2020 Set Labs Inc.
  1625.  
  1626. Licensed under the Apache License, Version 2.0 (the "License");
  1627. you may not use this file except in compliance with the License.
  1628. You may obtain a copy of the License at
  1629.  
  1630. http://www.apache.org/licenses/LICENSE-2.0
  1631.  
  1632. Unless required by applicable law or agreed to in writing, software
  1633. distributed under the License is distributed on an "AS IS" BASIS,
  1634. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1635. See the License for the specific language governing permissions and
  1636. limitations under the License.
  1637.  
  1638. SPDX-License-Identifier: Apache License, Version 2.0
  1639. */
  1640.  
  1641. pragma solidity 0.6.10;
  1642. pragma experimental ABIEncoderV2;
  1643.  
  1644.  
  1645.  
  1646.  
  1647. /**
  1648. * @title PreciseUnitMath
  1649. * @author Set Protocol
  1650. *
  1651. * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
  1652. * dYdX's BaseMath library.
  1653. *
  1654. * CHANGELOG:
  1655. * - 9/21/20: Added safePower function
  1656. */
  1657. library PreciseUnitMath {
  1658. using SafeMath for uint256;
  1659. using SignedSafeMath for int256;
  1660.  
  1661. // The number One in precise units.
  1662. uint256 constant internal PRECISE_UNIT = 10 ** 18;
  1663. int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
  1664.  
  1665. // Max unsigned integer value
  1666. uint256 constant internal MAX_UINT_256 = type(uint256).max;
  1667. // Max and min signed integer value
  1668. int256 constant internal MAX_INT_256 = type(int256).max;
  1669. int256 constant internal MIN_INT_256 = type(int256).min;
  1670.  
  1671. /**
  1672. * @dev Getter function since constants can't be read directly from libraries.
  1673. */
  1674. function preciseUnit() internal pure returns (uint256) {
  1675. return PRECISE_UNIT;
  1676. }
  1677.  
  1678. /**
  1679. * @dev Getter function since constants can't be read directly from libraries.
  1680. */
  1681. function preciseUnitInt() internal pure returns (int256) {
  1682. return PRECISE_UNIT_INT;
  1683. }
  1684.  
  1685. /**
  1686. * @dev Getter function since constants can't be read directly from libraries.
  1687. */
  1688. function maxUint256() internal pure returns (uint256) {
  1689. return MAX_UINT_256;
  1690. }
  1691.  
  1692. /**
  1693. * @dev Getter function since constants can't be read directly from libraries.
  1694. */
  1695. function maxInt256() internal pure returns (int256) {
  1696. return MAX_INT_256;
  1697. }
  1698.  
  1699. /**
  1700. * @dev Getter function since constants can't be read directly from libraries.
  1701. */
  1702. function minInt256() internal pure returns (int256) {
  1703. return MIN_INT_256;
  1704. }
  1705.  
  1706. /**
  1707. * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
  1708. * of a number with 18 decimals precision.
  1709. */
  1710. function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
  1711. return a.mul(b).div(PRECISE_UNIT);
  1712. }
  1713.  
  1714. /**
  1715. * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
  1716. * significand of a number with 18 decimals precision.
  1717. */
  1718. function preciseMul(int256 a, int256 b) internal pure returns (int256) {
  1719. return a.mul(b).div(PRECISE_UNIT_INT);
  1720. }
  1721.  
  1722. /**
  1723. * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
  1724. * of a number with 18 decimals precision.
  1725. */
  1726. function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
  1727. if (a == 0 || b == 0) {
  1728. return 0;
  1729. }
  1730. return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
  1731. }
  1732.  
  1733. /**
  1734. * @dev Divides value a by value b (result is rounded down).
  1735. */
  1736. function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
  1737. return a.mul(PRECISE_UNIT).div(b);
  1738. }
  1739.  
  1740.  
  1741. /**
  1742. * @dev Divides value a by value b (result is rounded towards 0).
  1743. */
  1744. function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
  1745. return a.mul(PRECISE_UNIT_INT).div(b);
  1746. }
  1747.  
  1748. /**
  1749. * @dev Divides value a by value b (result is rounded up or away from 0).
  1750. */
  1751. function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
  1752. require(b != 0, "Cant divide by 0");
  1753.  
  1754. return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
  1755. }
  1756.  
  1757. /**
  1758. * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
  1759. */
  1760. function divDown(int256 a, int256 b) internal pure returns (int256) {
  1761. require(b != 0, "Cant divide by 0");
  1762. require(a != MIN_INT_256 || b != -1, "Invalid input");
  1763.  
  1764. int256 result = a.div(b);
  1765. if (a ^ b < 0 && a % b != 0) {
  1766. result -= 1;
  1767. }
  1768.  
  1769. return result;
  1770. }
  1771.  
  1772. /**
  1773. * @dev Multiplies value a by value b where rounding is towards the lesser number.
  1774. * (positive values are rounded towards zero and negative values are rounded away from 0).
  1775. */
  1776. function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
  1777. return divDown(a.mul(b), PRECISE_UNIT_INT);
  1778. }
  1779.  
  1780. /**
  1781. * @dev Divides value a by value b where rounding is towards the lesser number.
  1782. * (positive values are rounded towards zero and negative values are rounded away from 0).
  1783. */
  1784. function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
  1785. return divDown(a.mul(PRECISE_UNIT_INT), b);
  1786. }
  1787.  
  1788. /**
  1789. * @dev Performs the power on a specified value, reverts on overflow.
  1790. */
  1791. function safePower(
  1792. uint256 a,
  1793. uint256 pow
  1794. )
  1795. internal
  1796. pure
  1797. returns (uint256)
  1798. {
  1799. require(a > 0, "Value must be positive");
  1800.  
  1801. uint256 result = 1;
  1802. for (uint256 i = 0; i < pow; i++){
  1803. uint256 previousResult = result;
  1804.  
  1805. // Using safemath multiplication prevents overflows
  1806. result = previousResult.mul(a);
  1807. }
  1808.  
  1809. return result;
  1810. }
  1811. }
  1812.  
  1813. // File: contracts\protocol\lib\Position.sol
  1814.  
  1815. /*
  1816. Copyright 2020 Set Labs Inc.
  1817.  
  1818. Licensed under the Apache License, Version 2.0 (the "License");
  1819. you may not use this file except in compliance with the License.
  1820. You may obtain a copy of the License at
  1821.  
  1822. http://www.apache.org/licenses/LICENSE-2.0
  1823.  
  1824. Unless required by applicable law or agreed to in writing, software
  1825. distributed under the License is distributed on an "AS IS" BASIS,
  1826. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1827. See the License for the specific language governing permissions and
  1828. limitations under the License.
  1829.  
  1830. SPDX-License-Identifier: Apache License, Version 2.0
  1831. */
  1832.  
  1833. pragma solidity 0.6.10;
  1834. pragma experimental "ABIEncoderV2";
  1835.  
  1836.  
  1837.  
  1838.  
  1839.  
  1840.  
  1841.  
  1842.  
  1843. /**
  1844. * @title Position
  1845. * @author Set Protocol
  1846. *
  1847. * Collection of helper functions for handling and updating SetToken Positions
  1848. *
  1849. * CHANGELOG:
  1850. * - Updated editExternalPosition to work when no external position is associated with module
  1851. */
  1852. library Position {
  1853. using SafeCast for uint256;
  1854. using SafeMath for uint256;
  1855. using SafeCast for int256;
  1856. using SignedSafeMath for int256;
  1857. using PreciseUnitMath for uint256;
  1858.  
  1859. /* ============ Helper ============ */
  1860.  
  1861. /**
  1862. * Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
  1863. */
  1864. function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
  1865. return _setToken.getDefaultPositionRealUnit(_component) > 0;
  1866. }
  1867.  
  1868. /**
  1869. * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
  1870. */
  1871. function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
  1872. return _setToken.getExternalPositionModules(_component).length > 0;
  1873. }
  1874.  
  1875. /**
  1876. * Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
  1877. */
  1878. function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
  1879. return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
  1880. }
  1881.  
  1882. /**
  1883. * Returns whether the SetToken component external position is greater than or equal to the real units passed in.
  1884. */
  1885. function hasSufficientExternalUnits(
  1886. ISetToken _setToken,
  1887. address _component,
  1888. address _positionModule,
  1889. uint256 _unit
  1890. )
  1891. internal
  1892. view
  1893. returns(bool)
  1894. {
  1895. return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
  1896. }
  1897.  
  1898. /**
  1899. * If the position does not exist, create a new Position and add to the SetToken. If it already exists,
  1900. * then set the position units. If the new units is 0, remove the position. Handles adding/removing of
  1901. * components where needed (in light of potential external positions).
  1902. *
  1903. * @param _setToken Address of SetToken being modified
  1904. * @param _component Address of the component
  1905. * @param _newUnit Quantity of Position units - must be >= 0
  1906. */
  1907. function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
  1908. bool isPositionFound = hasDefaultPosition(_setToken, _component);
  1909. if (!isPositionFound && _newUnit > 0) {
  1910. // If there is no Default Position and no External Modules, then component does not exist
  1911. if (!hasExternalPosition(_setToken, _component)) {
  1912. _setToken.addComponent(_component);
  1913. }
  1914. } else if (isPositionFound && _newUnit == 0) {
  1915. // If there is a Default Position and no external positions, remove the component
  1916. if (!hasExternalPosition(_setToken, _component)) {
  1917. _setToken.removeComponent(_component);
  1918. }
  1919. }
  1920.  
  1921. _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
  1922. }
  1923.  
  1924. /**
  1925. * Update an external position and remove and external positions or components if necessary. The logic flows as follows:
  1926. * 1) If component is not already added then add component and external position.
  1927. * 2) If component is added but no existing external position using the passed module exists then add the external position.
  1928. * 3) If the existing position is being added to then just update the unit and data
  1929. * 4) If the position is being closed and no other external positions or default positions are associated with the component
  1930. * then untrack the component and remove external position.
  1931. * 5) If the position is being closed and other existing positions still exist for the component then just remove the
  1932. * external position.
  1933. *
  1934. * @param _setToken SetToken being updated
  1935. * @param _component Component position being updated
  1936. * @param _module Module external position is associated with
  1937. * @param _newUnit Position units of new external position
  1938. * @param _data Arbitrary data associated with the position
  1939. */
  1940. function editExternalPosition(
  1941. ISetToken _setToken,
  1942. address _component,
  1943. address _module,
  1944. int256 _newUnit,
  1945. bytes memory _data
  1946. )
  1947. internal
  1948. {
  1949. if (_newUnit != 0) {
  1950. if (!_setToken.isComponent(_component)) {
  1951. _setToken.addComponent(_component);
  1952. _setToken.addExternalPositionModule(_component, _module);
  1953. } else if (!_setToken.isExternalPositionModule(_component, _module)) {
  1954. _setToken.addExternalPositionModule(_component, _module);
  1955. }
  1956. _setToken.editExternalPositionUnit(_component, _module, _newUnit);
  1957. _setToken.editExternalPositionData(_component, _module, _data);
  1958. } else {
  1959. require(_data.length == 0, "Passed data must be null");
  1960. // If no default or external position remaining then remove component from components array
  1961. if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
  1962. address[] memory positionModules = _setToken.getExternalPositionModules(_component);
  1963. if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
  1964. require(positionModules[0] == _module, "External positions must be 0 to remove component");
  1965. _setToken.removeComponent(_component);
  1966. }
  1967. _setToken.removeExternalPositionModule(_component, _module);
  1968. }
  1969. }
  1970. }
  1971.  
  1972. /**
  1973. * Get total notional amount of Default position
  1974. *
  1975. * @param _setTokenSupply Supply of SetToken in precise units (10^18)
  1976. * @param _positionUnit Quantity of Position units
  1977. *
  1978. * @return Total notional amount of units
  1979. */
  1980. function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
  1981. return _setTokenSupply.preciseMul(_positionUnit);
  1982. }
  1983.  
  1984. /**
  1985. * Get position unit from total notional amount
  1986. *
  1987. * @param _setTokenSupply Supply of SetToken in precise units (10^18)
  1988. * @param _totalNotional Total notional amount of component prior to
  1989. * @return Default position unit
  1990. */
  1991. function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
  1992. return _totalNotional.preciseDiv(_setTokenSupply);
  1993. }
  1994.  
  1995. /**
  1996. * Get the total tracked balance - total supply * position unit
  1997. *
  1998. * @param _setToken Address of the SetToken
  1999. * @param _component Address of the component
  2000. * @return Notional tracked balance
  2001. */
  2002. function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
  2003. int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
  2004. return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
  2005. }
  2006.  
  2007. /**
  2008. * Calculates the new default position unit and performs the edit with the new unit
  2009. *
  2010. * @param _setToken Address of the SetToken
  2011. * @param _component Address of the component
  2012. * @param _setTotalSupply Current SetToken supply
  2013. * @param _componentPreviousBalance Pre-action component balance
  2014. * @return Current component balance
  2015. * @return Previous position unit
  2016. * @return New position unit
  2017. */
  2018. function calculateAndEditDefaultPosition(
  2019. ISetToken _setToken,
  2020. address _component,
  2021. uint256 _setTotalSupply,
  2022. uint256 _componentPreviousBalance
  2023. )
  2024. internal
  2025. returns(uint256, uint256, uint256)
  2026. {
  2027. uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
  2028. uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
  2029.  
  2030. uint256 newTokenUnit = calculateDefaultEditPositionUnit(
  2031. _setTotalSupply,
  2032. _componentPreviousBalance,
  2033. currentBalance,
  2034. positionUnit
  2035. );
  2036.  
  2037. editDefaultPosition(_setToken, _component, newTokenUnit);
  2038.  
  2039. return (currentBalance, positionUnit, newTokenUnit);
  2040. }
  2041.  
  2042. /**
  2043. * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
  2044. * The intention is to make updates to the units without accidentally picking up airdropped assets as well.
  2045. *
  2046. * @param _setTokenSupply Supply of SetToken in precise units (10^18)
  2047. * @param _preTotalNotional Total notional amount of component prior to executing action
  2048. * @param _postTotalNotional Total notional amount of component after the executing action
  2049. * @param _prePositionUnit Position unit of SetToken prior to executing action
  2050. * @return New position unit
  2051. */
  2052. function calculateDefaultEditPositionUnit(
  2053. uint256 _setTokenSupply,
  2054. uint256 _preTotalNotional,
  2055. uint256 _postTotalNotional,
  2056. uint256 _prePositionUnit
  2057. )
  2058. internal
  2059. pure
  2060. returns (uint256)
  2061. {
  2062. // If pre action total notional amount is greater then subtract post action total notional and calculate new position units
  2063. uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
  2064. return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
  2065. }
  2066. }
  2067.  
  2068. // File: contracts\lib\AddressArrayUtils.sol
  2069.  
  2070. /*
  2071. Copyright 2020 Set Labs Inc.
  2072.  
  2073. Licensed under the Apache License, Version 2.0 (the "License");
  2074. you may not use this file except in compliance with the License.
  2075. You may obtain a copy of the License at
  2076.  
  2077. http://www.apache.org/licenses/LICENSE-2.0
  2078.  
  2079. Unless required by applicable law or agreed to in writing, software
  2080. distributed under the License is distributed on an "AS IS" BASIS,
  2081. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2082. See the License for the specific language governing permissions and
  2083. limitations under the License.
  2084.  
  2085. SPDX-License-Identifier: Apache License, Version 2.0
  2086. */
  2087.  
  2088. pragma solidity 0.6.10;
  2089.  
  2090. /**
  2091. * @title AddressArrayUtils
  2092. * @author Set Protocol
  2093. *
  2094. * Utility functions to handle Address Arrays
  2095. */
  2096. library AddressArrayUtils {
  2097.  
  2098. /**
  2099. * Finds the index of the first occurrence of the given element.
  2100. * @param A The input array to search
  2101. * @param a The value to find
  2102. * @return Returns (index and isIn) for the first occurrence starting from index 0
  2103. */
  2104. function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
  2105. uint256 length = A.length;
  2106. for (uint256 i = 0; i < length; i++) {
  2107. if (A[i] == a) {
  2108. return (i, true);
  2109. }
  2110. }
  2111. return (uint256(-1), false);
  2112. }
  2113.  
  2114. /**
  2115. * Returns true if the value is present in the list. Uses indexOf internally.
  2116. * @param A The input array to search
  2117. * @param a The value to find
  2118. * @return Returns isIn for the first occurrence starting from index 0
  2119. */
  2120. function contains(address[] memory A, address a) internal pure returns (bool) {
  2121. (, bool isIn) = indexOf(A, a);
  2122. return isIn;
  2123. }
  2124.  
  2125. /**
  2126. * Returns true if there are 2 elements that are the same in an array
  2127. * @param A The input array to search
  2128. * @return Returns boolean for the first occurrence of a duplicate
  2129. */
  2130. function hasDuplicate(address[] memory A) internal pure returns(bool) {
  2131. require(A.length > 0, "A is empty");
  2132.  
  2133. for (uint256 i = 0; i < A.length - 1; i++) {
  2134. address current = A[i];
  2135. for (uint256 j = i + 1; j < A.length; j++) {
  2136. if (current == A[j]) {
  2137. return true;
  2138. }
  2139. }
  2140. }
  2141. return false;
  2142. }
  2143.  
  2144. /**
  2145. * @param A The input array to search
  2146. * @param a The address to remove
  2147. * @return Returns the array with the object removed.
  2148. */
  2149. function remove(address[] memory A, address a)
  2150. internal
  2151. pure
  2152. returns (address[] memory)
  2153. {
  2154. (uint256 index, bool isIn) = indexOf(A, a);
  2155. if (!isIn) {
  2156. revert("Address not in array.");
  2157. } else {
  2158. (address[] memory _A,) = pop(A, index);
  2159. return _A;
  2160. }
  2161. }
  2162.  
  2163. /**
  2164. * Removes specified index from array
  2165. * @param A The input array to search
  2166. * @param index The index to remove
  2167. * @return Returns the new array and the removed entry
  2168. */
  2169. function pop(address[] memory A, uint256 index)
  2170. internal
  2171. pure
  2172. returns (address[] memory, address)
  2173. {
  2174. uint256 length = A.length;
  2175. require(index < A.length, "Index must be < A length");
  2176. address[] memory newAddresses = new address[](length - 1);
  2177. for (uint256 i = 0; i < index; i++) {
  2178. newAddresses[i] = A[i];
  2179. }
  2180. for (uint256 j = index + 1; j < length; j++) {
  2181. newAddresses[j - 1] = A[j];
  2182. }
  2183. return (newAddresses, A[index]);
  2184. }
  2185.  
  2186. /**
  2187. * Returns the combination of the two arrays
  2188. * @param A The first array
  2189. * @param B The second array
  2190. * @return Returns A extended by B
  2191. */
  2192. function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
  2193. uint256 aLength = A.length;
  2194. uint256 bLength = B.length;
  2195. address[] memory newAddresses = new address[](aLength + bLength);
  2196. for (uint256 i = 0; i < aLength; i++) {
  2197. newAddresses[i] = A[i];
  2198. }
  2199. for (uint256 j = 0; j < bLength; j++) {
  2200. newAddresses[aLength + j] = B[j];
  2201. }
  2202. return newAddresses;
  2203. }
  2204. }
  2205.  
  2206. // File: contracts\protocol\setToken.sol
  2207.  
  2208. /*
  2209. Copyright 2020 Set Labs Inc.
  2210.  
  2211. Licensed under the Apache License, Version 2.0 (the "License");
  2212. you may not use this file except in compliance with the License.
  2213. You may obtain a copy of the License at
  2214.  
  2215. http://www.apache.org/licenses/LICENSE-2.0
  2216.  
  2217. Unless required by applicable law or agreed to in writing, software
  2218. distributed under the License is distributed on an "AS IS" BASIS,
  2219. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2220. See the License for the specific language governing permissions and
  2221. limitations under the License.
  2222.  
  2223. SPDX-License-Identifier: Apache License, Version 2.0
  2224. */
  2225.  
  2226. pragma solidity 0.6.10;
  2227. pragma experimental "ABIEncoderV2";
  2228.  
  2229.  
  2230.  
  2231.  
  2232.  
  2233.  
  2234.  
  2235.  
  2236.  
  2237.  
  2238.  
  2239.  
  2240. /**
  2241. * @title SetToken
  2242. * @author Set Protocol
  2243. *
  2244. * ERC20 Token contract that allows privileged modules to make modifications to its positions and invoke function calls
  2245. * from the SetToken.
  2246. */
  2247. contract SetToken is ERC20 {
  2248. using SafeMath for uint256;
  2249. using SignedSafeMath for int256;
  2250. using PreciseUnitMath for int256;
  2251. using Address for address;
  2252. using AddressArrayUtils for address[];
  2253.  
  2254. /* ============ Constants ============ */
  2255.  
  2256. /*
  2257. The PositionState is the status of the Position, whether it is Default (held on the SetToken)
  2258. or otherwise held on a separate smart contract (whether a module or external source).
  2259. There are issues with cross-usage of enums, so we are defining position states
  2260. as a uint8.
  2261. */
  2262. uint8 internal constant DEFAULT = 0;
  2263. uint8 internal constant EXTERNAL = 1;
  2264.  
  2265. /* ============ Events ============ */
  2266.  
  2267. event Invoked(address indexed _target, uint indexed _value, bytes _data, bytes _returnValue);
  2268. event ModuleAdded(address indexed _module);
  2269. event ModuleRemoved(address indexed _module);
  2270. event ModuleInitialized(address indexed _module);
  2271. event ManagerEdited(address _newManager, address _oldManager);
  2272. event PendingModuleRemoved(address indexed _module);
  2273. event PositionMultiplierEdited(int256 _newMultiplier);
  2274. event ComponentAdded(address indexed _component);
  2275. event ComponentRemoved(address indexed _component);
  2276. event DefaultPositionUnitEdited(address indexed _component, int256 _realUnit);
  2277. event ExternalPositionUnitEdited(address indexed _component, address indexed _positionModule, int256 _realUnit);
  2278. event ExternalPositionDataEdited(address indexed _component, address indexed _positionModule, bytes _data);
  2279. event PositionModuleAdded(address indexed _component, address indexed _positionModule);
  2280. event PositionModuleRemoved(address indexed _component, address indexed _positionModule);
  2281.  
  2282. /* ============ Modifiers ============ */
  2283.  
  2284. /**
  2285. * Throws if the sender is not a SetToken's module or module not enabled
  2286. */
  2287. modifier onlyModule() {
  2288. // Internal function used to reduce bytecode size
  2289. _validateOnlyModule();
  2290. _;
  2291. }
  2292.  
  2293. /**
  2294. * Throws if the sender is not the SetToken's manager
  2295. */
  2296. modifier onlyManager() {
  2297. _validateOnlyManager();
  2298. _;
  2299. }
  2300.  
  2301. /**
  2302. * Throws if SetToken is locked and called by any account other than the locker.
  2303. */
  2304. modifier whenLockedOnlyLocker() {
  2305. _validateWhenLockedOnlyLocker();
  2306. _;
  2307. }
  2308.  
  2309. /* ============ State Variables ============ */
  2310.  
  2311. // Address of the controller
  2312. IController public controller;
  2313.  
  2314. // The manager has the privelege to add modules, remove, and set a new manager
  2315. address public manager;
  2316.  
  2317. // A module that has locked other modules from privileged functionality, typically required
  2318. // for multi-block module actions such as auctions
  2319. address public locker;
  2320.  
  2321. // List of initialized Modules; Modules extend the functionality of SetTokens
  2322. address[] public modules;
  2323.  
  2324. // Modules are initialized from NONE -> PENDING -> INITIALIZED through the
  2325. // addModule (called by manager) and initialize (called by module) functions
  2326. mapping(address => ISetToken.ModuleState) public moduleStates;
  2327.  
  2328. // When locked, only the locker (a module) can call privileged functionality
  2329. // Typically utilized if a module (e.g. Auction) needs multiple transactions to complete an action
  2330. // without interruption
  2331. bool public isLocked;
  2332.  
  2333. // List of components
  2334. address[] public components;
  2335.  
  2336. // Mapping that stores all Default and External position information for a given component.
  2337. // Position quantities are represented as virtual units; Default positions are on the top-level,
  2338. // while external positions are stored in a module array and accessed through its externalPositions mapping
  2339. mapping(address => ISetToken.ComponentPosition) private componentPositions;
  2340.  
  2341. // The multiplier applied to the virtual position unit to achieve the real/actual unit.
  2342. // This multiplier is used for efficiently modifying the entire position units (e.g. streaming fee)
  2343. int256 public positionMultiplier;
  2344.  
  2345.  
  2346. /* ============ Constructor ============ */
  2347.  
  2348. /**
  2349. * When a new SetToken is created, initializes Positions in default state and adds modules into pending state.
  2350. * All parameter validations are on the SetTokenCreator contract. Validations are performed already on the
  2351. * SetTokenCreator. Initiates the positionMultiplier as 1e18 (no adjustments).
  2352. *
  2353. * @param _components List of addresses of components for initial Positions
  2354. * @param _units List of units. Each unit is the # of components per 10^18 of a SetToken
  2355. * @param _modules List of modules to enable. All modules must be approved by the Controller
  2356. * @param _controller Address of the controller
  2357. * @param _manager Address of the manager
  2358. * @param _name Name of the SetToken
  2359. * @param _symbol Symbol of the SetToken
  2360. */
  2361. constructor(
  2362. address[] memory _components,
  2363. int256[] memory _units,
  2364. address[] memory _modules,
  2365. IController _controller,
  2366. address _manager,
  2367. string memory _name,
  2368. string memory _symbol
  2369. )
  2370. public
  2371. ERC20(_name, _symbol)
  2372. {
  2373. controller = _controller;
  2374. manager = _manager;
  2375. positionMultiplier = PreciseUnitMath.preciseUnitInt();
  2376. components = _components;
  2377.  
  2378. // Modules are put in PENDING state, as they need to be individually initialized by the Module
  2379. for (uint256 i = 0; i < _modules.length; i++) {
  2380. moduleStates[_modules[i]] = ISetToken.ModuleState.PENDING;
  2381. }
  2382.  
  2383. // Positions are put in default state initially
  2384. for (uint256 j = 0; j < _components.length; j++) {
  2385. componentPositions[_components[j]].virtualUnit = _units[j];
  2386. }
  2387. }
  2388.  
  2389. /* ============ External Functions ============ */
  2390.  
  2391. /**
  2392. * PRIVELEGED MODULE FUNCTION. Low level function that allows a module to make an arbitrary function
  2393. * call to any contract.
  2394. *
  2395. * @param _target Address of the smart contract to call
  2396. * @param _value Quantity of Ether to provide the call (typically 0)
  2397. * @param _data Encoded function selector and arguments
  2398. * @return _returnValue Bytes encoded return value
  2399. */
  2400. function invoke(
  2401. address _target,
  2402. uint256 _value,
  2403. bytes calldata _data
  2404. )
  2405. external
  2406. onlyModule
  2407. whenLockedOnlyLocker
  2408. returns (bytes memory _returnValue)
  2409. {
  2410. _returnValue = _target.functionCallWithValue(_data, _value);
  2411.  
  2412. emit Invoked(_target, _value, _data, _returnValue);
  2413.  
  2414. return _returnValue;
  2415. }
  2416.  
  2417. /**
  2418. * PRIVELEGED MODULE FUNCTION. Low level function that adds a component to the components array.
  2419. */
  2420. function addComponent(address _component) external onlyModule whenLockedOnlyLocker {
  2421. components.push(_component);
  2422.  
  2423. emit ComponentAdded(_component);
  2424. }
  2425.  
  2426. /**
  2427. * PRIVELEGED MODULE FUNCTION. Low level function that removes a component from the components array.
  2428. */
  2429. function removeComponent(address _component) external onlyModule whenLockedOnlyLocker {
  2430. components = components.remove(_component);
  2431.  
  2432. emit ComponentRemoved(_component);
  2433. }
  2434.  
  2435. /**
  2436. * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's virtual unit. Takes a real unit
  2437. * and converts it to virtual before committing.
  2438. */
  2439. function editDefaultPositionUnit(address _component, int256 _realUnit) external onlyModule whenLockedOnlyLocker {
  2440. int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
  2441.  
  2442. componentPositions[_component].virtualUnit = virtualUnit;
  2443.  
  2444. emit DefaultPositionUnitEdited(_component, _realUnit);
  2445. }
  2446.  
  2447. /**
  2448. * PRIVELEGED MODULE FUNCTION. Low level function that adds a module to a component's externalPositionModules array
  2449. */
  2450. function addExternalPositionModule(address _component, address _positionModule) external onlyModule whenLockedOnlyLocker {
  2451. componentPositions[_component].externalPositionModules.push(_positionModule);
  2452.  
  2453. emit PositionModuleAdded(_component, _positionModule);
  2454. }
  2455.  
  2456. /**
  2457. * PRIVELEGED MODULE FUNCTION. Low level function that removes a module from a component's
  2458. * externalPositionModules array and deletes the associated externalPosition.
  2459. */
  2460. function removeExternalPositionModule(
  2461. address _component,
  2462. address _positionModule
  2463. )
  2464. external
  2465. onlyModule
  2466. whenLockedOnlyLocker
  2467. {
  2468. componentPositions[_component].externalPositionModules = _externalPositionModules(_component).remove(_positionModule);
  2469. delete componentPositions[_component].externalPositions[_positionModule];
  2470.  
  2471. emit PositionModuleRemoved(_component, _positionModule);
  2472. }
  2473.  
  2474. /**
  2475. * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit.
  2476. * Takes a real unit and converts it to virtual before committing.
  2477. */
  2478. function editExternalPositionUnit(
  2479. address _component,
  2480. address _positionModule,
  2481. int256 _realUnit
  2482. )
  2483. external
  2484. onlyModule
  2485. whenLockedOnlyLocker
  2486. {
  2487. int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
  2488.  
  2489. componentPositions[_component].externalPositions[_positionModule].virtualUnit = virtualUnit;
  2490.  
  2491. emit ExternalPositionUnitEdited(_component, _positionModule, _realUnit);
  2492. }
  2493.  
  2494. /**
  2495. * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position data
  2496. */
  2497. function editExternalPositionData(
  2498. address _component,
  2499. address _positionModule,
  2500. bytes calldata _data
  2501. )
  2502. external
  2503. onlyModule
  2504. whenLockedOnlyLocker
  2505. {
  2506. componentPositions[_component].externalPositions[_positionModule].data = _data;
  2507.  
  2508. emit ExternalPositionDataEdited(_component, _positionModule, _data);
  2509. }
  2510.  
  2511. /**
  2512. * PRIVELEGED MODULE FUNCTION. Modifies the position multiplier. This is typically used to efficiently
  2513. * update all the Positions' units at once in applications where inflation is awarded (e.g. subscription fees).
  2514. */
  2515. function editPositionMultiplier(int256 _newMultiplier) external onlyModule whenLockedOnlyLocker {
  2516. require(_newMultiplier > 0, "Must be greater than 0");
  2517.  
  2518. positionMultiplier = _newMultiplier;
  2519.  
  2520. emit PositionMultiplierEdited(_newMultiplier);
  2521. }
  2522.  
  2523. /**
  2524. * PRIVELEGED MODULE FUNCTION. Increases the "account" balance by the "quantity".
  2525. */
  2526. function mint(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker {
  2527. _mint(_account, _quantity);
  2528. }
  2529.  
  2530. /**
  2531. * PRIVELEGED MODULE FUNCTION. Decreases the "account" balance by the "quantity".
  2532. * _burn checks that the "account" already has the required "quantity".
  2533. */
  2534. function burn(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker {
  2535. _burn(_account, _quantity);
  2536. }
  2537.  
  2538. /**
  2539. * PRIVELEGED MODULE FUNCTION. When a SetToken is locked, only the locker can call privileged functions.
  2540. */
  2541. function lock() external onlyModule {
  2542. require(!isLocked, "Must not be locked");
  2543. locker = msg.sender;
  2544. isLocked = true;
  2545. }
  2546.  
  2547. /**
  2548. * PRIVELEGED MODULE FUNCTION. Unlocks the SetToken and clears the locker
  2549. */
  2550. function unlock() external onlyModule {
  2551. require(isLocked, "Must be locked");
  2552. require(locker == msg.sender, "Must be locker");
  2553. delete locker;
  2554. isLocked = false;
  2555. }
  2556.  
  2557. /**
  2558. * MANAGER ONLY. Adds a module into a PENDING state; Module must later be initialized via
  2559. * module's initialize function
  2560. */
  2561. function addModule(address _module) external onlyManager {
  2562. require(moduleStates[_module] == ISetToken.ModuleState.NONE, "Module must not be added");
  2563. require(controller.isModule(_module), "Must be enabled on Controller");
  2564.  
  2565. moduleStates[_module] = ISetToken.ModuleState.PENDING;
  2566.  
  2567. emit ModuleAdded(_module);
  2568. }
  2569.  
  2570. /**
  2571. * MANAGER ONLY. Removes a module from the SetToken. SetToken calls removeModule on module itself to confirm
  2572. * it is not needed to manage any remaining positions and to remove state.
  2573. */
  2574. function removeModule(address _module) external onlyManager {
  2575. require(!isLocked, "Only when unlocked");
  2576. require(moduleStates[_module] == ISetToken.ModuleState.INITIALIZED, "Module must be added");
  2577.  
  2578. IModule(_module).removeModule();
  2579.  
  2580. moduleStates[_module] = ISetToken.ModuleState.NONE;
  2581.  
  2582. modules = modules.remove(_module);
  2583.  
  2584. emit ModuleRemoved(_module);
  2585. }
  2586.  
  2587. /**
  2588. * MANAGER ONLY. Removes a pending module from the SetToken.
  2589. */
  2590. function removePendingModule(address _module) external onlyManager {
  2591. require(!isLocked, "Only when unlocked");
  2592. require(moduleStates[_module] == ISetToken.ModuleState.PENDING, "Module must be pending");
  2593.  
  2594. moduleStates[_module] = ISetToken.ModuleState.NONE;
  2595.  
  2596. emit PendingModuleRemoved(_module);
  2597. }
  2598.  
  2599. /**
  2600. * Initializes an added module from PENDING to INITIALIZED state. Can only call when unlocked.
  2601. * An address can only enter a PENDING state if it is an enabled module added by the manager.
  2602. * Only callable by the module itself, hence msg.sender is the subject of update.
  2603. */
  2604. function initializeModule() external {
  2605. require(!isLocked, "Only when unlocked");
  2606. require(moduleStates[msg.sender] == ISetToken.ModuleState.PENDING, "Module must be pending");
  2607.  
  2608. moduleStates[msg.sender] = ISetToken.ModuleState.INITIALIZED;
  2609. modules.push(msg.sender);
  2610.  
  2611. emit ModuleInitialized(msg.sender);
  2612. }
  2613.  
  2614. /**
  2615. * MANAGER ONLY. Changes manager; We allow null addresses in case the manager wishes to wind down the SetToken.
  2616. * Modules may rely on the manager state, so only changable when unlocked
  2617. */
  2618. function setManager(address _manager) external onlyManager {
  2619. require(!isLocked, "Only when unlocked");
  2620. address oldManager = manager;
  2621. manager = _manager;
  2622.  
  2623. emit ManagerEdited(_manager, oldManager);
  2624. }
  2625.  
  2626. /* ============ External Getter Functions ============ */
  2627.  
  2628. function getComponents() external view returns(address[] memory) {
  2629. return components;
  2630. }
  2631.  
  2632. function getDefaultPositionRealUnit(address _component) public view returns(int256) {
  2633. return _convertVirtualToRealUnit(_defaultPositionVirtualUnit(_component));
  2634. }
  2635.  
  2636. function getExternalPositionRealUnit(address _component, address _positionModule) public view returns(int256) {
  2637. return _convertVirtualToRealUnit(_externalPositionVirtualUnit(_component, _positionModule));
  2638. }
  2639.  
  2640. function getExternalPositionModules(address _component) external view returns(address[] memory) {
  2641. return _externalPositionModules(_component);
  2642. }
  2643.  
  2644. function getExternalPositionData(address _component,address _positionModule) external view returns(bytes memory) {
  2645. return _externalPositionData(_component, _positionModule);
  2646. }
  2647.  
  2648. function getModules() external view returns (address[] memory) {
  2649. return modules;
  2650. }
  2651.  
  2652. function isComponent(address _component) external view returns(bool) {
  2653. return components.contains(_component);
  2654. }
  2655.  
  2656. function isExternalPositionModule(address _component, address _module) external view returns(bool) {
  2657. return _externalPositionModules(_component).contains(_module);
  2658. }
  2659.  
  2660. /**
  2661. * Only ModuleStates of INITIALIZED modules are considered enabled
  2662. */
  2663. function isInitializedModule(address _module) external view returns (bool) {
  2664. return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED;
  2665. }
  2666.  
  2667. /**
  2668. * Returns whether the module is in a pending state
  2669. */
  2670. function isPendingModule(address _module) external view returns (bool) {
  2671. return moduleStates[_module] == ISetToken.ModuleState.PENDING;
  2672. }
  2673.  
  2674. /**
  2675. * Returns a list of Positions, through traversing the components. Each component with a non-zero virtual unit
  2676. * is considered a Default Position, and each externalPositionModule will generate a unique position.
  2677. * Virtual units are converted to real units. This function is typically used off-chain for data presentation purposes.
  2678. */
  2679. function getPositions() external view returns (ISetToken.Position[] memory) {
  2680. ISetToken.Position[] memory positions = new ISetToken.Position[](_getPositionCount());
  2681. uint256 positionCount = 0;
  2682.  
  2683. for (uint256 i = 0; i < components.length; i++) {
  2684. address component = components[i];
  2685.  
  2686. // A default position exists if the default virtual unit is > 0
  2687. if (_defaultPositionVirtualUnit(component) > 0) {
  2688. positions[positionCount] = ISetToken.Position({
  2689. component: component,
  2690. module: address(0),
  2691. unit: getDefaultPositionRealUnit(component),
  2692. positionState: DEFAULT,
  2693. data: ""
  2694. });
  2695.  
  2696. positionCount++;
  2697. }
  2698.  
  2699. address[] memory externalModules = _externalPositionModules(component);
  2700. for (uint256 j = 0; j < externalModules.length; j++) {
  2701. address currentModule = externalModules[j];
  2702.  
  2703. positions[positionCount] = ISetToken.Position({
  2704. component: component,
  2705. module: currentModule,
  2706. unit: getExternalPositionRealUnit(component, currentModule),
  2707. positionState: EXTERNAL,
  2708. data: _externalPositionData(component, currentModule)
  2709. });
  2710.  
  2711. positionCount++;
  2712. }
  2713. }
  2714.  
  2715. return positions;
  2716. }
  2717.  
  2718. /**
  2719. * Returns the total Real Units for a given component, summing the default and external position units.
  2720. */
  2721. function getTotalComponentRealUnits(address _component) external view returns(int256) {
  2722. int256 totalUnits = getDefaultPositionRealUnit(_component);
  2723.  
  2724. address[] memory externalModules = _externalPositionModules(_component);
  2725. for (uint256 i = 0; i < externalModules.length; i++) {
  2726. // We will perform the summation no matter what, as an external position virtual unit can be negative
  2727. totalUnits = totalUnits.add(getExternalPositionRealUnit(_component, externalModules[i]));
  2728. }
  2729.  
  2730. return totalUnits;
  2731. }
  2732.  
  2733.  
  2734. receive() external payable {} // solium-disable-line quotes
  2735.  
  2736. /* ============ Internal Functions ============ */
  2737.  
  2738. function _defaultPositionVirtualUnit(address _component) internal view returns(int256) {
  2739. return componentPositions[_component].virtualUnit;
  2740. }
  2741.  
  2742. function _externalPositionModules(address _component) internal view returns(address[] memory) {
  2743. return componentPositions[_component].externalPositionModules;
  2744. }
  2745.  
  2746. function _externalPositionVirtualUnit(address _component, address _module) internal view returns(int256) {
  2747. return componentPositions[_component].externalPositions[_module].virtualUnit;
  2748. }
  2749.  
  2750. function _externalPositionData(address _component, address _module) internal view returns(bytes memory) {
  2751. return componentPositions[_component].externalPositions[_module].data;
  2752. }
  2753.  
  2754. /**
  2755. * Takes a real unit and divides by the position multiplier to return the virtual unit
  2756. */
  2757. function _convertRealToVirtualUnit(int256 _realUnit) internal view returns(int256) {
  2758. int256 virtualUnit = _realUnit.conservativePreciseDiv(positionMultiplier);
  2759.  
  2760. // These checks ensure that the virtual unit does not return a result that has rounded down to 0
  2761. if (_realUnit > 0 && virtualUnit == 0) {
  2762. revert("Virtual unit conversion invalid");
  2763. }
  2764.  
  2765. return virtualUnit;
  2766. }
  2767.  
  2768. /**
  2769. * Takes a virtual unit and multiplies by the position multiplier to return the real unit
  2770. */
  2771. function _convertVirtualToRealUnit(int256 _virtualUnit) internal view returns(int256) {
  2772. return _virtualUnit.conservativePreciseMul(positionMultiplier);
  2773. }
  2774.  
  2775. /**
  2776. * Gets the total number of positions, defined as the following:
  2777. * - Each component has a default position if its virtual unit is > 0
  2778. * - Each component's external positions module is counted as a position
  2779. */
  2780. function _getPositionCount() internal view returns (uint256) {
  2781. uint256 positionCount;
  2782. for (uint256 i = 0; i < components.length; i++) {
  2783. address component = components[i];
  2784.  
  2785. // Increment the position count if the default position is > 0
  2786. if (_defaultPositionVirtualUnit(component) > 0) {
  2787. positionCount++;
  2788. }
  2789.  
  2790. // Increment the position count by each external position module
  2791. address[] memory externalModules = _externalPositionModules(component);
  2792. if (externalModules.length > 0) {
  2793. positionCount = positionCount.add(externalModules.length);
  2794. }
  2795. }
  2796.  
  2797. return positionCount;
  2798. }
  2799.  
  2800. /**
  2801. * Due to reason error bloat, internal functions are used to reduce bytecode size
  2802. *
  2803. * Module must be initialized on the SetToken and enabled by the controller
  2804. */
  2805. function _validateOnlyModule() internal view {
  2806. require(
  2807. moduleStates[msg.sender] == ISetToken.ModuleState.INITIALIZED,
  2808. "Only the module can call"
  2809. );
  2810.  
  2811. require(
  2812. controller.isModule(msg.sender),
  2813. "Module must be enabled on controller"
  2814. );
  2815. }
  2816.  
  2817. function _validateOnlyManager() internal view {
  2818. require(msg.sender == manager, "Only manager can call");
  2819. }
  2820.  
  2821. function _validateWhenLockedOnlyLocker() internal view {
  2822. if (isLocked) {
  2823. require(msg.sender == locker, "When locked, only the locker can call");
  2824. }
  2825. }
  2826. }
  2827.  
RAW Paste Data