{ "language": "Solidity", "settings": { "evmVersion": "istanbul", "libraries": { "contracts/protocol/core/CreditLine.sol:CreditLine": { "Accountant": "0x76ee6B1Db228E09aF70B86800c31f8Bd52794045" } }, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 100 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "sources": { "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol": { "content": "pragma solidity ^0.6.0;\nimport \"../Initializable.sol\";\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\ncontract ContextUpgradeSafe is Initializable {\n // Empty internal constructor, to prevent people from mistakenly deploying\n // an instance of this contract, which should be used via inheritance.\n\n function __Context_init() internal initializer {\n __Context_init_unchained();\n }\n\n function __Context_init_unchained() internal initializer {\n\n\n }\n\n\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol": { "content": "pragma solidity >=0.4.24 <0.7.0;\n\n\n/**\n * @title Initializable\n *\n * @dev Helper contract to support initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n */\ncontract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private initializing;\n\n /**\n * @dev Modifier to use in the initializer function of a contract.\n */\n modifier initializer() {\n require(initializing || isConstructor() || !initialized, \"Contract instance has already been initialized\");\n\n bool isTopLevelCall = !initializing;\n if (isTopLevelCall) {\n initializing = true;\n initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n address self = address(this);\n uint256 cs;\n assembly { cs := extcodesize(self) }\n return cs == 0;\n }\n\n // Reserved storage space to allow for layout changes in the future.\n uint256[50] private ______gap;\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol": { "content": "pragma solidity ^0.6.0;\n\nimport \"../utils/EnumerableSet.sol\";\nimport \"../utils/Address.sol\";\nimport \"../GSN/Context.sol\";\nimport \"../Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, _msgSender()));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n */\nabstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {\n function __AccessControl_init() internal initializer {\n __Context_init_unchained();\n __AccessControl_init_unchained();\n }\n\n function __AccessControl_init_unchained() internal initializer {\n\n\n }\n\n using EnumerableSet for EnumerableSet.AddressSet;\n using Address for address;\n\n struct RoleData {\n EnumerableSet.AddressSet members;\n bytes32 adminRole;\n }\n\n mapping (bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view returns (bool) {\n return _roles[role].members.contains(account);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n return _roles[role].members.length();\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n return _roles[role].members.at(index);\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) public virtual {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n _roles[role].adminRole = adminRole;\n }\n\n function _grantRole(bytes32 role, address account) private {\n if (_roles[role].members.add(account)) {\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n function _revokeRole(bytes32 role, address account) private {\n if (_roles[role].members.remove(account)) {\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow, so we distribute\n return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);\n }\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @title SignedSafeMath\n * @dev Signed math operations with safety checks that revert on error.\n */\nlibrary SignedSafeMath {\n int256 constant private _INT256_MIN = -2**255;\n\n /**\n * @dev Multiplies two signed integers, reverts on overflow.\n */\n function mul(int256 a, int256 b) internal pure returns (int256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n require(!(a == -1 && b == _INT256_MIN), \"SignedSafeMath: multiplication overflow\");\n\n int256 c = a * b;\n require(c / a == b, \"SignedSafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.\n */\n function div(int256 a, int256 b) internal pure returns (int256) {\n require(b != 0, \"SignedSafeMath: division by zero\");\n require(!(b == -1 && a == _INT256_MIN), \"SignedSafeMath: division overflow\");\n\n int256 c = a / b;\n\n return c;\n }\n\n /**\n * @dev Subtracts two signed integers, reverts on overflow.\n */\n function sub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a), \"SignedSafeMath: subtraction overflow\");\n\n return c;\n }\n\n /**\n * @dev Adds two signed integers, reverts on overflow.\n */\n function add(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a + b;\n require((b >= 0 && c >= a) || (b < 0 && c < a), \"SignedSafeMath: addition overflow\");\n\n return c;\n }\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol": { "content": "pragma solidity ^0.6.2;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash := extcodehash(account) }\n return (codehash != accountHash && codehash != 0x0);\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol": { "content": "pragma solidity ^0.6.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`\n * (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint256(_at(set._inner, index)));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol": { "content": "pragma solidity ^0.6.0;\n\nimport \"../GSN/Context.sol\";\nimport \"../Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\ncontract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n\n function __Pausable_init() internal initializer {\n __Context_init_unchained();\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal initializer {\n\n\n _paused = false;\n\n }\n\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n */\n modifier whenNotPaused() {\n require(!_paused, \"Pausable: paused\");\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n */\n modifier whenPaused() {\n require(_paused, \"Pausable: not paused\");\n _;\n }\n\n /**\n * @dev Triggers stopped state.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol": { "content": "pragma solidity ^0.6.0;\nimport \"../Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\ncontract ReentrancyGuardUpgradeSafe is Initializable {\n bool private _notEntered;\n\n\n function __ReentrancyGuard_init() internal initializer {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal initializer {\n\n\n // Storing an initial non-zero value makes deployment a bit more\n // expensive, but in exchange the refund on every call to nonReentrant\n // will be lower in amount. Since refunds are capped to a percetange of\n // the total transaction's gas, it is best to keep them low in cases\n // like this one, to increase the likelihood of the full refund coming\n // into effect.\n _notEntered = true;\n\n }\n\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_notEntered, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _notEntered = false;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _notEntered = true;\n }\n\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/external/FixedPoint.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0-only\n// solhint-disable\n// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol\";\n\n/**\n * @title Library for fixed point arithmetic on uints\n */\nlibrary FixedPoint {\n using SafeMath for uint256;\n using SignedSafeMath for int256;\n\n // Supports 18 decimals. E.g., 1e18 represents \"1\", 5e17 represents \"0.5\".\n // For unsigned values:\n // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.\n uint256 private constant FP_SCALING_FACTOR = 10 ** 18;\n\n // --------------------------------------- UNSIGNED -----------------------------------------------------------------------------\n struct Unsigned {\n uint256 rawValue;\n }\n\n /**\n * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.\n * @param a uint to convert into a FixedPoint.\n * @return the converted FixedPoint.\n */\n function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {\n return Unsigned(a.mul(FP_SCALING_FACTOR));\n }\n\n /**\n * @notice Whether `a` is equal to `b`.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return True if equal, or False.\n */\n function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {\n return a.rawValue == fromUnscaledUint(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is equal to `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return True if equal, or False.\n */\n function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {\n return a.rawValue == b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {\n return a.rawValue > b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {\n return a.rawValue > fromUnscaledUint(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a a uint256.\n * @param b a FixedPoint.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {\n return fromUnscaledUint(a).rawValue > b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {\n return a.rawValue >= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {\n return a.rawValue >= fromUnscaledUint(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a a uint256.\n * @param b a FixedPoint.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {\n return fromUnscaledUint(a).rawValue >= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return True if `a < b`, or False.\n */\n function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {\n return a.rawValue < b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return True if `a < b`, or False.\n */\n function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {\n return a.rawValue < fromUnscaledUint(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a a uint256.\n * @param b a FixedPoint.\n * @return True if `a < b`, or False.\n */\n function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {\n return fromUnscaledUint(a).rawValue < b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {\n return a.rawValue <= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {\n return a.rawValue <= fromUnscaledUint(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a a uint256.\n * @param b a FixedPoint.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {\n return fromUnscaledUint(a).rawValue <= b.rawValue;\n }\n\n /**\n * @notice The minimum of `a` and `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the minimum of `a` and `b`.\n */\n function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return a.rawValue < b.rawValue ? a : b;\n }\n\n /**\n * @notice The maximum of `a` and `b`.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the maximum of `a` and `b`.\n */\n function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return a.rawValue > b.rawValue ? a : b;\n }\n\n /**\n * @notice Adds two `Unsigned`s, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the sum of `a` and `b`.\n */\n function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return Unsigned(a.rawValue.add(b.rawValue));\n }\n\n /**\n * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return the sum of `a` and `b`.\n */\n function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n return add(a, fromUnscaledUint(b));\n }\n\n /**\n * @notice Subtracts two `Unsigned`s, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the difference of `a` and `b`.\n */\n function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return Unsigned(a.rawValue.sub(b.rawValue));\n }\n\n /**\n * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return the difference of `a` and `b`.\n */\n function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n return sub(a, fromUnscaledUint(b));\n }\n\n /**\n * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.\n * @param a a uint256.\n * @param b a FixedPoint.\n * @return the difference of `a` and `b`.\n */\n function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return sub(fromUnscaledUint(a), b);\n }\n\n /**\n * @notice Multiplies two `Unsigned`s, reverting on overflow.\n * @dev This will \"floor\" the product.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the product of `a` and `b`.\n */\n function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n // There are two caveats with this computation:\n // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is\n // stored internally as a uint256 ~10^59.\n // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which\n // would round to 3, but this computation produces the result 2.\n // No need to use SafeMath because FP_SCALING_FACTOR != 0.\n return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);\n }\n\n /**\n * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.\n * @dev This will \"floor\" the product.\n * @param a a FixedPoint.\n * @param b a uint256.\n * @return the product of `a` and `b`.\n */\n function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n return Unsigned(a.rawValue.mul(b));\n }\n\n /**\n * @notice Multiplies two `Unsigned`s and \"ceil's\" the product, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the product of `a` and `b`.\n */\n function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n uint256 mulRaw = a.rawValue.mul(b.rawValue);\n uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;\n uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);\n if (mod != 0) {\n return Unsigned(mulFloor.add(1));\n } else {\n return Unsigned(mulFloor);\n }\n }\n\n /**\n * @notice Multiplies an `Unsigned` and an unscaled uint256 and \"ceil's\" the product, reverting on overflow.\n * @param a a FixedPoint.\n * @param b a FixedPoint.\n * @return the product of `a` and `b`.\n */\n function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n // Since b is an int, there is no risk of truncation and we can just mul it normally\n return Unsigned(a.rawValue.mul(b));\n }\n\n /**\n * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a a FixedPoint numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n // There are two caveats with this computation:\n // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.\n // 10^41 is stored internally as a uint256 10^59.\n // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which\n // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.\n return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));\n }\n\n /**\n * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a a FixedPoint numerator.\n * @param b a uint256 denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n return Unsigned(a.rawValue.div(b));\n }\n\n /**\n * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a a uint256 numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {\n return div(fromUnscaledUint(a), b);\n }\n\n /**\n * @notice Divides one `Unsigned` by an `Unsigned` and \"ceil's\" the quotient, reverting on overflow or division by 0.\n * @param a a FixedPoint numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {\n uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);\n uint256 divFloor = aScaled.div(b.rawValue);\n uint256 mod = aScaled.mod(b.rawValue);\n if (mod != 0) {\n return Unsigned(divFloor.add(1));\n } else {\n return Unsigned(divFloor);\n }\n }\n\n /**\n * @notice Divides one `Unsigned` by an unscaled uint256 and \"ceil's\" the quotient, reverting on overflow or division by 0.\n * @param a a FixedPoint numerator.\n * @param b a uint256 denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {\n // Because it is possible that a quotient gets truncated, we can't just call \"Unsigned(a.rawValue.div(b))\"\n // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.\n // This creates the possibility of overflow if b is very large.\n return divCeil(a, fromUnscaledUint(b));\n }\n\n /**\n * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.\n * @dev This will \"floor\" the result.\n * @param a a FixedPoint numerator.\n * @param b a uint256 denominator.\n * @return output is `a` to the power of `b`.\n */\n function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {\n output = fromUnscaledUint(1);\n for (uint256 i = 0; i < b; i = i.add(1)) {\n output = mul(output, a);\n }\n }\n\n // ------------------------------------------------- SIGNED -------------------------------------------------------------\n // Supports 18 decimals. E.g., 1e18 represents \"1\", 5e17 represents \"0.5\".\n // For signed values:\n // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.\n int256 private constant SFP_SCALING_FACTOR = 10 ** 18;\n\n struct Signed {\n int256 rawValue;\n }\n\n function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {\n require(a.rawValue >= 0, \"Negative value provided\");\n return Unsigned(uint256(a.rawValue));\n }\n\n function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {\n require(a.rawValue <= uint256(type(int256).max), \"Unsigned too large\");\n return Signed(int256(a.rawValue));\n }\n\n /**\n * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.\n * @param a int to convert into a FixedPoint.Signed.\n * @return the converted FixedPoint.Signed.\n */\n function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {\n return Signed(a.mul(SFP_SCALING_FACTOR));\n }\n\n /**\n * @notice Whether `a` is equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b a int256.\n * @return True if equal, or False.\n */\n function isEqual(Signed memory a, int256 b) internal pure returns (bool) {\n return a.rawValue == fromUnscaledInt(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return True if equal, or False.\n */\n function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {\n return a.rawValue == b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {\n return a.rawValue > b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {\n return a.rawValue > fromUnscaledInt(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than `b`.\n * @param a an int256.\n * @param b a FixedPoint.Signed.\n * @return True if `a > b`, or False.\n */\n function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {\n return fromUnscaledInt(a).rawValue > b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {\n return a.rawValue >= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {\n return a.rawValue >= fromUnscaledInt(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is greater than or equal to `b`.\n * @param a an int256.\n * @param b a FixedPoint.Signed.\n * @return True if `a >= b`, or False.\n */\n function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {\n return fromUnscaledInt(a).rawValue >= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return True if `a < b`, or False.\n */\n function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {\n return a.rawValue < b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return True if `a < b`, or False.\n */\n function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {\n return a.rawValue < fromUnscaledInt(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is less than `b`.\n * @param a an int256.\n * @param b a FixedPoint.Signed.\n * @return True if `a < b`, or False.\n */\n function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {\n return fromUnscaledInt(a).rawValue < b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {\n return a.rawValue <= b.rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {\n return a.rawValue <= fromUnscaledInt(b).rawValue;\n }\n\n /**\n * @notice Whether `a` is less than or equal to `b`.\n * @param a an int256.\n * @param b a FixedPoint.Signed.\n * @return True if `a <= b`, or False.\n */\n function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {\n return fromUnscaledInt(a).rawValue <= b.rawValue;\n }\n\n /**\n * @notice The minimum of `a` and `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the minimum of `a` and `b`.\n */\n function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n return a.rawValue < b.rawValue ? a : b;\n }\n\n /**\n * @notice The maximum of `a` and `b`.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the maximum of `a` and `b`.\n */\n function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n return a.rawValue > b.rawValue ? a : b;\n }\n\n /**\n * @notice Adds two `Signed`s, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the sum of `a` and `b`.\n */\n function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n return Signed(a.rawValue.add(b.rawValue));\n }\n\n /**\n * @notice Adds an `Signed` to an unscaled int, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return the sum of `a` and `b`.\n */\n function add(Signed memory a, int256 b) internal pure returns (Signed memory) {\n return add(a, fromUnscaledInt(b));\n }\n\n /**\n * @notice Subtracts two `Signed`s, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the difference of `a` and `b`.\n */\n function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n return Signed(a.rawValue.sub(b.rawValue));\n }\n\n /**\n * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return the difference of `a` and `b`.\n */\n function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {\n return sub(a, fromUnscaledInt(b));\n }\n\n /**\n * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.\n * @param a an int256.\n * @param b a FixedPoint.Signed.\n * @return the difference of `a` and `b`.\n */\n function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {\n return sub(fromUnscaledInt(a), b);\n }\n\n /**\n * @notice Multiplies two `Signed`s, reverting on overflow.\n * @dev This will \"floor\" the product.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the product of `a` and `b`.\n */\n function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n // There are two caveats with this computation:\n // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is\n // stored internally as an int256 ~10^59.\n // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which\n // would round to 3, but this computation produces the result 2.\n // No need to use SafeMath because SFP_SCALING_FACTOR != 0.\n return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);\n }\n\n /**\n * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.\n * @dev This will \"floor\" the product.\n * @param a a FixedPoint.Signed.\n * @param b an int256.\n * @return the product of `a` and `b`.\n */\n function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {\n return Signed(a.rawValue.mul(b));\n }\n\n /**\n * @notice Multiplies two `Signed`s and \"ceil's\" the product, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the product of `a` and `b`.\n */\n function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n int256 mulRaw = a.rawValue.mul(b.rawValue);\n int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;\n // Manual mod because SignedSafeMath doesn't support it.\n int256 mod = mulRaw % SFP_SCALING_FACTOR;\n if (mod != 0) {\n bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);\n int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);\n return Signed(mulTowardsZero.add(valueToAdd));\n } else {\n return Signed(mulTowardsZero);\n }\n }\n\n /**\n * @notice Multiplies an `Signed` and an unscaled int256 and \"ceil's\" the product, reverting on overflow.\n * @param a a FixedPoint.Signed.\n * @param b a FixedPoint.Signed.\n * @return the product of `a` and `b`.\n */\n function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {\n // Since b is an int, there is no risk of truncation and we can just mul it normally\n return Signed(a.rawValue.mul(b));\n }\n\n /**\n * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a a FixedPoint numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n // There are two caveats with this computation:\n // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.\n // 10^41 is stored internally as an int256 10^59.\n // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which\n // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.\n return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));\n }\n\n /**\n * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a a FixedPoint numerator.\n * @param b an int256 denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(Signed memory a, int256 b) internal pure returns (Signed memory) {\n return Signed(a.rawValue.div(b));\n }\n\n /**\n * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.\n * @dev This will \"floor\" the quotient.\n * @param a an int256 numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function div(int256 a, Signed memory b) internal pure returns (Signed memory) {\n return div(fromUnscaledInt(a), b);\n }\n\n /**\n * @notice Divides one `Signed` by an `Signed` and \"ceil's\" the quotient, reverting on overflow or division by 0.\n * @param a a FixedPoint numerator.\n * @param b a FixedPoint denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {\n int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);\n int256 divTowardsZero = aScaled.div(b.rawValue);\n // Manual mod because SignedSafeMath doesn't support it.\n int256 mod = aScaled % b.rawValue;\n if (mod != 0) {\n bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);\n int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);\n return Signed(divTowardsZero.add(valueToAdd));\n } else {\n return Signed(divTowardsZero);\n }\n }\n\n /**\n * @notice Divides one `Signed` by an unscaled int256 and \"ceil's\" the quotient, reverting on overflow or division by 0.\n * @param a a FixedPoint numerator.\n * @param b an int256 denominator.\n * @return the quotient of `a` divided by `b`.\n */\n function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {\n // Because it is possible that a quotient gets truncated, we can't just call \"Signed(a.rawValue.div(b))\"\n // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.\n // This creates the possibility of overflow if b is very large.\n return divAwayFromZero(a, fromUnscaledInt(b));\n }\n\n /**\n * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.\n * @dev This will \"floor\" the result.\n * @param a a FixedPoint.Signed.\n * @param b a uint256 (negative exponents are not allowed).\n * @return output is `a` to the power of `b`.\n */\n function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {\n output = fromUnscaledInt(1);\n for (uint256 i = 0; i < b; i = i.add(1)) {\n output = mul(output, a);\n }\n }\n}\n" }, "contracts/interfaces/IBackerRewards.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.12;\n\npragma experimental ABIEncoderV2;\n\ninterface IBackerRewards {\n function allocateRewards(uint256 _interestPaymentAmount) external;\n\n function onTranchedPoolDrawdown(uint256 sliceIndex) external;\n\n function setPoolTokenAccRewardsPerPrincipalDollarAtMint(\n address poolAddress,\n uint256 tokenId\n ) external;\n}\n" }, "contracts/interfaces/ICUSDCContract.sol": { "content": "// SPDX-License-Identifier: MIT\n// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./IERC20withDec.sol\";\n\ninterface ICUSDCContract is IERC20withDec {\n /*** User Interface ***/\n\n function mint(uint256 mintAmount) external returns (uint256);\n\n function redeem(uint256 redeemTokens) external returns (uint256);\n\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\n\n function borrow(uint256 borrowAmount) external returns (uint256);\n\n function repayBorrow(uint256 repayAmount) external returns (uint256);\n\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\n\n function liquidateBorrow(\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral\n ) external returns (uint256);\n\n function getAccountSnapshot(\n address account\n ) external view returns (uint256, uint256, uint256, uint256);\n\n function balanceOfUnderlying(address owner) external returns (uint256);\n\n function exchangeRateCurrent() external returns (uint256);\n\n /*** Admin Functions ***/\n\n function _addReserves(uint256 addAmount) external returns (uint256);\n}\n" }, "contracts/interfaces/ICreditLine.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\ninterface ICreditLine {\n function borrower() external view returns (address);\n\n function limit() external view returns (uint256);\n\n function maxLimit() external view returns (uint256);\n\n function interestApr() external view returns (uint256);\n\n function paymentPeriodInDays() external view returns (uint256);\n\n function principalGracePeriodInDays() external view returns (uint256);\n\n function termInDays() external view returns (uint256);\n\n function lateFeeApr() external view returns (uint256);\n\n function isLate() external view returns (bool);\n\n function withinPrincipalGracePeriod() external view returns (bool);\n\n // Accounting variables\n function balance() external view returns (uint256);\n\n function interestOwed() external view returns (uint256);\n\n function principalOwed() external view returns (uint256);\n\n function termEndTime() external view returns (uint256);\n\n function nextDueTime() external view returns (uint256);\n\n function interestAccruedAsOf() external view returns (uint256);\n\n function lastFullPaymentTime() external view returns (uint256);\n}\n" }, "contracts/interfaces/ICurveLP.sol": { "content": "// SPDX-License-Identifier: MIT\n// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\ninterface ICurveLP {\n function coins(uint256) external view returns (address);\n\n function token() external view returns (address);\n\n function calc_token_amount(uint256[2] calldata amounts) external view returns (uint256);\n\n function lp_price() external view returns (uint256);\n\n function add_liquidity(\n uint256[2] calldata amounts,\n uint256 min_mint_amount,\n bool use_eth,\n address receiver\n ) external returns (uint256);\n\n function remove_liquidity(\n uint256 _amount,\n uint256[2] calldata min_amounts\n ) external returns (uint256);\n\n function remove_liquidity_one_coin(\n uint256 token_amount,\n uint256 i,\n uint256 min_amount\n ) external returns (uint256);\n\n function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256);\n\n function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external returns (uint256);\n\n function balances(uint256 arg0) external view returns (uint256);\n}\n" }, "contracts/interfaces/IERC20withDec.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {IERC20} from \"@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol\";\n\n/*\nOnly addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.\n*/\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20withDec is IERC20 {\n /**\n * @dev Returns the number of decimals used for the token\n */\n function decimals() external view returns (uint8);\n}\n" }, "contracts/interfaces/IFidu.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./IERC20withDec.sol\";\n\ninterface IFidu is IERC20withDec {\n function mintTo(address to, uint256 amount) external;\n\n function burnFrom(address to, uint256 amount) external;\n\n function renounceRole(bytes32 role, address account) external;\n}\n" }, "contracts/interfaces/IGo.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nabstract contract IGo {\n uint256 public constant ID_TYPE_0 = 0;\n uint256 public constant ID_TYPE_1 = 1;\n uint256 public constant ID_TYPE_2 = 2;\n uint256 public constant ID_TYPE_3 = 3;\n uint256 public constant ID_TYPE_4 = 4;\n uint256 public constant ID_TYPE_5 = 5;\n uint256 public constant ID_TYPE_6 = 6;\n uint256 public constant ID_TYPE_7 = 7;\n uint256 public constant ID_TYPE_8 = 8;\n uint256 public constant ID_TYPE_9 = 9;\n uint256 public constant ID_TYPE_10 = 10;\n\n /// @notice Returns the address of the UniqueIdentity contract.\n function uniqueIdentity() external virtual returns (address);\n\n function go(address account) public view virtual returns (bool);\n\n function goOnlyIdTypes(\n address account,\n uint256[] calldata onlyIdTypes\n ) public view virtual returns (bool);\n\n /**\n * @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol.\n * @param account The account whose go status to obtain\n * @return true if `account` is go listed\n */\n function goSeniorPool(address account) public view virtual returns (bool);\n}\n" }, "contracts/interfaces/IGoldfinchConfig.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\ninterface IGoldfinchConfig {\n function getNumber(uint256 index) external returns (uint256);\n\n function getAddress(uint256 index) external returns (address);\n\n function setAddress(uint256 index, address newAddress) external returns (address);\n\n function setNumber(uint256 index, uint256 newNumber) external returns (uint256);\n}\n" }, "contracts/interfaces/IGoldfinchFactory.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\ninterface IGoldfinchFactory {\n function createCreditLine() external returns (address);\n\n function createBorrower(address owner) external returns (address);\n\n function createPool(\n address _borrower,\n uint256 _juniorFeePercent,\n uint256 _limit,\n uint256 _interestApr,\n uint256 _paymentPeriodInDays,\n uint256 _termInDays,\n uint256 _lateFeeApr,\n uint256[] calldata _allowedUIDTypes\n ) external returns (address);\n\n function createMigratedPool(\n address _borrower,\n uint256 _juniorFeePercent,\n uint256 _limit,\n uint256 _interestApr,\n uint256 _paymentPeriodInDays,\n uint256 _termInDays,\n uint256 _lateFeeApr,\n uint256[] calldata _allowedUIDTypes\n ) external returns (address);\n}\n" }, "contracts/interfaces/IPoolTokens.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./openzeppelin/IERC721.sol\";\n\ninterface IPoolTokens is IERC721 {\n event TokenMinted(\n address indexed owner,\n address indexed pool,\n uint256 indexed tokenId,\n uint256 amount,\n uint256 tranche\n );\n\n event TokenRedeemed(\n address indexed owner,\n address indexed pool,\n uint256 indexed tokenId,\n uint256 principalRedeemed,\n uint256 interestRedeemed,\n uint256 tranche\n );\n event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);\n\n struct TokenInfo {\n address pool;\n uint256 tranche;\n uint256 principalAmount;\n uint256 principalRedeemed;\n uint256 interestRedeemed;\n }\n\n struct MintParams {\n uint256 principalAmount;\n uint256 tranche;\n }\n\n function mint(MintParams calldata params, address to) external returns (uint256);\n\n function redeem(uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed) external;\n\n function withdrawPrincipal(uint256 tokenId, uint256 principalAmount) external;\n\n function burn(uint256 tokenId) external;\n\n function onPoolCreated(address newPool) external;\n\n function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);\n\n function validPool(address sender) external view returns (bool);\n\n function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);\n}\n" }, "contracts/interfaces/ISeniorPool.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {ITranchedPool} from \"./ITranchedPool.sol\";\nimport {ISeniorPoolEpochWithdrawals} from \"./ISeniorPoolEpochWithdrawals.sol\";\n\nabstract contract ISeniorPool is ISeniorPoolEpochWithdrawals {\n uint256 public sharePrice;\n uint256 public totalLoansOutstanding;\n uint256 public totalWritedowns;\n\n function deposit(uint256 amount) external virtual returns (uint256 depositShares);\n\n function depositWithPermit(\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external virtual returns (uint256 depositShares);\n\n /**\n * @notice Withdraw `usdcAmount` of USDC, bypassing the epoch withdrawal system. Callable\n * by Zapper only.\n */\n function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);\n\n /**\n * @notice Withdraw `fiduAmount` of FIDU converted to USDC at the current share price,\n * bypassing the epoch withdrawal system. Callable by Zapper only\n */\n function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);\n\n function invest(ITranchedPool pool) external virtual returns (uint256);\n\n function estimateInvestment(ITranchedPool pool) external view virtual returns (uint256);\n\n function redeem(uint256 tokenId) external virtual;\n\n function writedown(uint256 tokenId) external virtual;\n\n function calculateWritedown(\n uint256 tokenId\n ) external view virtual returns (uint256 writedownAmount);\n\n function sharesOutstanding() external view virtual returns (uint256);\n\n function assets() external view virtual returns (uint256);\n\n function getNumShares(uint256 amount) public view virtual returns (uint256);\n\n event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);\n event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);\n event InterestCollected(address indexed payer, uint256 amount);\n event PrincipalCollected(address indexed payer, uint256 amount);\n event ReserveFundsCollected(address indexed user, uint256 amount);\n event ReserveSharesCollected(address indexed user, address indexed reserve, uint256 amount);\n\n event PrincipalWrittenDown(address indexed tranchedPool, int256 amount);\n event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount);\n event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount);\n}\n" }, "contracts/interfaces/ISeniorPoolEpochWithdrawals.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\n\npragma experimental ABIEncoderV2;\n\ninterface ISeniorPoolEpochWithdrawals {\n /**\n * @notice A withdrawal epoch\n * @param endsAt timestamp the epoch ends\n * @param fiduRequested amount of fidu requested in the epoch, including fidu\n * carried over from previous epochs\n * @param fiduLiquidated Amount of fidu that was liquidated at the end of this epoch\n * @param usdcAllocated Amount of usdc that was allocated to liquidate fidu.\n * Does not consider withdrawal fees.\n */\n struct Epoch {\n uint256 endsAt;\n uint256 fiduRequested;\n uint256 fiduLiquidated;\n uint256 usdcAllocated;\n }\n\n /**\n * @notice A user's request for withdrawal\n * @param epochCursor id of next epoch the user can liquidate their request\n * @param fiduRequested amount of fidu left to liquidate since last checkpoint\n * @param usdcWithdrawable amount of usdc available for a user to withdraw\n */\n struct WithdrawalRequest {\n uint256 epochCursor;\n uint256 usdcWithdrawable;\n uint256 fiduRequested;\n }\n\n /**\n * @notice Returns the amount of unallocated usdc in the senior pool, taking into account\n * usdc that _will_ be allocated to withdrawals when a checkpoint happens\n */\n function usdcAvailable() external view returns (uint256);\n\n /// @notice Current duration of withdrawal epochs, in seconds\n function epochDuration() external view returns (uint256);\n\n /// @notice Update epoch duration\n function setEpochDuration(uint256 newEpochDuration) external;\n\n /// @notice The current withdrawal epoch\n function currentEpoch() external view returns (Epoch memory);\n\n /// @notice Get request by tokenId. A request is considered active if epochCursor > 0.\n function withdrawalRequest(uint256 tokenId) external view returns (WithdrawalRequest memory);\n\n /**\n * @notice Submit a request to withdraw `fiduAmount` of FIDU. Request is rejected\n * if caller already owns a request token. A non-transferrable request token is\n * minted to the caller\n * @return tokenId token minted to caller\n */\n function requestWithdrawal(uint256 fiduAmount) external returns (uint256 tokenId);\n\n /**\n * @notice Add `fiduAmount` FIDU to a withdrawal request for `tokenId`. Caller\n * must own tokenId\n */\n function addToWithdrawalRequest(uint256 fiduAmount, uint256 tokenId) external;\n\n /**\n * @notice Cancel request for tokenId. The fiduRequested (minus a fee) is returned\n * to the caller. Caller must own tokenId.\n * @return fiduReceived the fidu amount returned to the caller\n */\n function cancelWithdrawalRequest(uint256 tokenId) external returns (uint256 fiduReceived);\n\n /**\n * @notice Transfer the usdcWithdrawable of request for tokenId to the caller.\n * Caller must own tokenId\n */\n function claimWithdrawalRequest(uint256 tokenId) external returns (uint256 usdcReceived);\n\n /// @notice Emitted when the epoch duration is changed\n event EpochDurationChanged(uint256 newDuration);\n\n /// @notice Emitted when a new withdraw request has been created\n event WithdrawalRequested(\n uint256 indexed epochId,\n uint256 indexed tokenId,\n address indexed operator,\n uint256 fiduRequested\n );\n\n /// @notice Emitted when a user adds to their existing withdraw request\n /// @param epochId epoch that the withdraw was added to\n /// @param tokenId id of token that represents the position being added to\n /// @param operator address that added to the request\n /// @param fiduRequested amount of additional fidu added to request\n event WithdrawalAddedTo(\n uint256 indexed epochId,\n uint256 indexed tokenId,\n address indexed operator,\n uint256 fiduRequested\n );\n\n /// @notice Emitted when a withdraw request has been canceled\n event WithdrawalCanceled(\n uint256 indexed epochId,\n uint256 indexed tokenId,\n address indexed operator,\n uint256 fiduCanceled,\n uint256 reserveFidu\n );\n\n /// @notice Emitted when an epoch has been checkpointed\n /// @param epochId id of epoch that ended\n /// @param endTime timestamp the epoch ended\n /// @param fiduRequested amount of FIDU oustanding when the epoch ended\n /// @param usdcAllocated amount of USDC allocated to liquidate FIDU\n /// @param fiduLiquidated amount of FIDU liquidated using `usdcAllocated`\n event EpochEnded(\n uint256 indexed epochId,\n uint256 endTime,\n uint256 fiduRequested,\n uint256 usdcAllocated,\n uint256 fiduLiquidated\n );\n\n /// @notice Emitted when an epoch could not be finalized and is extended instead\n /// @param epochId id of epoch that was extended\n /// @param newEndTime new epoch end time\n /// @param oldEndTime previous epoch end time\n event EpochExtended(uint256 indexed epochId, uint256 newEndTime, uint256 oldEndTime);\n}\n" }, "contracts/interfaces/ISeniorPoolStrategy.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./ISeniorPool.sol\";\nimport \"./ITranchedPool.sol\";\n\nabstract contract ISeniorPoolStrategy {\n function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);\n\n function invest(\n ISeniorPool seniorPool,\n ITranchedPool pool\n ) public view virtual returns (uint256 amount);\n\n function estimateInvestment(\n ISeniorPool seniorPool,\n ITranchedPool pool\n ) public view virtual returns (uint256);\n}\n" }, "contracts/interfaces/IStakingRewards.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.12;\n\npragma experimental ABIEncoderV2;\n\nimport {IERC721} from \"./openzeppelin/IERC721.sol\";\nimport {IERC721Metadata} from \"./openzeppelin/IERC721Metadata.sol\";\nimport {IERC721Enumerable} from \"./openzeppelin/IERC721Enumerable.sol\";\n\ninterface IStakingRewards is IERC721, IERC721Metadata, IERC721Enumerable {\n function getPosition(uint256 tokenId) external view returns (StakedPosition memory position);\n\n function unstake(uint256 tokenId, uint256 amount) external;\n\n function addToStake(uint256 tokenId, uint256 amount) external;\n\n function stakedBalanceOf(uint256 tokenId) external view returns (uint256);\n\n function depositToCurveAndStakeFrom(\n address nftRecipient,\n uint256 fiduAmount,\n uint256 usdcAmount\n ) external;\n\n function kick(uint256 tokenId) external;\n\n function accumulatedRewardsPerToken() external view returns (uint256);\n\n function lastUpdateTime() external view returns (uint256);\n\n /* ========== EVENTS ========== */\n\n event RewardAdded(uint256 reward);\n event Staked(\n address indexed user,\n uint256 indexed tokenId,\n uint256 amount,\n StakedPositionType positionType,\n uint256 baseTokenExchangeRate\n );\n event DepositedAndStaked(\n address indexed user,\n uint256 depositedAmount,\n uint256 indexed tokenId,\n uint256 amount\n );\n event DepositedToCurve(\n address indexed user,\n uint256 fiduAmount,\n uint256 usdcAmount,\n uint256 tokensReceived\n );\n event DepositedToCurveAndStaked(\n address indexed user,\n uint256 fiduAmount,\n uint256 usdcAmount,\n uint256 indexed tokenId,\n uint256 amount\n );\n event AddToStake(\n address indexed user,\n uint256 indexed tokenId,\n uint256 amount,\n StakedPositionType positionType\n );\n event Unstaked(\n address indexed user,\n uint256 indexed tokenId,\n uint256 amount,\n StakedPositionType positionType\n );\n event UnstakedMultiple(address indexed user, uint256[] tokenIds, uint256[] amounts);\n event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward);\n event RewardsParametersUpdated(\n address indexed who,\n uint256 targetCapacity,\n uint256 minRate,\n uint256 maxRate,\n uint256 minRateAtPercent,\n uint256 maxRateAtPercent\n );\n event EffectiveMultiplierUpdated(\n address indexed who,\n StakedPositionType positionType,\n uint256 multiplier\n );\n}\n\n/// @notice Indicates which ERC20 is staked\nenum StakedPositionType {\n Fidu,\n CurveLP\n}\n\nstruct Rewards {\n uint256 totalUnvested;\n uint256 totalVested;\n // @dev DEPRECATED (definition kept for storage slot)\n // For legacy vesting positions, this was used in the case of slashing.\n // For non-vesting positions, this is unused.\n uint256 totalPreviouslyVested;\n uint256 totalClaimed;\n uint256 startTime;\n // @dev DEPRECATED (definition kept for storage slot)\n // For legacy vesting positions, this is the endTime of the vesting.\n // For non-vesting positions, this is 0.\n uint256 endTime;\n}\n\nstruct StakedPosition {\n // @notice Staked amount denominated in `stakingToken().decimals()`\n uint256 amount;\n // @notice Struct describing rewards owed with vesting\n Rewards rewards;\n // @notice Multiplier applied to staked amount when locking up position\n uint256 leverageMultiplier;\n // @notice Time in seconds after which position can be unstaked\n uint256 lockedUntil;\n // @notice Type of the staked position\n StakedPositionType positionType;\n // @notice Multiplier applied to staked amount to denominate in `baseStakingToken().decimals()`\n // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.\n // If you need this field, use `safeEffectiveMultiplier()`, which correctly handles old staked positions.\n uint256 unsafeEffectiveMultiplier;\n // @notice Exchange rate applied to staked amount to denominate in `baseStakingToken().decimals()`\n // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1.\n // If you need this field, use `safeBaseTokenExchangeRate()`, which correctly handles old staked positions.\n uint256 unsafeBaseTokenExchangeRate;\n}\n" }, "contracts/interfaces/ITranchedPool.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {IV2CreditLine} from \"./IV2CreditLine.sol\";\n\nabstract contract ITranchedPool {\n IV2CreditLine public creditLine;\n uint256 public createdAt;\n enum Tranches {\n Reserved,\n Senior,\n Junior\n }\n\n struct TrancheInfo {\n uint256 id;\n uint256 principalDeposited;\n uint256 principalSharePrice;\n uint256 interestSharePrice;\n uint256 lockedUntil;\n }\n\n struct PoolSlice {\n TrancheInfo seniorTranche;\n TrancheInfo juniorTranche;\n uint256 totalInterestAccrued;\n uint256 principalDeployed;\n }\n\n function initialize(\n address _config,\n address _borrower,\n uint256 _juniorFeePercent,\n uint256 _limit,\n uint256 _interestApr,\n uint256 _paymentPeriodInDays,\n uint256 _termInDays,\n uint256 _lateFeeApr,\n uint256 _principalGracePeriodInDays,\n uint256 _fundableAt,\n uint256[] calldata _allowedUIDTypes\n ) public virtual;\n\n function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);\n\n function pay(uint256 amount) external virtual;\n\n function poolSlices(uint256 index) external view virtual returns (PoolSlice memory);\n\n function lockJuniorCapital() external virtual;\n\n function lockPool() external virtual;\n\n function initializeNextSlice(uint256 _fundableAt) external virtual;\n\n function totalJuniorDeposits() external view virtual returns (uint256);\n\n function drawdown(uint256 amount) external virtual;\n\n function setFundableAt(uint256 timestamp) external virtual;\n\n function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);\n\n function assess() external virtual;\n\n function depositWithPermit(\n uint256 tranche,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external virtual returns (uint256 tokenId);\n\n function availableToWithdraw(\n uint256 tokenId\n ) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable);\n\n function withdraw(\n uint256 tokenId,\n uint256 amount\n ) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn);\n\n function withdrawMax(\n uint256 tokenId\n ) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn);\n\n function withdrawMultiple(\n uint256[] calldata tokenIds,\n uint256[] calldata amounts\n ) external virtual;\n\n function numSlices() external view virtual returns (uint256);\n}\n" }, "contracts/interfaces/IV2CreditLine.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./ICreditLine.sol\";\n\nabstract contract IV2CreditLine is ICreditLine {\n function principal() external view virtual returns (uint256);\n\n function totalInterestAccrued() external view virtual returns (uint256);\n\n function termStartTime() external view virtual returns (uint256);\n\n function setLimit(uint256 newAmount) external virtual;\n\n function setMaxLimit(uint256 newAmount) external virtual;\n\n function setBalance(uint256 newBalance) external virtual;\n\n function setPrincipal(uint256 _principal) external virtual;\n\n function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;\n\n function drawdown(uint256 amount) external virtual;\n\n function assess() external virtual returns (uint256, uint256, uint256);\n\n function initialize(\n address _config,\n address owner,\n address _borrower,\n uint256 _limit,\n uint256 _interestApr,\n uint256 _paymentPeriodInDays,\n uint256 _termInDays,\n uint256 _lateFeeApr,\n uint256 _principalGracePeriodInDays\n ) public virtual;\n\n function setTermEndTime(uint256 newTermEndTime) external virtual;\n\n function setNextDueTime(uint256 newNextDueTime) external virtual;\n\n function setInterestOwed(uint256 newInterestOwed) external virtual;\n\n function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;\n\n function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;\n\n function setWritedownAmount(uint256 newWritedownAmount) external virtual;\n\n function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;\n\n function setLateFeeApr(uint256 newLateFeeApr) external virtual;\n}\n" }, "contracts/interfaces/IWithdrawalRequestToken.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {IERC721Enumerable} from \"./openzeppelin/IERC721Enumerable.sol\";\n\ninterface IWithdrawalRequestToken is IERC721Enumerable {\n /// @notice Mint a withdrawal request token to `receiver`\n /// @dev succeeds if and only if called by senior pool\n function mint(address receiver) external returns (uint256 tokenId);\n\n /// @notice Burn token `tokenId`\n /// @dev suceeds if and only if called by senior pool\n function burn(uint256 tokenId) external;\n}\n" }, "contracts/interfaces/openzeppelin/IERC165.sol": { "content": "pragma solidity >=0.6.0;\n\n// This file copied from OZ, but with the version pragma updated to use >=.\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "contracts/interfaces/openzeppelin/IERC721.sol": { "content": "pragma solidity >=0.6.2;\n\n// This file copied from OZ, but with the version pragma updated to use >= & reference other >= pragma interfaces.\n// NOTE: Modified to reference our updated pragma version of IERC165\nimport \"./IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of NFTs in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the NFT specified by `tokenId`.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to\n * another (`to`).\n *\n *\n *\n * Requirements:\n * - `from`, `to` cannot be zero.\n * - `tokenId` must be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this\n * NFT by either {approve} or {setApprovalForAll}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to\n * another (`to`).\n *\n * Requirements:\n * - If the caller is not `from`, it must be approved to move this NFT by\n * either {approve} or {setApprovalForAll}.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n function approve(address to, uint256 tokenId) external;\n\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n function setApprovalForAll(address operator, bool _approved) external;\n\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n" }, "contracts/interfaces/openzeppelin/IERC721Enumerable.sol": { "content": "pragma solidity >=0.6.2;\n\n// This file copied from OZ, but with the version pragma updated to use >=.\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n function totalSupply() external view returns (uint256);\n\n function tokenOfOwnerByIndex(\n address owner,\n uint256 index\n ) external view returns (uint256 tokenId);\n\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n" }, "contracts/interfaces/openzeppelin/IERC721Metadata.sol": { "content": "pragma solidity >=0.6.2;\n\n// This file copied from OZ, but with the version pragma updated to use >=.\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" }, "contracts/protocol/core/Accountant.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./CreditLine.sol\";\nimport \"../../interfaces/ICreditLine.sol\";\nimport \"../../external/FixedPoint.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol\";\n\n/**\n * @title The Accountant\n * @notice Library for handling key financial calculations, such as interest and principal accrual.\n * @author Goldfinch\n */\n\nlibrary Accountant {\n using SafeMath for uint256;\n using FixedPoint for FixedPoint.Signed;\n using FixedPoint for FixedPoint.Unsigned;\n using FixedPoint for int256;\n using FixedPoint for uint256;\n\n // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled\n uint256 private constant FP_SCALING_FACTOR = 10 ** 18;\n uint256 private constant INTEREST_DECIMALS = 1e18;\n uint256 private constant SECONDS_PER_DAY = 60 * 60 * 24;\n uint256 private constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365);\n\n struct PaymentAllocation {\n uint256 interestPayment;\n uint256 principalPayment;\n uint256 additionalBalancePayment;\n }\n\n function calculateInterestAndPrincipalAccrued(\n CreditLine cl,\n uint256 timestamp,\n uint256 lateFeeGracePeriod\n ) public view returns (uint256, uint256) {\n uint256 balance = cl.balance(); // gas optimization\n uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod);\n uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp);\n return (interestAccrued, principalAccrued);\n }\n\n function calculateInterestAndPrincipalAccruedOverPeriod(\n CreditLine cl,\n uint256 balance,\n uint256 startTime,\n uint256 endTime,\n uint256 lateFeeGracePeriod\n ) public view returns (uint256, uint256) {\n uint256 interestAccrued = calculateInterestAccruedOverPeriod(\n cl,\n balance,\n startTime,\n endTime,\n lateFeeGracePeriod\n );\n uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime);\n return (interestAccrued, principalAccrued);\n }\n\n function calculatePrincipalAccrued(\n ICreditLine cl,\n uint256 balance,\n uint256 timestamp\n ) public view returns (uint256) {\n // If we've already accrued principal as of the term end time, then don't accrue more principal\n uint256 termEndTime = cl.termEndTime();\n if (cl.interestAccruedAsOf() >= termEndTime) {\n return 0;\n }\n if (timestamp >= termEndTime) {\n return balance;\n } else {\n return 0;\n }\n }\n\n function calculateWritedownFor(\n ICreditLine cl,\n uint256 timestamp,\n uint256 gracePeriodInDays,\n uint256 maxDaysLate\n ) public view returns (uint256, uint256) {\n return\n calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate);\n }\n\n function calculateWritedownForPrincipal(\n ICreditLine cl,\n uint256 principal,\n uint256 timestamp,\n uint256 gracePeriodInDays,\n uint256 maxDaysLate\n ) public view returns (uint256, uint256) {\n FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);\n if (amountOwedPerDay.isEqual(0)) {\n return (0, 0);\n }\n FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays);\n FixedPoint.Unsigned memory daysLate;\n\n // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,\n // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term\n // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to\n // calculate the periods later.\n uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());\n daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);\n if (timestamp > cl.termEndTime()) {\n uint256 secondsLate = timestamp.sub(cl.termEndTime());\n daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY));\n }\n\n FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);\n FixedPoint.Unsigned memory writedownPercent;\n if (daysLate.isLessThanOrEqual(fpGracePeriod)) {\n // Within the grace period, we don't have to write down, so assume 0%\n writedownPercent = FixedPoint.fromUnscaledUint(0);\n } else {\n writedownPercent = FixedPoint.min(\n FixedPoint.fromUnscaledUint(1),\n (daysLate.sub(fpGracePeriod)).div(maxLate)\n );\n }\n\n FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(\n FP_SCALING_FACTOR\n );\n // This will return a number between 0-100 representing the write down percent with no decimals\n uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;\n return (unscaledWritedownPercent, writedownAmount.rawValue);\n }\n\n function calculateAmountOwedForOneDay(\n ICreditLine cl\n ) public view returns (FixedPoint.Unsigned memory) {\n // Determine theoretical interestOwed for one full day\n uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);\n FixedPoint.Unsigned memory interestOwedForOneDay = FixedPoint\n .fromUnscaledUint(totalInterestPerYear)\n .div(365);\n return interestOwedForOneDay.add(cl.principalOwed());\n }\n\n function calculateInterestAccrued(\n CreditLine cl,\n uint256 balance,\n uint256 timestamp,\n uint256 lateFeeGracePeriodInDays\n ) public view returns (uint256) {\n // We use Math.min here to prevent integer overflow (ie. go negative) when calculating\n // numSecondsElapsed. Typically this shouldn't be possible, because\n // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing\n // we allow this function to be called with a past timestamp, which raises the possibility\n // of overflow.\n // This use of min should not generate incorrect interest calculations, since\n // this function's purpose is just to normalize balances, and handing in a past timestamp\n // will necessarily return zero interest accrued (because zero elapsed time), which is correct.\n uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf());\n return\n calculateInterestAccruedOverPeriod(\n cl,\n balance,\n startTime,\n timestamp,\n lateFeeGracePeriodInDays\n );\n }\n\n function calculateInterestAccruedOverPeriod(\n CreditLine cl,\n uint256 balance,\n uint256 startTime,\n uint256 endTime,\n uint256 lateFeeGracePeriodInDays\n ) public view returns (uint256 interestOwed) {\n uint256 secondsElapsed = endTime.sub(startTime);\n uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS);\n uint256 normalInterestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR);\n\n // Interest accrued in the current period isn't owed until nextDueTime. After that the borrower\n // has a grace period before late fee interest starts to accrue. This grace period applies for\n // every due time (termEndTime is not a special case).\n uint256 lateFeeInterestOwed = 0;\n uint256 lateFeeStartsAt = Math.max(\n startTime,\n cl.nextDueTime().add(lateFeeGracePeriodInDays.mul(SECONDS_PER_DAY))\n );\n if (lateFeeStartsAt < endTime) {\n uint256 lateSecondsElapsed = endTime.sub(lateFeeStartsAt);\n uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);\n lateFeeInterestOwed = lateFeeInterestPerYear.mul(lateSecondsElapsed).div(SECONDS_PER_YEAR);\n }\n\n return normalInterestOwed.add(lateFeeInterestOwed);\n }\n\n function allocatePayment(\n uint256 paymentAmount,\n uint256 balance,\n uint256 interestOwed,\n uint256 principalOwed\n ) public pure returns (PaymentAllocation memory) {\n uint256 paymentRemaining = paymentAmount;\n uint256 interestPayment = Math.min(interestOwed, paymentRemaining);\n paymentRemaining = paymentRemaining.sub(interestPayment);\n\n uint256 principalPayment = Math.min(principalOwed, paymentRemaining);\n paymentRemaining = paymentRemaining.sub(principalPayment);\n\n uint256 balanceRemaining = balance.sub(principalPayment);\n uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);\n\n return\n PaymentAllocation({\n interestPayment: interestPayment,\n principalPayment: principalPayment,\n additionalBalancePayment: additionalBalancePayment\n });\n }\n}\n" }, "contracts/protocol/core/BaseUpgradeablePausable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol\";\nimport \"./PauserPausable.sol\";\n\n/**\n * @title BaseUpgradeablePausable contract\n * @notice This is our Base contract that most other contracts inherit from. It includes many standard\n * useful abilities like upgradeability, pausability, access control, and re-entrancy guards.\n * @author Goldfinch\n */\n\ncontract BaseUpgradeablePausable is\n Initializable,\n AccessControlUpgradeSafe,\n PauserPausable,\n ReentrancyGuardUpgradeSafe\n{\n bytes32 public constant OWNER_ROLE = keccak256(\"OWNER_ROLE\");\n using SafeMath for uint256;\n // Pre-reserving a few slots in the base contract in case we need to add things in the future.\n // This does not actually take up gas cost or storage cost, but it does reserve the storage slots.\n // See OpenZeppelin's use of this pattern here:\n // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37\n uint256[50] private __gap1;\n uint256[50] private __gap2;\n uint256[50] private __gap3;\n uint256[50] private __gap4;\n\n // solhint-disable-next-line func-name-mixedcase\n function __BaseUpgradeablePausable__init(address owner) public initializer {\n require(owner != address(0), \"Owner cannot be the zero address\");\n __AccessControl_init_unchained();\n __Pausable_init_unchained();\n __ReentrancyGuard_init_unchained();\n\n _setupRole(OWNER_ROLE, owner);\n _setupRole(PAUSER_ROLE, owner);\n\n _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);\n _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);\n }\n\n function isAdmin() public view returns (bool) {\n return hasRole(OWNER_ROLE, _msgSender());\n }\n\n modifier onlyAdmin() {\n require(isAdmin(), \"Must have admin role to perform this action\");\n _;\n }\n}\n" }, "contracts/protocol/core/ConfigHelper.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {ImplementationRepository} from \"./proxy/ImplementationRepository.sol\";\nimport {ConfigOptions} from \"./ConfigOptions.sol\";\nimport {GoldfinchConfig} from \"./GoldfinchConfig.sol\";\nimport {IFidu} from \"../../interfaces/IFidu.sol\";\nimport {IWithdrawalRequestToken} from \"../../interfaces/IWithdrawalRequestToken.sol\";\nimport {ISeniorPool} from \"../../interfaces/ISeniorPool.sol\";\nimport {ISeniorPoolStrategy} from \"../../interfaces/ISeniorPoolStrategy.sol\";\nimport {IERC20withDec} from \"../../interfaces/IERC20withDec.sol\";\nimport {ICUSDCContract} from \"../../interfaces/ICUSDCContract.sol\";\nimport {IPoolTokens} from \"../../interfaces/IPoolTokens.sol\";\nimport {IBackerRewards} from \"../../interfaces/IBackerRewards.sol\";\nimport {IGoldfinchFactory} from \"../../interfaces/IGoldfinchFactory.sol\";\nimport {IGo} from \"../../interfaces/IGo.sol\";\nimport {IStakingRewards} from \"../../interfaces/IStakingRewards.sol\";\nimport {ICurveLP} from \"../../interfaces/ICurveLP.sol\";\n\n/**\n * @title ConfigHelper\n * @notice A convenience library for getting easy access to other contracts and constants within the\n * protocol, through the use of the GoldfinchConfig contract\n * @author Goldfinch\n */\n\nlibrary ConfigHelper {\n function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {\n return ISeniorPool(seniorPoolAddress(config));\n }\n\n function getSeniorPoolStrategy(\n GoldfinchConfig config\n ) internal view returns (ISeniorPoolStrategy) {\n return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));\n }\n\n function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {\n return IERC20withDec(usdcAddress(config));\n }\n\n function getFidu(GoldfinchConfig config) internal view returns (IFidu) {\n return IFidu(fiduAddress(config));\n }\n\n function getFiduUSDCCurveLP(GoldfinchConfig config) internal view returns (ICurveLP) {\n return ICurveLP(fiduUSDCCurveLPAddress(config));\n }\n\n function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {\n return ICUSDCContract(cusdcContractAddress(config));\n }\n\n function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {\n return IPoolTokens(poolTokensAddress(config));\n }\n\n function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {\n return IBackerRewards(backerRewardsAddress(config));\n }\n\n function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {\n return IGoldfinchFactory(goldfinchFactoryAddress(config));\n }\n\n function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {\n return IERC20withDec(gfiAddress(config));\n }\n\n function getGo(GoldfinchConfig config) internal view returns (IGo) {\n return IGo(goAddress(config));\n }\n\n function getStakingRewards(GoldfinchConfig config) internal view returns (IStakingRewards) {\n return IStakingRewards(stakingRewardsAddress(config));\n }\n\n function getTranchedPoolImplementationRepository(\n GoldfinchConfig config\n ) internal view returns (ImplementationRepository) {\n return\n ImplementationRepository(\n config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementationRepository))\n );\n }\n\n function getWithdrawalRequestToken(\n GoldfinchConfig config\n ) internal view returns (IWithdrawalRequestToken) {\n return\n IWithdrawalRequestToken(\n config.getAddress(uint256(ConfigOptions.Addresses.WithdrawalRequestToken))\n );\n }\n\n function oneInchAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));\n }\n\n function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));\n }\n\n /// @dev deprecated because we no longer use GSN\n function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));\n }\n\n function configAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));\n }\n\n function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));\n }\n\n function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards));\n }\n\n function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));\n }\n\n function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));\n }\n\n function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));\n }\n\n function gfiAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.GFI));\n }\n\n function fiduAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));\n }\n\n function fiduUSDCCurveLPAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.FiduUSDCCurveLP));\n }\n\n function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));\n }\n\n function usdcAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.USDC));\n }\n\n function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));\n }\n\n function reserveAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));\n }\n\n function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));\n }\n\n function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));\n }\n\n function goAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.Go));\n }\n\n function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) {\n return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards));\n }\n\n function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));\n }\n\n function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));\n }\n\n function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));\n }\n\n function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));\n }\n\n function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));\n }\n\n function getTransferRestrictionPeriodInDays(\n GoldfinchConfig config\n ) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));\n }\n\n function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));\n }\n\n function getSeniorPoolWithdrawalCancelationFeeInBps(\n GoldfinchConfig config\n ) internal view returns (uint256) {\n return config.getNumber(uint256(ConfigOptions.Numbers.SeniorPoolWithdrawalCancelationFeeInBps));\n }\n}\n" }, "contracts/protocol/core/ConfigOptions.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\n/**\n * @title ConfigOptions\n * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract\n * @author Goldfinch\n */\n\nlibrary ConfigOptions {\n // NEVER EVER CHANGE THE ORDER OF THESE!\n // You can rename or append. But NEVER change the order.\n enum Numbers {\n TransactionLimit,\n /// @dev: TotalFundsLimit used to represent a total cap on senior pool deposits\n /// but is now deprecated\n TotalFundsLimit,\n MaxUnderwriterLimit,\n ReserveDenominator,\n WithdrawFeeDenominator,\n LatenessGracePeriodInDays,\n LatenessMaxDays,\n DrawdownPeriodInSeconds,\n TransferRestrictionPeriodInDays,\n LeverageRatio,\n /// A number in the range [0, 10000] representing basis points of FIDU taken as a fee\n /// when a withdrawal request is canceled.\n SeniorPoolWithdrawalCancelationFeeInBps\n }\n /// @dev TrustedForwarder is deprecated because we no longer use GSN. CreditDesk\n /// and Pool are deprecated because they are no longer used in the protocol.\n enum Addresses {\n Pool, // deprecated\n CreditLineImplementation,\n GoldfinchFactory,\n CreditDesk, // deprecated\n Fidu,\n USDC,\n TreasuryReserve,\n ProtocolAdmin,\n OneInch,\n TrustedForwarder, // deprecated\n CUSDCContract,\n GoldfinchConfig,\n PoolTokens,\n TranchedPoolImplementation, // deprecated\n SeniorPool,\n SeniorPoolStrategy,\n MigratedTranchedPoolImplementation,\n BorrowerImplementation,\n GFI,\n Go,\n BackerRewards,\n StakingRewards,\n FiduUSDCCurveLP,\n TranchedPoolImplementationRepository,\n WithdrawalRequestToken\n }\n}\n" }, "contracts/protocol/core/CreditLine.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./GoldfinchConfig.sol\";\nimport \"./ConfigHelper.sol\";\nimport \"./BaseUpgradeablePausable.sol\";\nimport \"./Accountant.sol\";\nimport \"../../interfaces/IERC20withDec.sol\";\nimport \"../../interfaces/ICreditLine.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol\";\n\n/**\n * @title CreditLine\n * @notice A contract that represents the agreement between Backers and\n * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.\n * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not\n * operate in any standalone capacity. It should generally be considered internal to the TranchedPool.\n * @author Goldfinch\n */\n\n// solhint-disable-next-line max-states-count\ncontract CreditLine is BaseUpgradeablePausable, ICreditLine {\n uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24;\n\n event GoldfinchConfigUpdated(address indexed who, address configAddress);\n\n // Credit line terms\n address public override borrower;\n uint256 public currentLimit;\n uint256 public override maxLimit;\n uint256 public override interestApr;\n uint256 public override paymentPeriodInDays;\n uint256 public override termInDays;\n uint256 public override principalGracePeriodInDays;\n uint256 public override lateFeeApr;\n\n // Accounting variables\n uint256 public override balance;\n uint256 public override interestOwed;\n uint256 public override principalOwed;\n uint256 public override termEndTime;\n uint256 public override nextDueTime;\n uint256 public override interestAccruedAsOf;\n uint256 public override lastFullPaymentTime;\n uint256 public totalInterestAccrued;\n\n GoldfinchConfig public config;\n using ConfigHelper for GoldfinchConfig;\n\n function initialize(\n address _config,\n address owner,\n address _borrower,\n uint256 _maxLimit,\n uint256 _interestApr,\n uint256 _paymentPeriodInDays,\n uint256 _termInDays,\n uint256 _lateFeeApr,\n uint256 _principalGracePeriodInDays\n ) public initializer {\n require(\n _config != address(0) && owner != address(0) && _borrower != address(0),\n \"Zero address passed in\"\n );\n __BaseUpgradeablePausable__init(owner);\n config = GoldfinchConfig(_config);\n borrower = _borrower;\n maxLimit = _maxLimit;\n interestApr = _interestApr;\n paymentPeriodInDays = _paymentPeriodInDays;\n termInDays = _termInDays;\n lateFeeApr = _lateFeeApr;\n principalGracePeriodInDays = _principalGracePeriodInDays;\n interestAccruedAsOf = block.timestamp;\n\n // Unlock owner, which is a TranchedPool, for infinite amount\n bool success = config.getUSDC().approve(owner, uint256(-1));\n require(success, \"Failed to approve USDC\");\n }\n\n function limit() external view override returns (uint256) {\n return currentLimit;\n }\n\n /**\n * @notice Updates the internal accounting to track a drawdown as of current block timestamp.\n * Does not move any money\n * @param amount The amount in USDC that has been drawndown\n */\n function drawdown(uint256 amount) external onlyAdmin {\n uint256 timestamp = currentTime();\n require(termEndTime == 0 || (timestamp < termEndTime), \"After termEndTime\");\n require(amount.add(balance) <= currentLimit, \"Cannot drawdown more than the limit\");\n require(amount > 0, \"Invalid drawdown amount\");\n\n if (balance == 0) {\n setInterestAccruedAsOf(timestamp);\n setLastFullPaymentTime(timestamp);\n setTotalInterestAccrued(0);\n // Set termEndTime only once to prevent extending\n // the loan's end time on every 0 balance drawdown\n if (termEndTime == 0) {\n setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays)));\n }\n }\n\n (uint256 _interestOwed, uint256 _principalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(\n timestamp\n );\n balance = balance.add(amount);\n\n updateCreditLineAccounting(balance, _interestOwed, _principalOwed);\n require(!_isLate(timestamp), \"Cannot drawdown when payments are past due\");\n }\n\n function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {\n lateFeeApr = newLateFeeApr;\n }\n\n function setLimit(uint256 newAmount) external onlyAdmin {\n require(newAmount <= maxLimit, \"Cannot be more than the max limit\");\n currentLimit = newAmount;\n }\n\n function setMaxLimit(uint256 newAmount) external onlyAdmin {\n maxLimit = newAmount;\n }\n\n function termStartTime() external view returns (uint256) {\n return _termStartTime();\n }\n\n function isLate() external view override returns (bool) {\n return _isLate(block.timestamp);\n }\n\n function withinPrincipalGracePeriod() external view override returns (bool) {\n if (termEndTime == 0) {\n // Loan hasn't started yet\n return true;\n }\n return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY));\n }\n\n function setTermEndTime(uint256 newTermEndTime) public onlyAdmin {\n termEndTime = newTermEndTime;\n }\n\n function setNextDueTime(uint256 newNextDueTime) public onlyAdmin {\n nextDueTime = newNextDueTime;\n }\n\n function setBalance(uint256 newBalance) public onlyAdmin {\n balance = newBalance;\n }\n\n function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin {\n totalInterestAccrued = _totalInterestAccrued;\n }\n\n function setInterestOwed(uint256 newInterestOwed) public onlyAdmin {\n interestOwed = newInterestOwed;\n }\n\n function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin {\n principalOwed = newPrincipalOwed;\n }\n\n function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin {\n interestAccruedAsOf = newInterestAccruedAsOf;\n }\n\n function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin {\n lastFullPaymentTime = newLastFullPaymentTime;\n }\n\n /**\n * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied\n * towards the interest and principal.\n * @return Any amount remaining after applying payments towards the interest and principal\n * @return Amount applied towards interest\n * @return Amount applied towards principal\n */\n function assess() public onlyAdmin returns (uint256, uint256, uint256) {\n // Do not assess until a full period has elapsed or past due\n require(balance > 0, \"Must have balance to assess credit line\");\n\n // Don't assess credit lines early!\n if (currentTime() < nextDueTime && !_isLate(currentTime())) {\n return (0, 0, 0);\n }\n uint256 timeToAssess = calculateNextDueTime();\n setNextDueTime(timeToAssess);\n\n // We always want to assess for the most recently *past* nextDueTime.\n // So if the recalculation above sets the nextDueTime into the future,\n // then ensure we pass in the one just before this.\n if (timeToAssess > currentTime()) {\n uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);\n timeToAssess = timeToAssess.sub(secondsPerPeriod);\n }\n return handlePayment(_getUSDCBalance(address(this)), timeToAssess);\n }\n\n function calculateNextDueTime() internal view returns (uint256) {\n uint256 newNextDueTime = nextDueTime;\n uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);\n uint256 curTimestamp = currentTime();\n // You must have just done your first drawdown\n if (newNextDueTime == 0 && balance > 0) {\n return curTimestamp.add(secondsPerPeriod);\n }\n\n // Active loan that has entered a new period, so return the *next* newNextDueTime.\n // But never return something after the termEndTime\n if (balance > 0 && curTimestamp >= newNextDueTime) {\n uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod))\n .add(1)\n .mul(secondsPerPeriod);\n newNextDueTime = newNextDueTime.add(secondsToAdvance);\n return Math.min(newNextDueTime, termEndTime);\n }\n\n // You're paid off, or have not taken out a loan yet, so no next due time.\n if (balance == 0 && newNextDueTime != 0) {\n return 0;\n }\n // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change.\n if (balance > 0 && curTimestamp < newNextDueTime) {\n return newNextDueTime;\n }\n revert(\"Error: could not calculate next due time.\");\n }\n\n function currentTime() internal view virtual returns (uint256) {\n return block.timestamp;\n }\n\n function _isLate(uint256 timestamp) internal view returns (bool) {\n uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime);\n return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY);\n }\n\n function _termStartTime() internal view returns (uint256) {\n return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays));\n }\n\n /**\n * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.\n * It also updates all the accounting variables. Note that interest is always paid back first, then principal.\n * Any extra after paying the minimum will go towards existing principal (reducing the\n * effective interest rate). Any extra after the full loan has been paid off will remain in the\n * USDC Balance of the creditLine, where it will be automatically used for the next drawdown.\n * @param paymentAmount The amount, in USDC atomic units, to be applied\n * @param timestamp The timestamp on which accrual calculations should be based. This allows us\n * to be precise when we assess a Credit Line\n */\n function handlePayment(\n uint256 paymentAmount,\n uint256 timestamp\n ) internal returns (uint256, uint256, uint256) {\n (uint256 newInterestOwed, uint256 newPrincipalOwed) = _updateAndGetInterestAndPrincipalOwedAsOf(\n timestamp\n );\n Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(\n paymentAmount,\n balance,\n newInterestOwed,\n newPrincipalOwed\n );\n\n uint256 newBalance = balance.sub(pa.principalPayment);\n // Apply any additional payment towards the balance\n newBalance = newBalance.sub(pa.additionalBalancePayment);\n uint256 totalPrincipalPayment = balance.sub(newBalance);\n uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);\n\n updateCreditLineAccounting(\n newBalance,\n newInterestOwed.sub(pa.interestPayment),\n newPrincipalOwed.sub(pa.principalPayment)\n );\n\n assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);\n\n return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);\n }\n\n function _updateAndGetInterestAndPrincipalOwedAsOf(\n uint256 timestamp\n ) internal returns (uint256, uint256) {\n (uint256 interestAccrued, uint256 principalAccrued) = Accountant\n .calculateInterestAndPrincipalAccrued(this, timestamp, config.getLatenessGracePeriodInDays());\n if (interestAccrued > 0) {\n // If we've accrued any interest, update interestAccruedAsOf to the time that we've\n // calculated interest for. If we've not accrued any interest, then we keep the old value so the next\n // time the entire period is taken into account.\n setInterestAccruedAsOf(timestamp);\n totalInterestAccrued = totalInterestAccrued.add(interestAccrued);\n }\n return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued));\n }\n\n function updateCreditLineAccounting(\n uint256 newBalance,\n uint256 newInterestOwed,\n uint256 newPrincipalOwed\n ) internal nonReentrant {\n setBalance(newBalance);\n setInterestOwed(newInterestOwed);\n setPrincipalOwed(newPrincipalOwed);\n\n // This resets lastFullPaymentTime. These conditions assure that they have\n // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown)\n uint256 _nextDueTime = nextDueTime;\n if (newInterestOwed == 0 && _nextDueTime != 0) {\n // If interest was fully paid off, then set the last full payment as the previous due time\n uint256 mostRecentLastDueTime;\n if (currentTime() < _nextDueTime) {\n uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY);\n mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod);\n } else {\n mostRecentLastDueTime = _nextDueTime;\n }\n setLastFullPaymentTime(mostRecentLastDueTime);\n }\n\n setNextDueTime(calculateNextDueTime());\n }\n\n function _getUSDCBalance(address _address) internal view returns (uint256) {\n return config.getUSDC().balanceOf(_address);\n }\n}\n" }, "contracts/protocol/core/GoldfinchConfig.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"./BaseUpgradeablePausable.sol\";\nimport \"../../interfaces/IGoldfinchConfig.sol\";\nimport \"./ConfigOptions.sol\";\n\n/**\n * @title GoldfinchConfig\n * @notice This contract stores mappings of useful \"protocol config state\", giving a central place\n * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars\n * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.\n * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this\n * is mostly to save gas costs of having each call go through a proxy)\n * @author Goldfinch\n */\n\ncontract GoldfinchConfig is BaseUpgradeablePausable {\n bytes32 public constant GO_LISTER_ROLE = keccak256(\"GO_LISTER_ROLE\");\n\n mapping(uint256 => address) public addresses;\n mapping(uint256 => uint256) public numbers;\n mapping(address => bool) public goList;\n\n event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);\n event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);\n\n event GoListed(address indexed member);\n event NoListed(address indexed member);\n\n bool public valuesInitialized;\n\n function initialize(address owner) public initializer {\n require(owner != address(0), \"Owner address cannot be empty\");\n\n __BaseUpgradeablePausable__init(owner);\n\n _setupRole(GO_LISTER_ROLE, owner);\n\n _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);\n }\n\n function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {\n require(addresses[addressIndex] == address(0), \"Address has already been initialized\");\n\n emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);\n addresses[addressIndex] = newAddress;\n }\n\n function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {\n emit NumberUpdated(msg.sender, index, numbers[index], newNumber);\n numbers[index] = newNumber;\n }\n\n function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);\n emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);\n addresses[key] = newTreasuryReserve;\n }\n\n function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);\n emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);\n addresses[key] = newStrategy;\n }\n\n function setCreditLineImplementation(address newAddress) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);\n emit AddressUpdated(msg.sender, key, addresses[key], newAddress);\n addresses[key] = newAddress;\n }\n\n function setTranchedPoolImplementation(address newAddress) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);\n emit AddressUpdated(msg.sender, key, addresses[key], newAddress);\n addresses[key] = newAddress;\n }\n\n function setBorrowerImplementation(address newAddress) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);\n emit AddressUpdated(msg.sender, key, addresses[key], newAddress);\n addresses[key] = newAddress;\n }\n\n function setGoldfinchConfig(address newAddress) public onlyAdmin {\n uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);\n emit AddressUpdated(msg.sender, key, addresses[key], newAddress);\n addresses[key] = newAddress;\n }\n\n function initializeFromOtherConfig(\n address _initialConfig,\n uint256 numbersLength,\n uint256 addressesLength\n ) public onlyAdmin {\n require(!valuesInitialized, \"Already initialized values\");\n IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);\n for (uint256 i = 0; i < numbersLength; i++) {\n setNumber(i, initialConfig.getNumber(i));\n }\n\n for (uint256 i = 0; i < addressesLength; i++) {\n if (getAddress(i) == address(0)) {\n setAddress(i, initialConfig.getAddress(i));\n }\n }\n valuesInitialized = true;\n }\n\n /**\n * @dev Adds a user to go-list\n * @param _member address to add to go-list\n */\n function addToGoList(address _member) public onlyGoListerRole {\n goList[_member] = true;\n emit GoListed(_member);\n }\n\n /**\n * @dev removes a user from go-list\n * @param _member address to remove from go-list\n */\n function removeFromGoList(address _member) public onlyGoListerRole {\n goList[_member] = false;\n emit NoListed(_member);\n }\n\n /**\n * @dev adds many users to go-list at once\n * @param _members addresses to ad to go-list\n */\n function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {\n for (uint256 i = 0; i < _members.length; i++) {\n addToGoList(_members[i]);\n }\n }\n\n /**\n * @dev removes many users from go-list at once\n * @param _members addresses to remove from go-list\n */\n function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {\n for (uint256 i = 0; i < _members.length; i++) {\n removeFromGoList(_members[i]);\n }\n }\n\n /*\n Using custom getters in case we want to change underlying implementation later,\n or add checks or validations later on.\n */\n function getAddress(uint256 index) public view returns (address) {\n return addresses[index];\n }\n\n function getNumber(uint256 index) public view returns (uint256) {\n return numbers[index];\n }\n\n modifier onlyGoListerRole() {\n require(\n hasRole(GO_LISTER_ROLE, _msgSender()),\n \"Must have go-lister role to perform this action\"\n );\n _;\n }\n}\n" }, "contracts/protocol/core/PauserPausable.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol\";\nimport \"@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol\";\n\n/**\n * @title PauserPausable\n * @notice Inheriting from OpenZeppelin's Pausable contract, this does small\n * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.\n * It is meant to be inherited.\n * @author Goldfinch\n */\n\ncontract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {\n bytes32 public constant PAUSER_ROLE = keccak256(\"PAUSER_ROLE\");\n\n // solhint-disable-next-line func-name-mixedcase\n function __PauserPausable__init() public initializer {\n __Pausable_init_unchained();\n }\n\n /**\n * @dev Pauses all functions guarded by Pause\n *\n * See {Pausable-_pause}.\n *\n * Requirements:\n *\n * - the caller must have the PAUSER_ROLE.\n */\n\n function pause() public onlyPauserRole {\n _pause();\n }\n\n /**\n * @dev Unpauses the contract\n *\n * See {Pausable-_unpause}.\n *\n * Requirements:\n *\n * - the caller must have the Pauser role\n */\n function unpause() public onlyPauserRole {\n _unpause();\n }\n\n modifier onlyPauserRole() {\n /// @dev NA: not authorized\n require(hasRole(PAUSER_ROLE, _msgSender()), \"NA\");\n _;\n }\n}\n" }, "contracts/protocol/core/proxy/ImplementationRepository.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.6.12;\npragma experimental ABIEncoderV2;\n\nimport {BaseUpgradeablePausable} from \"../BaseUpgradeablePausable.sol\";\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\n\n/// @title User Controlled Upgrades (UCU) Proxy Repository\n/// A repository maintaing a collection of \"lineages\" of implementation contracts\n///\n/// Lineages are a sequence of implementations each lineage can be thought of as\n/// a \"major\" revision of implementations. Implementations between lineages are\n/// considered incompatible.\ncontract ImplementationRepository is BaseUpgradeablePausable {\n address internal constant INVALID_IMPL = address(0);\n uint256 internal constant INVALID_LINEAGE_ID = 0;\n\n /// @notice returns data that will be delegatedCalled when the given implementation\n /// is upgraded to\n mapping(address => bytes) public upgradeDataFor;\n\n /// @dev mapping from one implementation to the succeeding implementation\n mapping(address => address) internal _nextImplementationOf;\n\n /// @notice Returns the id of the lineage a given implementation belongs to\n mapping(address => uint256) public lineageIdOf;\n\n /// @dev internal because we expose this through the `currentImplementation(uint256)` api\n mapping(uint256 => address) internal _currentOfLineage;\n\n /// @notice Returns the id of the most recently created lineage\n uint256 public currentLineageId;\n\n // //////// External ////////////////////////////////////////////////////////////\n\n /// @notice initialize the repository's state\n /// @dev reverts if `_owner` is the null address\n /// @dev reverts if `implementation` is not a contract\n /// @param _owner owner of the repository\n /// @param implementation initial implementation in the repository\n function initialize(address _owner, address implementation) external initializer {\n __BaseUpgradeablePausable__init(_owner);\n _createLineage(implementation);\n require(currentLineageId != INVALID_LINEAGE_ID);\n }\n\n /// @notice set data that will be delegate called when a proxy upgrades to the given `implementation`\n /// @dev reverts when caller is not an admin\n /// @dev reverts when the contract is paused\n /// @dev reverts if the given implementation isn't registered\n function setUpgradeDataFor(\n address implementation,\n bytes calldata data\n ) external onlyAdmin whenNotPaused {\n _setUpgradeDataFor(implementation, data);\n }\n\n /// @notice Create a new lineage of implementations.\n ///\n /// This creates a new \"root\" of a new lineage\n /// @dev reverts if `implementation` is not a contract\n /// @param implementation implementation that will be the first implementation in the lineage\n /// @return newly created lineage's id\n function createLineage(\n address implementation\n ) external onlyAdmin whenNotPaused returns (uint256) {\n return _createLineage(implementation);\n }\n\n /// @notice add a new implementation and set it as the current implementation\n /// @dev reverts if the sender is not an owner\n /// @dev reverts if the contract is paused\n /// @dev reverts if `implementation` is not a contract\n /// @param implementation implementation to append\n function append(address implementation) external onlyAdmin whenNotPaused {\n _append(implementation, currentLineageId);\n }\n\n /// @notice Append an implementation to a specified lineage\n /// @dev reverts if the contract is paused\n /// @dev reverts if the sender is not an owner\n /// @dev reverts if `implementation` is not a contract\n /// @param implementation implementation to append\n /// @param lineageId id of lineage to append to\n function append(address implementation, uint256 lineageId) external onlyAdmin whenNotPaused {\n _append(implementation, lineageId);\n }\n\n /// @notice Remove an implementation from the chain and \"stitch\" together its neighbors\n /// @dev If you have a chain of `A -> B -> C` and I call `remove(B, C)` it will result in `A -> C`\n /// @dev reverts if `previos` is not the ancestor of `toRemove`\n /// @dev we need to provide the previous implementation here to be able to successfully \"stitch\"\n /// the chain back together. Because this is an admin action, we can source what the previous\n /// version is from events.\n /// @param toRemove Implementation to remove\n /// @param previous Implementation that currently has `toRemove` as its successor\n function remove(address toRemove, address previous) external onlyAdmin whenNotPaused {\n _remove(toRemove, previous);\n }\n\n // //////// External view ////////////////////////////////////////////////////////////\n\n /// @notice Returns `true` if an implementation has a next implementation set\n /// @param implementation implementation to check\n /// @return The implementation following the given implementation\n function hasNext(address implementation) external view returns (bool) {\n return _nextImplementationOf[implementation] != INVALID_IMPL;\n }\n\n /// @notice Returns `true` if an implementation has already been added\n /// @param implementation Implementation to check existence of\n /// @return `true` if the implementation has already been added\n function has(address implementation) external view returns (bool) {\n return _has(implementation);\n }\n\n /// @notice Get the next implementation for a given implementation or\n /// `address(0)` if it doesn't exist\n /// @dev reverts when contract is paused\n /// @param implementation implementation to get the upgraded implementation for\n /// @return Next Implementation\n function nextImplementationOf(\n address implementation\n ) external view whenNotPaused returns (address) {\n return _nextImplementationOf[implementation];\n }\n\n /// @notice Returns `true` if a given lineageId exists\n function lineageExists(uint256 lineageId) external view returns (bool) {\n return _lineageExists(lineageId);\n }\n\n /// @notice Return the current implementation of a lineage with the given `lineageId`\n function currentImplementation(uint256 lineageId) external view whenNotPaused returns (address) {\n return _currentImplementation(lineageId);\n }\n\n /// @notice return current implementaton of the current lineage\n function currentImplementation() external view whenNotPaused returns (address) {\n return _currentImplementation(currentLineageId);\n }\n\n // //////// Internal ////////////////////////////////////////////////////////////\n\n function _setUpgradeDataFor(address implementation, bytes memory data) internal {\n require(_has(implementation), \"unknown impl\");\n upgradeDataFor[implementation] = data;\n emit UpgradeDataSet(implementation, data);\n }\n\n function _createLineage(address implementation) internal virtual returns (uint256) {\n require(Address.isContract(implementation), \"not a contract\");\n // NOTE: impractical to overflow\n currentLineageId += 1;\n\n _currentOfLineage[currentLineageId] = implementation;\n lineageIdOf[implementation] = currentLineageId;\n\n emit Added(currentLineageId, implementation, address(0));\n return currentLineageId;\n }\n\n function _currentImplementation(uint256 lineageId) internal view returns (address) {\n return _currentOfLineage[lineageId];\n }\n\n /// @notice Returns `true` if an implementation has already been added\n /// @param implementation implementation to check for\n /// @return `true` if the implementation has already been added\n function _has(address implementation) internal view virtual returns (bool) {\n return lineageIdOf[implementation] != INVALID_LINEAGE_ID;\n }\n\n /// @notice Set an implementation to the current implementation\n /// @param implementation implementation to set as current implementation\n /// @param lineageId id of lineage to append to\n function _append(address implementation, uint256 lineageId) internal virtual {\n require(Address.isContract(implementation), \"not a contract\");\n require(!_has(implementation), \"exists\");\n require(_lineageExists(lineageId), \"invalid lineageId\");\n require(_currentOfLineage[lineageId] != INVALID_IMPL, \"empty lineage\");\n\n address oldImplementation = _currentOfLineage[lineageId];\n _currentOfLineage[lineageId] = implementation;\n lineageIdOf[implementation] = lineageId;\n _nextImplementationOf[oldImplementation] = implementation;\n\n emit Added(lineageId, implementation, oldImplementation);\n }\n\n function _remove(address toRemove, address previous) internal virtual {\n require(toRemove != INVALID_IMPL && previous != INVALID_IMPL, \"ZERO\");\n require(_nextImplementationOf[previous] == toRemove, \"Not prev\");\n\n uint256 lineageId = lineageIdOf[toRemove];\n\n // need to reset the head pointer to the previous version if we remove the head\n if (toRemove == _currentOfLineage[lineageId]) {\n _currentOfLineage[lineageId] = previous;\n }\n\n _setUpgradeDataFor(toRemove, \"\"); // reset upgrade data\n _nextImplementationOf[previous] = _nextImplementationOf[toRemove];\n _nextImplementationOf[toRemove] = INVALID_IMPL;\n lineageIdOf[toRemove] = INVALID_LINEAGE_ID;\n emit Removed(lineageId, toRemove);\n }\n\n function _lineageExists(uint256 lineageId) internal view returns (bool) {\n return lineageId != INVALID_LINEAGE_ID && lineageId <= currentLineageId;\n }\n\n // //////// Events //////////////////////////////////////////////////////////////\n event Added(\n uint256 indexed lineageId,\n address indexed newImplementation,\n address indexed oldImplementation\n );\n event Removed(uint256 indexed lineageId, address indexed implementation);\n event UpgradeDataSet(address indexed implementation, bytes data);\n}\n" } } }