file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2021-06-28 */ // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: openzeppelin-solidity/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: openzeppelin-solidity/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: openzeppelin-solidity/contracts/access/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/VestingMultiVault.sol pragma solidity ^0.8.0; /** * @title VestingMultiVault * @dev A token vesting contract that will release tokens gradually like a * standard equity vesting schedule, with a cliff and vesting period but no * arbitrary restrictions on the frequency of claims. Optionally has an initial * tranche claimable immediately after the cliff expires (in addition to any * amounts that would have vested up to that point but didn't due to a cliff). */ contract VestingMultiVault is AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; event Issued( address indexed beneficiary, uint256 indexed allocationId, uint256 amount, uint256 start, uint256 cliff, uint256 duration ); event Released( address indexed beneficiary, uint256 indexed allocationId, uint256 amount, uint256 remaining ); event Revoked( address indexed beneficiary, uint256 indexed allocationId, uint256 allocationAmount, uint256 revokedAmount ); struct Allocation { uint256 start; uint256 cliff; uint256 duration; uint256 total; uint256 claimed; uint256 initial; } // The token being vested. IERC20 public immutable token; // The amount unclaimed for an address, whether or not vested. mapping(address => uint256) public pendingAmount; // The allocations assigned to an address. mapping(address => Allocation[]) public userAllocations; // The precomputed hash of the "ISSUER" role. bytes32 public constant ISSUER = keccak256("ISSUER"); /** * @dev Creates a vesting contract that releases allocations of a token * over an arbitrary time period with support for tranches and cliffs. * @param _token The ERC-20 token to be vested */ constructor(IERC20 _token) { token = _token; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(ISSUER, msg.sender); } /** * @dev Creates a new allocation for a beneficiary. Tokens are released * linearly over time until a given number of seconds have passed since the * start of the vesting schedule. Callable only by issuers. * @param _beneficiary The address to which tokens will be released * @param _amount The amount of the allocation (in wei) * @param _startAt The unix timestamp at which the vesting may begin * @param _cliff The number of seconds after _startAt before which no vesting occurs * @param _duration The number of seconds after which the entire allocation is vested * @param _initialPct The percentage of the allocation initially available (integer, 0-100) */ function issue( address _beneficiary, uint256 _amount, uint256 _startAt, uint256 _cliff, uint256 _duration, uint256 _initialPct ) public onlyRole(ISSUER) { require(token.allowance(msg.sender, address(this)) >= _amount, "Token allowance not sufficient"); require(_beneficiary != address(0), "Cannot grant tokens to the zero address"); require(_cliff <= _duration, "Cliff must not exceed duration"); require(_initialPct <= 100, "Initial release percentage must be an integer 0 to 100 (inclusive)"); // Pull the number of tokens required for the allocation. token.safeTransferFrom(msg.sender, address(this), _amount); // Increase the total pending for the address. pendingAmount[_beneficiary] = pendingAmount[_beneficiary].add(_amount); // Push the new allocation into the stack. userAllocations[_beneficiary].push(Allocation({ claimed: 0, cliff: _cliff, duration: _duration, initial: _amount.mul(_initialPct).div(100), start: _startAt, total: _amount })); emit Issued( _beneficiary, userAllocations[_beneficiary].length - 1, _amount, _startAt, _cliff, _duration ); } /** * @dev Revokes an existing allocation. Any unclaimed tokens are recalled * and sent to the caller. Callable only be issuers. * @param _beneficiary The address whose allocation is to be revoked * @param _id The allocation ID to revoke */ function revoke( address _beneficiary, uint256 _id ) public onlyRole(ISSUER) { Allocation storage allocation = userAllocations[_beneficiary][_id]; // Calculate the remaining amount. uint256 total = allocation.total; uint256 remainder = total.sub(allocation.claimed); // Update the total pending for the address. pendingAmount[_beneficiary] = pendingAmount[_beneficiary].sub(remainder); // Update the allocation to be claimed in full. allocation.claimed = total; // Transfer the tokens vested token.safeTransfer(msg.sender, remainder); emit Revoked( _beneficiary, _id, total, remainder ); } /** * @dev Transfers vested tokens from an allocation to its beneficiary. Callable by anyone. * @param _beneficiary The address that has vested tokens * @param _id The vested allocation index */ function release( address _beneficiary, uint256 _id ) public { Allocation storage allocation = userAllocations[_beneficiary][_id]; // Calculate the releasable amount. uint256 amount = _releasableAmount(allocation); require(amount > 0, "Nothing to release"); // Add the amount to the allocation's total claimed. allocation.claimed = allocation.claimed.add(amount); // Subtract the amount from the beneficiary's total pending. pendingAmount[_beneficiary] = pendingAmount[_beneficiary].sub(amount); // Transfer the tokens to the beneficiary. token.safeTransfer(_beneficiary, amount); emit Released( _beneficiary, _id, amount, allocation.total.sub(allocation.claimed) ); } /** * @dev Transfers vested tokens from any number of allocations to their beneficiary. Callable by anyone. May be gas-intensive. * @param _beneficiary The address that has vested tokens * @param _ids The vested allocation indexes */ function releaseMultiple( address _beneficiary, uint256[] calldata _ids ) external { for (uint256 i = 0; i < _ids.length; i++) { release(_beneficiary, _ids[i]); } } /** * @dev Gets the number of allocations issued for a given address. * @param _beneficiary The address to check for allocations */ function allocationCount( address _beneficiary ) public view returns (uint256 count) { return userAllocations[_beneficiary].length; } /** * @dev Calculates the amount that has already vested but has not yet been released for a given address. * @param _beneficiary Address to check * @param _id The allocation index */ function releasableAmount( address _beneficiary, uint256 _id ) public view returns (uint256 amount) { Allocation storage allocation = userAllocations[_beneficiary][_id]; return _releasableAmount(allocation); } /** * @dev Gets the total releasable for a given address. Likely gas-intensive, not intended for contract use. * @param _beneficiary Address to check */ function totalReleasableAount( address _beneficiary ) public view returns (uint256 amount) { for (uint256 i = 0; i < allocationCount(_beneficiary); i++) { amount = amount.add(releasableAmount(_beneficiary, i)); } return amount; } /** * @dev Calculates the amount that has vested to date. * @param _beneficiary Address to check * @param _id The allocation index */ function vestedAmount( address _beneficiary, uint256 _id ) public view returns (uint256) { Allocation storage allocation = userAllocations[_beneficiary][_id]; return _vestedAmount(allocation); } /** * @dev Gets the total ever vested for a given address. Likely gas-intensive, not intended for contract use. * @param _beneficiary Address to check */ function totalVestedAount( address _beneficiary ) public view returns (uint256 amount) { for (uint256 i = 0; i < allocationCount(_beneficiary); i++) { amount = amount.add(vestedAmount(_beneficiary, i)); } return amount; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param allocation Allocation to calculate against */ function _releasableAmount( Allocation storage allocation ) internal view returns (uint256) { return _vestedAmount(allocation).sub(allocation.claimed); } /** * @dev Calculates the amount that has already vested. * @param allocation Allocation to calculate against */ function _vestedAmount( Allocation storage allocation ) internal view returns (uint256 amount) { if (block.timestamp < allocation.start.add(allocation.cliff)) { // Nothing is vested until after the start time + cliff length. amount = 0; } else if (block.timestamp >= allocation.start.add(allocation.duration)) { // The entire amount has vested if the entire duration has elapsed. amount = allocation.total; } else { // The initial tranche is available once the cliff expires, plus any portion of // tokens which have otherwise become vested as of the current block's timestamp. amount = allocation.initial.add( allocation.total .sub(allocation.initial) .sub(amount) .mul(block.timestamp.sub(allocation.start)) .div(allocation.duration) ); } return amount; } } // File: contracts/StakeRewarder.sol pragma solidity ^0.8.5; /** * @title StakeRewarder * @dev This contract distributes rewards to depositors of supported tokens. * It's based on Sushi's MasterChef v1, but notably only serves what's already * available: no new tokens can be created. It's just a restaurant, not a farm. */ contract StakeRewarder is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // Quantity of tokens the user has staked. uint256 rewardDebt; // Reward debt. See explanation below. // We do some fancy math here. Basically, any point in time, the // amount of rewards entitled to a user but is pending to be distributed is: // // pendingReward = (stakedAmount * pool.accPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens in a pool: // 1. The pool's `accPerShare` (and `lastRewardBlock`) gets updated. // 2. User's pending rewards are issued (greatly simplifies accounting). // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct PoolInfo { IERC20 token; // Address of the token contract. uint256 weight; // Weight points assigned to this pool. uint256 power; // The multiplier for determining "staking power". uint256 total; // Total number of tokens staked. uint256 accPerShare; // Accumulated rewards per share (times 1e12). uint256 lastRewardBlock; // Last block where rewards were calculated. } // Distribution vault. VestingMultiVault public immutable vault; // Reward configuration. IERC20 public immutable rewardToken; uint256 public rewardPerBlock; uint256 public vestingCliff; uint256 public vestingDuration; // Housekeeping for each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Underpaid rewards owed to a user. mapping(address => uint256) public underpayment; // The sum of weights across all staking tokens. uint256 public totalWeight = 0; // The block number when staking starts. uint256 public startBlock; event TokenAdded(address indexed token, uint256 weight, uint256 totalWeight); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Claim(address indexed user, uint256 amount); event EmergencyReclaim(address indexed user, address token, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /** * @dev Create a staking contract that rewards depositors using its own token balance * and optionally vests rewards over time. * @param _rewardToken The token to be distributed as rewards. * @param _rewardPerBlock The quantity of reward tokens accrued per block. * @param _startBlock The first block at which staking is allowed. * @param _vestingCliff The number of seconds until issued rewards begin vesting. * @param _vestingDuration The number of seconds after issuance until vesting is completed. * @param _vault The VestingMultiVault that is ultimately responsible for reward distribution. */ constructor( IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _vestingCliff, uint256 _vestingDuration, VestingMultiVault _vault ) { // Set the initial reward config rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; vestingCliff = _vestingCliff; vestingDuration = _vestingDuration; // Set the vault and reward token (immutable after creation) vault = _vault; rewardToken = _rewardToken; // Approve the vault to pull reward tokens _rewardToken.approve(address(_vault), 2**256 - 1); } /** * @dev Adds a new staking pool to the stack. Can only be called by the owner. * @param _token The token to be staked. * @param _weight The weight of this pool (used to determine proportion of rewards relative to the total weight). * @param _power The power factor of this pool (used as a multiple of tokens staked, e.g. for determining voting power). * @param _shouldUpdate Whether to update all pools first. */ function createPool( IERC20 _token, uint256 _weight, uint256 _power, bool _shouldUpdate ) public onlyOwner { if (_shouldUpdate) { pokePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalWeight = totalWeight.add(_weight); poolInfo.push( PoolInfo({ token: _token, weight: _weight, power: _power, total: 0, accPerShare: 0, lastRewardBlock: lastRewardBlock }) ); } /** * @dev Update the given staking pool's weight and power. Can only be called by the owner. * @param _pid The pool identifier. * @param _weight The weight of this pool (used to determine proportion of rewards relative to the total weight). * @param _power The power of this pool's token (used as a multiplier of tokens staked, e.g. for voting). * @param _shouldUpdate Whether to update all pools first. */ function updatePool( uint256 _pid, uint256 _weight, uint256 _power, bool _shouldUpdate ) public onlyOwner { if (_shouldUpdate) { pokePools(); } totalWeight = totalWeight.sub(poolInfo[_pid].weight).add( _weight ); poolInfo[_pid].weight = _weight; poolInfo[_pid].power = _power; } /** * @dev Update the reward per block. Can only be called by the owner. * @param _rewardPerBlock The total quantity to distribute per block. */ function setRewardPerBlock( uint256 _rewardPerBlock ) public onlyOwner { rewardPerBlock = _rewardPerBlock; } /** * @dev Update the vesting rules for rewards. Can only be called by the owner. * @param _duration the number of seconds over which vesting occurs (see VestingMultiVault) * @param _cliff the number of seconds before any release occurs (see VestingMultiVault) */ function setVestingRules( uint256 _duration, uint256 _cliff ) public onlyOwner { vestingDuration = _duration; vestingCliff = _cliff; } /** * @dev Calculate elapsed blocks between `_from` and `_to`. * @param _from The starting block. * @param _to The ending block. */ function duration( uint256 _from, uint256 _to ) public pure returns (uint256) { return _to.sub(_from); } function totalPendingRewards( address _beneficiary ) public view returns (uint256 total) { for (uint256 pid = 0; pid < poolInfo.length; pid++) { total = total.add(pendingRewards(pid, _beneficiary)); } return total; } /** * @dev View function to see pending rewards for an address. Likely gas intensive. * @param _pid The pool identifier. * @param _beneficiary The address to check. */ function pendingRewards( uint256 _pid, address _beneficiary ) public view returns (uint256 amount) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_beneficiary]; uint256 accPerShare = pool.accPerShare; uint256 tokenSupply = pool.total; if (block.number > pool.lastRewardBlock && tokenSupply != 0) { uint256 reward = duration(pool.lastRewardBlock, block.number) .mul(rewardPerBlock) .mul(pool.weight) .div(totalWeight); accPerShare = accPerShare.add( reward.mul(1e12).div(tokenSupply) ); } return user.amount.mul(accPerShare).div(1e12).sub(user.rewardDebt); } /** * @dev Gets the sum of power for every pool. Likely gas intensive. * @param _beneficiary The address to check. */ function totalPower( address _beneficiary ) public view returns (uint256 total) { for (uint256 pid = 0; pid < poolInfo.length; pid++) { total = total.add(power(pid, _beneficiary)); } return total; } /** * @dev Gets power for a single pool. * @param _pid The pool identifier. * @param _beneficiary The address to check. */ function power( uint256 _pid, address _beneficiary ) public view returns (uint256 amount) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_beneficiary]; return pool.power.mul(user.amount); } /** * @dev Update all pools. Callable by anyone. Could be gas intensive. */ function pokePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { pokePool(pid); } } /** * @dev Update rewards of the given pool to be up-to-date. Callable by anyone. * @param _pid The pool identifier. */ function pokePool( uint256 _pid ) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 tokenSupply = pool.total; if (tokenSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 reward = duration(pool.lastRewardBlock, block.number) .mul(rewardPerBlock) .mul(pool.weight) .div(totalWeight); pool.accPerShare = pool.accPerShare.add( reward.mul(1e12).div(tokenSupply) ); pool.lastRewardBlock = block.number; } /** * @dev Claim rewards not yet distributed for an address. Callable by anyone. * @param _pid The pool identifier. * @param _beneficiary The address to claim for. */ function claim( uint256 _pid, address _beneficiary ) public { // make sure the pool is up-to-date pokePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_beneficiary]; _claim(pool, user, _beneficiary); } /** * @dev Claim rewards from multiple pools. Callable by anyone. * @param _pids An array of pool identifiers. * @param _beneficiary The address to claim for. */ function claimMultiple( uint256[] calldata _pids, address _beneficiary ) external { for (uint256 i = 0; i < _pids.length; i++) { claim(_pids[i], _beneficiary); } } /** * @dev Stake tokens to earn a share of rewards. * @param _pid The pool identifier. * @param _amount The number of tokens to deposit. */ function deposit( uint256 _pid, uint256 _amount ) public { require(_amount > 0, "deposit: only non-zero amounts allowed"); // make sure the pool is up-to-date pokePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; // deliver any pending rewards _claim(pool, user, msg.sender); // pull in user's staked assets pool.token.safeTransferFrom( address(msg.sender), address(this), _amount ); // update the pool's total deposit pool.total = pool.total.add(_amount); // update user's deposit and reward info user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } /** * @dev Withdraw staked tokens and any pending rewards. */ function withdraw( uint256 _pid, uint256 _amount ) public { require(_amount > 0, "withdraw: only non-zero amounts allowed"); // make sure the pool is up-to-date pokePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: amount too large"); // deliver any pending rewards _claim(pool, user, msg.sender); // update the pool's total deposit pool.total = pool.total.sub(_amount); // update the user's deposit and reward info user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12); // send back the staked assets pool.token.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } /** * @dev Withdraw staked tokens and forego any unclaimed rewards. This is a fail-safe. */ function emergencyWithdraw( uint256 _pid ) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; // reset everything to zero user.amount = 0; user.rewardDebt = 0; underpayment[msg.sender] = 0; // update the pool's total deposit pool.total = pool.total.sub(amount); // send back the staked assets pool.token.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } /** * @dev Reclaim stuck tokens (e.g. unexpected external rewards). This is a fail-safe. */ function emergencyReclaim( IERC20 _token, uint256 _amount ) public onlyOwner { if (_amount == 0) { _amount = _token.balanceOf(address(this)); } _token.transfer(msg.sender, _amount); emit EmergencyReclaim(msg.sender, address(_token), _amount); } /** * @dev Gets the length of the pools array. */ function poolLength() external view returns (uint256 length) { return poolInfo.length; } /** * @dev Claim rewards not yet distributed for an address. * @param pool The staking pool issuing rewards. * @param user The staker who earned them. * @param to The address to pay. */ function _claim( PoolInfo storage pool, UserInfo storage user, address to ) internal { if (user.amount > 0) { // calculate the pending reward uint256 pending = user.amount .mul(pool.accPerShare) .div(1e12) .sub(user.rewardDebt) .add(underpayment[to]); // send the rewards out uint256 payout = _safelyDistribute(to, pending); if (payout < pending) { underpayment[to] = pending.sub(payout); } else { underpayment[to] = 0; } emit Claim(to, payout); } } /** * @dev Safely distribute at most the amount of tokens in holding. */ function _safelyDistribute( address _to, uint256 _amount ) internal returns (uint256 amount) { uint256 available = rewardToken.balanceOf(address(this)); amount = _amount > available ? available : _amount; vault.issue( _to, // address _beneficiary, _amount, // uint256 _amount, block.timestamp, // uint256 _startAt, vestingCliff, // uint256 _cliff, vestingDuration, // uint256 _duration, 0 // uint256 _initialPct ); return amount; } }
Withdraw staked tokens and any pending rewards./ make sure the pool is up-to-date deliver any pending rewards update the pool's total deposit update the user's deposit and reward info send back the staked assets
function withdraw( uint256 _pid, uint256 _amount ) public { require(_amount > 0, "withdraw: only non-zero amounts allowed"); pokePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: amount too large"); _claim(pool, user, msg.sender); pool.total = pool.total.sub(_amount); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPerShare).div(1e12); pool.token.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
5,404,157
pragma solidity >= 0.5.0 < 0.7.0; // pragma experimental ABIEncoderV2; // To support struct as return value // WifiAllocation.sol: Performs bandwidth allocation according to the proportional rule // Based on the previous version, and added support for requesting both (1) bandwidth and (2) burst data volume contract WifiAllocation { // Only owner can perform the allocation address payable public owner; uint public totalBandwidth; uint public totalDesiredBandwidth; uint public totalDesiredNonDynamic; uint public totalDesiredDynamic; uint public totalDesiredBurst; // The owner can set a minimum unit price of the bandwidth. // Unit: wei // The price has to be an integer, so it is scaled for higher precision; same for bandwidth uint constant bandwidthPriceScalingFactor = 100; uint constant bandwidthScalingFactor = 100; uint constant burstPriceScalingFactor = 100; uint public minBandwidthPrice; uint public bandwidthPrice; uint public oldPrice; uint public minBurstPriceFactor; // If user does not specify desired burst, a default value is returned (e.g., 1MB) uint public burstPrice; // uint public weight; // Changed to local variables to reduce gas cost // uint public weightedPrice; // The bids to be collected by the contract owner uint public pendingCollection; uint public totalCollected; uint public latestTransaction; // Keep record of all users uint public numUsers; uint[] public allocatedBandwidth; uint[] public currentBalances; bool[] public isActive; // Whether the user accepts dynamic bandwidth allocation // i.e., the allocated bandwidth may fluctuate, while the bid remains the same bool[] public isDynamic; // The corresponding prices that users are charged according to uint[] public actualPrices; uint[] public burstVol; struct User { address userAddress; uint desiredBandwidth; uint receivedBandwidth; uint lastPaymentTime; uint thresholdBid; uint burst; } mapping(uint => User) users; mapping(address => uint) occupiedID; mapping(address => uint) pendingWithdrawl; event UponAllocation( uint _numUsers, uint[] _allocatedBandwidth, uint[] _currentBalances, uint[] _actualPrices, bool[] _isActive, uint[] _burstVol ); modifier onlyOwner { require( msg.sender == owner, "Only the owner can call this function" ); _; } modifier onlyNotOwner { require( msg.sender != owner, "The owner cannot call this function" ); _; } modifier requirePayment { require( msg.value > 0, "You must pay some value !" ); _; } constructor(uint _totalBandwidth, uint _minBandwidthPrice, uint _minBurstPriceFactor) public { // Initialises with the total bandwidth specified owner = msg.sender; totalBandwidth = _totalBandwidth; minBandwidthPrice = _minBandwidthPrice; minBurstPriceFactor = _minBurstPriceFactor; bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor; // By default totalDesiredBurst is set to 1 burstPrice = minBurstPriceFactor * 1 * 1; } // Called by a user when joining or exitting the wifi connection function uponConnection(uint bandwidth, uint thresholdBid, uint burst) public payable onlyNotOwner { latestTransaction = now; if(bandwidth > 0) { // The user wants to join the connection // Check if user already exists if(occupiedID[msg.sender] > 0) { uint userID = occupiedID[msg.sender]; // Array index starts from 0, userID starts from 1 if(isActive[userID - 1]) { /// @notice Case1: The user is still actively connected: renewal of connection connectionRenewal(userID, bandwidth, thresholdBid, burst); } else { /// @notice Case2: The user has been disconnected: reentry of connection connectionReentry(userID, bandwidth, thresholdBid, burst); } } else { /// @notice Case3: The user has never connected before: initialisation of connection occupiedID[msg.sender] = connectionInitialisation(bandwidth, thresholdBid, burst); } } else { /// @notice Case4: The user wants to quit the connection (by indicating a bandwidth of 0) require(occupiedID[msg.sender] > 0, "You are not an existing user!"); connectionTermination(occupiedID[msg.sender]); withdrawBalance(); } } // Called by an ACTIVE user when he only selects to top up balance function addBalance() public payable onlyNotOwner { require(occupiedID[msg.sender] > 0, "You are not an existing user!"); currentBalances[occupiedID[msg.sender] - 1] += msg.value; } // // Called by the owner to check results for testing purposes // function getAllocationResults() public onlyOwner { // // returns (uint[] memory, uint[] memory, uint, bool[] memory, bool[] memory, uint[] memory) { // // updateBalance(); // emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive); // // return (currentBalances, actualPrices, totalCollected, isActive, isDynamic, allocatedBandwidth); // } // // Called by users to check the real-time supply and price // function getPriceAndSupply() public view returns (uint, uint, uint, uint) { // // Param1: current unit price of bandwidth (scaled by bandwidthPriceScalingFactor) // // Param2: total demand (totalDesiredBandwidth) // // Param3: total demand of dynamic users (totalDesiredDynamic) // // Param4: total demand of non-dynamic users (totalDesiredNonDynamic) // return (bandwidthPrice, totalDesiredBandwidth, totalDesiredDynamic, totalDesiredNonDynamic); // } // Get user profile // function getUserProfile(uint userID) public view returns (User memory) { // return users[userID]; // } // Get userID function getUserID(address _user) public view returns (uint) { return occupiedID[_user]; } function getUserAllocation(uint _userID) public view returns (uint) { return allocatedBandwidth[_userID]/bandwidthScalingFactor; } function getUserBalance(uint _userID) public view returns (uint) { return currentBalances[_userID]; } // Perform bandwidth allocation depending on the demand and supply function performAllocation() public { if(totalDesiredBandwidth <= totalBandwidth) { demandNotExceedSupply(); } else { demandExceedSupply(); } } // Deduct balance according to usage // If the balance is not enough, the user is deactived from connection function updateBalance() public { for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { uint currentTime = now; uint currentFee = bandwidthPrice * users[i + 1].receivedBandwidth * (currentTime - users[i + 1].lastPaymentTime) / (bandwidthPriceScalingFactor * bandwidthScalingFactor); // Since there is no capacity limit on burst volume, users are only charged at a constant price specified by owner // The cost of burst is VOLUME * UNIT PRICE * TIME DURATION currentFee += burstPrice * users[i + 1].burst * (currentTime - users[i + 1].lastPaymentTime) / burstPriceScalingFactor; users[i + 1].lastPaymentTime = currentTime; if(currentBalances[i] >= currentFee) { currentBalances[i] -= currentFee; pendingCollection += currentFee; } else { // Deactivate the user from connection currentFee = currentBalances[i]; currentBalances[i] = 0; pendingCollection += currentFee; users[i + 1].receivedBandwidth = 0; totalDesiredBandwidth -= users[i + 1].desiredBandwidth; if(isDynamic[i]) { totalDesiredDynamic -= users[i + 1].desiredBandwidth; } else { totalDesiredNonDynamic -= users[i + 1].desiredBandwidth; } users[i + 1].desiredBandwidth = 0; allocatedBandwidth[i] = 0; actualPrices[i] = 0; isActive[i] = false; isDynamic[i] = false; users[i + 1].burst = 0; burstVol[i] = 0; // Calculate the allocation again since the demand has changed // performAllocation(); } } } collectBids(); emit UponAllocation(numUsers, allocatedBandwidth, currentBalances, actualPrices, isActive, burstVol); } // Top-up back to user according to the bandwidth wasted // e.g. userID 1, bandwidth 1MB, duration 2 second: (1, 100, 200, false) function topBack(uint userID, uint bandwidth, uint duration, bool useOldPrice) public onlyOwner { uint timingFactor = 100; if(isActive[userID]) { uint price = useOldPrice ? oldPrice : bandwidthPrice; uint topBackFee = price * bandwidth * duration / (bandwidthPriceScalingFactor * bandwidthScalingFactor * timingFactor); currentBalances[userID] += topBackFee; if (pendingCollection >= topBackFee) { pendingCollection -= topBackFee; } else { pendingCollection = 0; } } } // When the user has never connected before function connectionInitialisation(uint bandwidth, uint thresholdBid, uint burst) internal requirePayment returns (uint userID) { // Create profile for the new user userID = ++numUsers; // {userAddress, desiredBandwidth, receivedBandwidth, lastPaymentTime, thresholdBid, burst} users[userID] = User(msg.sender, bandwidth, 0, now, thresholdBid, burst); isActive.push(true); totalDesiredBandwidth += bandwidth; // In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) { isDynamic.push(true); totalDesiredDynamic += bandwidth; } else { isDynamic.push(false); totalDesiredNonDynamic += bandwidth; } totalDesiredBurst += burst; allocatedBandwidth.push(0); currentBalances.push(msg.value); actualPrices.push(bandwidthPrice); burstVol.push(burst); updatePrice(bandwidth * bandwidthScalingFactor, true); performAllocation(); updateBalance(); } // When the user is still connected // The user can either top up his balance or modify his desired bandwidth function connectionRenewal(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal { totalDesiredBandwidth = totalDesiredBandwidth + bandwidth - users[userID].desiredBandwidth; // Since the user is still active, there is no need to update isDynamic (later in performAllocation()) if(isDynamic[userID - 1]) { totalDesiredDynamic = totalDesiredDynamic + bandwidth - users[userID].desiredBandwidth; } else { totalDesiredNonDynamic = totalDesiredNonDynamic + bandwidth - users[userID].desiredBandwidth; } totalDesiredBurst = totalDesiredBurst + burst - users[userID].burst; // Update user profile currentBalances[userID - 1] += msg.value; users[userID].desiredBandwidth = bandwidth; users[userID].thresholdBid = thresholdBid; users[userID].burst = burst; burstVol[userID - 1] = burst; // No need to update lastPaymentTime here // Check whether the demand is increasing or decreasing, depending on the *actually received bandwidth(WHICH IS SCALED)* // e.g., User i desires 40 units bandwidth at price 1.2, but receives 32 units at price 1.5 // Now he only wants 20 units instead, so the total bid is reduced by 1.5 * (32 - 20) // ***NOTE***: receivedBandwidth is scaled by bandwidthScalingFactor // bool isPositive = (bandwidth * bandwidthScalingFactor >= users[userID].receivedBandwidth); // updatePrice(isPositive ? (bandwidth * bandwidthScalingFactor - users[userID].receivedBandwidth) : (users[userID].receivedBandwidth - bandwidth * bandwidthScalingFactor), isPositive); // -------------------------------------- // // ***REMOVED***: depending on the *desired bandwidth* instead, otherwise a user who only wants to top up his balance but retaining his desired bandwidth may // // unintentionally increase the price bool isPositive = (bandwidth >= users[userID].desiredBandwidth); updatePrice(isPositive ? (bandwidth - users[userID].desiredBandwidth) * bandwidthScalingFactor : (users[userID].desiredBandwidth - bandwidth) * bandwidthScalingFactor, isPositive); performAllocation(); updateBalance(); } // When the user has connected before but was deactivated from connection // The owner still keeps the user profile for a certain period function connectionReentry(uint userID, uint bandwidth, uint thresholdBid, uint burst) internal requirePayment { // Update user profile isActive[userID - 1] = true; totalDesiredBandwidth += bandwidth; // In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic if(bandwidthPrice * bandwidth / bandwidthPriceScalingFactor > thresholdBid) { isDynamic[userID - 1] = true; totalDesiredDynamic += bandwidth; } else { isDynamic[userID - 1] = false; totalDesiredNonDynamic += bandwidth; } totalDesiredBurst += burst; currentBalances[userID - 1] += msg.value; users[userID].desiredBandwidth = bandwidth; users[userID].lastPaymentTime = now; users[userID].thresholdBid = thresholdBid; users[userID].burst = burst; burstVol[userID - 1] = burst; updatePrice(bandwidth * bandwidthScalingFactor, true); performAllocation(); updateBalance(); } // When the user wants to quit the connection // The owner still keeps the user profile for a certain period function connectionTermination(uint userID) internal { uint deltaBandwidth = users[userID].receivedBandwidth; // uint deltaBandwidth = users[userID].desiredBandwidth * bandwidthScalingFactor; pendingWithdrawl[users[userID].userAddress] += (currentBalances[userID - 1] + msg.value); isActive[userID - 1] = false; totalDesiredBandwidth -= users[userID].desiredBandwidth; if(isDynamic[userID - 1]) { totalDesiredDynamic -= users[userID].desiredBandwidth; } else { totalDesiredNonDynamic -= users[userID].desiredBandwidth; } totalDesiredBurst -= users[userID].burst; isDynamic[userID - 1] = false; currentBalances[userID - 1] = 0; users[userID].receivedBandwidth = 0; users[userID].desiredBandwidth = 0; users[userID].thresholdBid = 0; users[userID].burst = 0; burstVol[userID - 1] = 0; allocatedBandwidth[userID - 1] = 0; actualPrices[userID - 1] = 0; // Similar to connectionRenewal(), the deltaBandwidth depends on the *actually received bandwidth* updatePrice(deltaBandwidth, false); performAllocation(); updateBalance(); } // When the total desired bandwidth does not exceed the available bandwidth: // Everyone simply gets as much as desired function demandNotExceedSupply() internal { for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { actualPrices[i] = bandwidthPrice; allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor; users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor; } } } // When the total desired bandwidth exceeds the available bandwidth: // The resource allocation mechanism is triggered function demandExceedSupply() internal { // uint weight; uint weightedPrice; updateIsDynamic(); if(totalDesiredNonDynamic >= totalBandwidth) { // Ignore isDynamic[] and actualPrices[], and all users are charged bandwidthPrice // Proportionally allocate the bandwidth according to desired bandwidth for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { actualPrices[i] = bandwidthPrice; allocatedBandwidth[i] = users[i + 1].desiredBandwidth * totalBandwidth * bandwidthScalingFactor / totalDesiredBandwidth; users[i + 1].receivedBandwidth = allocatedBandwidth[i]; } } } else { // Non-dynamic users receive desired bandwidth, while dynamic users proportionally share the remaining // weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic); // weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor; weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic); for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { if(isDynamic[i]) { actualPrices[i] = bandwidthPrice; allocatedBandwidth[i] = users[i + 1].desiredBandwidth * (totalBandwidth - totalDesiredNonDynamic) * bandwidthScalingFactor / totalDesiredDynamic; users[i + 1].receivedBandwidth = allocatedBandwidth[i]; } else { // actualPrices[i] = weight * bandwidthPrice / bandwidthPriceScalingFactor; actualPrices[i] = weightedPrice; allocatedBandwidth[i] = users[i + 1].desiredBandwidth * bandwidthScalingFactor; users[i + 1].receivedBandwidth = users[i + 1].desiredBandwidth * bandwidthScalingFactor; } } } } } // Update the real-time unit price according to user demand // NOTICE: deltaBandwidth is a scaled value function updatePrice(uint deltaBandwidth, bool isPositive) internal { // uint prevPrice = bandwidthPrice; oldPrice = bandwidthPrice; if(totalDesiredBandwidth <= totalBandwidth) { bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor; } else { if(isPositive) { // New price = Total bid / Total bandwidth = Current price * (Total allocated bandwidth + New demand) / Total bandwidth // (1) Total allocated bandwidth < Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth < totalBandwidth // (2) Total allocated bandwidth = Total bandwidth, i.e., totalDesiredBandwidth - deltaBandwidth >= totalBandwidth if(totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth < totalBandwidth * bandwidthScalingFactor) { bandwidthPrice = bandwidthPrice * totalDesiredBandwidth / totalBandwidth; } else { bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor + deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor); // bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor - deltaBandwidth); } } else { // The condition has guaranteed that: Total allocated bandwidth = Total bandwidth // New price = Total bid / Total bandwidth = Current Price * (Total bandwidth - Reduced demand) / Total bandwidth bandwidthPrice = bandwidthPrice * (totalBandwidth * bandwidthScalingFactor - deltaBandwidth) / (totalBandwidth * bandwidthScalingFactor); // bandwidthPrice = bandwidthPrice * totalDesiredBandwidth * bandwidthScalingFactor / (totalDesiredBandwidth * bandwidthScalingFactor + deltaBandwidth); } } burstPrice = minBurstPriceFactor * totalDesiredBurst * totalDesiredBurst; } // Update whether the user is dynamic according to current demand and price function updateIsDynamic() internal { // uint weight; uint weightedPrice; if(totalDesiredNonDynamic >= totalBandwidth) { for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { // In this case, the thresholdBid is compared with desiredBandwidth * bandwidthPrice to determine whether the user is dynamic if(!isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) { isDynamic[i] = true; totalDesiredNonDynamic -= users[i + 1].desiredBandwidth; totalDesiredDynamic += users[i + 1].desiredBandwidth; } else if (isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) { isDynamic[i] = false; totalDesiredDynamic -= users[i + 1].desiredBandwidth; totalDesiredNonDynamic += users[i + 1].desiredBandwidth; } } } } // Not using *else* here, since a second-round update may be needed after the first *if* // weight > 1, so some non-dynamic users after the first round may be tagged as dynamic in this round // weight is decreasing, so probably multiple rounds of update are needed // ***UPDATE***: Limit the number of cycles to avoid gas over limit uint numCycle; while(true) { numCycle++; bool hasChanged; if(totalDesiredNonDynamic < totalBandwidth) { // weight = totalDesiredDynamic * bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic); // weightedPrice = weight * bandwidthPrice / bandwidthPriceScalingFactor; weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic); // If the bid per unit time exceeds the thresholdBid, the user becomes dynamic for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { // In this case, the thresholdBid is compared with desiredBandwidth * weightedPrice to determine whether the user is dynamic if(!isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) { isDynamic[i] = true; totalDesiredNonDynamic -= users[i + 1].desiredBandwidth; totalDesiredDynamic += users[i + 1].desiredBandwidth; hasChanged = true; } else if(isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor <= users[i + 1].thresholdBid) { isDynamic[i] = false; totalDesiredDynamic -= users[i + 1].desiredBandwidth; totalDesiredNonDynamic += users[i + 1].desiredBandwidth; hasChanged = true; } } } } // Check numCycle to avoid infinite loop, e.g., when a user keeps changing between the dynamic and non-dynamic users if(!hasChanged || numCycle == 10 || totalDesiredNonDynamic == 0) { break; } } } // Allow the user to withdraw remaining balance upon connection termination function withdrawBalance() internal { uint amount = pendingWithdrawl[msg.sender]; pendingWithdrawl[msg.sender] = 0; msg.sender.transfer(amount); } // Allow the owner to collect bids submitted by users function collectBids() internal { uint amount = pendingCollection; pendingCollection = 0; totalCollected += amount; owner.transfer(amount); } // Clearing all existing user profiles and reset the parameters function resetAll() internal onlyOwner { for(uint i = 0; i < numUsers; i++) { delete(pendingWithdrawl[users[i + 1].userAddress]); delete(occupiedID[users[i + 1].userAddress]); delete(users[i + 1]); } delete currentBalances; delete allocatedBandwidth; delete actualPrices; delete isDynamic; delete isActive; delete numUsers; delete totalCollected; delete pendingCollection; bandwidthPrice = minBandwidthPrice * bandwidthPriceScalingFactor; delete totalDesiredBurst; delete totalDesiredDynamic; delete totalDesiredNonDynamic; delete totalDesiredBandwidth; delete burstVol; } }
Update whether the user is dynamic according to current demand and price uint weight; In this case, the thresholdBid is compared with desiredBandwidth bandwidthPrice to determine whether the user is dynamic weight = totalDesiredDynamic bandwidthPriceScalingFactor / (totalBandwidth - totalDesiredNonDynamic); weightedPrice = weight bandwidthPrice / bandwidthPriceScalingFactor; If the bid per unit time exceeds the thresholdBid, the user becomes dynamic In this case, the thresholdBid is compared with desiredBandwidth weightedPrice to determine whether the user is dynamic Check numCycle to avoid infinite loop, e.g., when a user keeps changing between the dynamic and non-dynamic users
function updateIsDynamic() internal { uint weightedPrice; if(totalDesiredNonDynamic >= totalBandwidth) { for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { if(!isDynamic[i] && bandwidthPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) { isDynamic[i] = true; totalDesiredNonDynamic -= users[i + 1].desiredBandwidth; totalDesiredDynamic += users[i + 1].desiredBandwidth; isDynamic[i] = false; totalDesiredDynamic -= users[i + 1].desiredBandwidth; totalDesiredNonDynamic += users[i + 1].desiredBandwidth; } } } } while(true) { numCycle++; bool hasChanged; if(totalDesiredNonDynamic < totalBandwidth) { weightedPrice = totalDesiredDynamic * bandwidthPrice / (totalBandwidth - totalDesiredNonDynamic); for(uint i = 0; i < numUsers; i++) { if(isActive[i]) { if(!isDynamic[i] && weightedPrice * users[i + 1].desiredBandwidth / bandwidthPriceScalingFactor > users[i + 1].thresholdBid) { isDynamic[i] = true; totalDesiredNonDynamic -= users[i + 1].desiredBandwidth; totalDesiredDynamic += users[i + 1].desiredBandwidth; hasChanged = true; isDynamic[i] = false; totalDesiredDynamic -= users[i + 1].desiredBandwidth; totalDesiredNonDynamic += users[i + 1].desiredBandwidth; hasChanged = true; } } } } if(!hasChanged || numCycle == 10 || totalDesiredNonDynamic == 0) { break; } } }
6,478,446
pragma solidity ^0.4.6; import "zeppelin/contracts/SafeMath.sol"; import "./Crowdsale.sol"; import "./StandardToken.sol"; import "./Haltable.sol"; /** * Collect funds from presale investors, buy tokens for them in a single transaction and distribute out tokens. * * - Collect funds from pre-sale investors * - Send funds to the crowdsale when it opens * - Allow owner to set the crowdsale * - Have refund after X days as a safety hatch if the crowdsale doesn't materilize * - Allow unlimited investors * - Tokens are distributed on PreICOProxyBuyer smart contract first * - The original investors can claim their tokens from the smart contract after the token transfer has been released * - All functions can be halted by owner if something goes wrong * */ contract PreICOProxyBuyer is Ownable, Haltable, SafeMath { /** How many investors we have now */ uint public investorCount; /** How many wei we have raised totla. */ uint public weiRaisedTotal; /** Who are our investors (iterable) */ address[] public investors; /** How much they have invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When our refund freeze is over (UNIT timestamp) */ uint public freezeEndsAt; /** What is the minimum buy in */ uint public weiMinimumLimit; /** How many weis total we are allowed to collect. */ uint public weiCap; /** How many tokens were bought */ uint public tokensBought; /** How many investors have claimed their tokens */ uint public claimCount; uint public totalClaimed; /** Our ICO contract where we will move the funds */ Crowdsale public crowdsale; /** What is our current state. */ enum State{Unknown, Funding, Distributing, Refunding} /** Somebody loaded their investment money */ event Invested(address investor, uint value); /** Refund claimed */ event Refunded(address investor, uint value); /** We executed our buy */ event TokensBoughts(uint count); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); /** * Create presale contract where lock up period is given days */ function PreICOProxyBuyer(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit, uint _weiCap) { owner = _owner; // Give argument if(_freezeEndsAt == 0) { throw; } // Give argument if(_weiMinimumLimit == 0) { throw; } weiMinimumLimit = _weiMinimumLimit; weiCap = _weiCap; freezeEndsAt = _freezeEndsAt; } /** * Get the token we are distributing. */ function getToken() public constant returns(FractionalERC20) { if(address(crowdsale) == 0) { throw; } return crowdsale.token(); } /** * Participate to a presale. */ function invest() public stopInEmergency payable { // Cannot invest anymore through crowdsale when moving has begun if(getState() != State.Funding) throw; if(msg.value == 0) throw; // No empty buys address investor = msg.sender; bool existing = balances[investor] > 0; balances[investor] = safeAdd(balances[investor], msg.value); // Need to fulfill minimum limit if(balances[investor] < weiMinimumLimit) { throw; } // This is a new investor if(!existing) { investors.push(investor); investorCount++; } weiRaisedTotal = safeAdd(weiRaisedTotal, msg.value); if(weiRaisedTotal > weiCap) { throw; } Invested(investor, msg.value); } /** * Load funds to the crowdsale for all investors. * * */ function buyForEverybody() stopInEmergency public { if(getState() != State.Funding) { // Only allow buy once throw; } // Crowdsale not yet set if(address(crowdsale) == 0) throw; // Buy tokens on the contract crowdsale.invest.value(weiRaisedTotal)(address(this)); // Record how many tokens we got tokensBought = getToken().balanceOf(address(this)); if(tokensBought == 0) { // Did not get any tokens throw; } TokensBoughts(tokensBought); } /** * How may tokens each investor gets. */ function getClaimAmount(address investor) public constant returns (uint) { // Claims can be only made if we manage to buy tokens if(getState() != State.Distributing) { throw; } return safeMul(balances[investor], tokensBought) / weiRaisedTotal; } /** * How many tokens remain unclaimed for an investor. */ function getClaimLeft(address investor) public constant returns (uint) { return safeSub(getClaimAmount(investor), claimed[investor]); } /** * Claim all remaining tokens for this investor. */ function claimAll() { claim(getClaimLeft(msg.sender)); } /** * Claim N bought tokens to the investor as the msg sender. * */ function claim(uint amount) stopInEmergency { address investor = msg.sender; if(amount == 0) { throw; } if(getClaimLeft(investor) < amount) { // Woops we cannot get more than we have left throw; } // We track who many investor have (partially) claimed their tokens if(claimed[investor] == 0) { claimCount++; } claimed[investor] = safeAdd(claimed[investor], amount); totalClaimed = safeAdd(totalClaimed, amount); getToken().transfer(investor, amount); Distributed(investor, amount); } /** * ICO never happened. Allow refund. */ function refund() stopInEmergency { // Trying to ask refund too soon if(getState() != State.Refunding) throw; address investor = msg.sender; if(balances[investor] == 0) throw; uint amount = balances[investor]; delete balances[investor]; if(!investor.send(amount)) throw; Refunded(investor, amount); } /** * Set the target crowdsale where we will move presale funds when the crowdsale opens. */ function setCrowdsale(Crowdsale _crowdsale) public onlyOwner { crowdsale = _crowdsale; // Check interface if(!crowdsale.isCrowdsale()) true; } /** * Resolve the contract umambigious state. */ function getState() public returns(State) { if(tokensBought == 0) { if(now >= freezeEndsAt) { return State.Refunding; } else { return State.Funding; } } else { return State.Distributing; } } /** Explicitly call function from your wallet. */ function() payable { throw; } }
Somebody loaded their investment money / Refund claimed / We executed our buy / We distributed tokens to an investor / Create presale contract where lock up period is given days/ Give argument Give argument
function PreICOProxyBuyer(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit, uint _weiCap) { owner = _owner; if(_freezeEndsAt == 0) { throw; } if(_weiMinimumLimit == 0) { throw; } weiMinimumLimit = _weiMinimumLimit; weiCap = _weiCap; freezeEndsAt = _freezeEndsAt; }
12,765,530
./full_match/1/0xa55F73Da180C176AB769E124a74933C5824c3615/sources/ProjectRadiance.sol
Check whether public sales are already started
function isSaleOn() public view returns (bool) { return block.timestamp >= saleStartTime; }
2,920,421
./full_match/80001/0xC5175391470dA0CD3BfD2EAC79123C331Ff7a541/sources/_xaya/eth-delegator-contract/contracts/MovePermissions.sol
Revokes permissions for an address in a PermissionsMap (i.e. removes the corresponding entry, keeping "keys" up-to-date)./ Now we need to remove the entry from keys. If it is the last one,
function removeEntry (PermissionsMap storage map, address key) private { uint oldIndex = map.forAddress[key].indexAndOne; if (oldIndex == 0) return; delete map.forAddress[key]; we can just pop. Otherwise we swap the last element into its position and pop then. */ if (oldIndex < map.keys.length) { address last = map.keys[map.keys.length - 1]; map.keys[oldIndex - 1] = last; AddressPermissions storage lastEntry = map.forAddress[last]; assert (lastEntry.indexAndOne > 0); lastEntry.indexAndOne = oldIndex; } map.keys.pop (); }
5,564,613
pragma solidity ^0.4.21; /** https://goldenmoon.io https://goldenmoon.io https://goldenmoon.io https://goldenmoon.io https://goldenmoon.io ______ __ __ __ ___ / ____/___ / /___/ /__ ____ / |/ /___ ____ ____ / / __/ __ \/ / __ / _ \/ __ \ / /|_/ / __ \/ __ \/ __ \ / /_/ / /_/ / / /_/ / __/ / / / / / / / /_/ / /_/ / / / / \____/\____/_/\__,_/\___/_/ /_/ /_/ /_/\____/\____/_/ /_/ A pyramid scheme, 25% buy and sell fee contract with fair distributed tokens among investors. GMOON tokens used on games which will be released after pyramid launch on 19th 10pm EST. Credits ======= Contract Developer: > GoldenMoon Front-End Design: > roman25 **/ contract AcceptsGMOON { GMOON public tokenContract; function AcceptsGMOON(address _tokenContract) public { tokenContract = GMOON(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract GMOON { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } //Public sale opens (token purchase) at 10pm EST / 10am China / 9am South Korea uint activatePublicPurchase = 1535248800; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; //Activate the timer for public sale (token purchase) at 10pm EST / 10am China / 9am South Korea if (now >= activatePublicPurchase) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event OnRedistribution ( uint256 amount, uint256 timestamp ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "GoldenMoon"; string public symbol = "GMOON"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 25; // 25% dividend fee on each buy and sell uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 1 tokens) uint256 public stakingRequirement = 1e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = .3 ether; uint256 constant internal ambassadorQuota_ = 3 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper game) bool public onlyAmbassadors = true; // Special GoldenMoon Platform control from scam game contracts on GoldenMoon platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept GMOON tokens /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function GMOON() public { // administrators administrators[0x9C98A3eE07F53b3BFAd5Aa83a62Ac96600aED8b5] = true; administrators[0xe0212f02C1AD10f3DDA645F4F9775a0e3604d0B5] = true; // ambassadors - goldenmoon (main dev) ambassadors_[0x9C98A3eE07F53b3BFAd5Aa83a62Ac96600aED8b5] = true; // ambassadors - roman25 (front end dev) ambassadors_[0xe0212f02C1AD10f3DDA645F4F9775a0e3604d0B5] = true; // ambassadors - Ravi ambassadors_[0x41a21b264F9ebF6cF571D4543a5b3AB1c6bEd98C] = true; // ambassadors - Amit ambassadors_[0x421D7643Cf71b704c0E13d23f34bE18846237574] = true; // ambassadors - Xrypto ambassadors_[0xD5FA3017A6af76b31eB093DFA527eE1D939f05ea] = true; // ambassadors - Khan.Among.Lions.Amid.Pyramids ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8] = true; // ambassadors - yobo ambassadors_[0x190A2409fc6434483D4c2CAb804E75e3Bc5ebFa6] = true; // ambassadors - Flytothemars ambassadors_[0xAdcc19C8873193223460F67552ddec01C16CE32E] = true; // ambassadors - udaman ambassadors_[0xEE22F8Ca234C8Ca35c22593ac5524643B8136bdF] = true; // ambassadors - Jacksonkid ambassadors_[0xc7F15d0238d207e19cce6bd6C0B85f343896F046] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { require(tx.gasprice <= 0.05 szabo); purchaseInternal(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { //Max gas limit 50 Gwei( to avoid gas war especialy in early stage ) require(tx.gasprice <= 0.05 szabo); purchaseInternal(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); // Take out dividends uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by GoldenMoon platform require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsGMOON receiver = AcceptsGMOON(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept GMOON tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more then 3 ether before 100 ETH in contract function purchaseInternal(uint256 _incomingEthereum, address _referredBy) notContract()// no contracts allowed internal returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > 3 ether) { // check if the transaction is over 3 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether purchaseEthereum = 3 ether; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } purchaseTokens(purchaseEthereum, _referredBy); if (excess > 0) { msg.sender.transfer(excess); } } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the game somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
Return the sell price of 1 individual token./ our calculation relies on the token supply, so we need supply. Doh.
function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } }
2,419,594
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "hardhat/console.sol"; import "./ExampleExternalContract.sol"; /** * @title Stacker Contract * @author scaffold-eth * @notice A contract that allow users to stack ETH */ contract Staker { // External contract that will old stacked funds ExampleExternalContract public exampleExternalContract; // Balances of the user's stacked funds mapping(address => uint256) public balances; // Staking threshold uint256 public constant threshold = 1 ether; // Staking deadline uint256 public deadline = block.timestamp + 30 seconds; // Contract's Events event Stake(address indexed sender, uint256 amount); // Contract's Modifiers /** * @notice Modifier that require the deadline to be reached or not * @param requireReached Check if the deadline has reached or not */ modifier deadlineReached( bool requireReached ) { uint256 timeRemaining = timeLeft(); if( requireReached ) { require(timeRemaining == 0, "Deadline is not reached yet"); } else { require(timeRemaining > 0, "Deadline is already reached"); } _; } /** * @notice Modifier that require the external contract to not be completed */ modifier stakeNotCompleted() { bool completed = exampleExternalContract.completed(); require(!completed, "staking process already completed"); _; } /** * @notice Contract Constructor * @param exampleExternalContractAddress Address of the external contract that will hold stacked funds */ constructor(address exampleExternalContractAddress) { exampleExternalContract = ExampleExternalContract(exampleExternalContractAddress); } function execute() public stakeNotCompleted deadlineReached(false) { uint256 contractBalance = address(this).balance; // check the contract has enough ETH to reach the treshold require(contractBalance >= threshold, "Threshold not reached"); // Execute the external contract, transfer all the balance to the contract // (bool sent, bytes memory data) = exampleExternalContract.complete{value: contractBalance}(); (bool sent,) = address(exampleExternalContract).call{value: contractBalance}(abi.encodeWithSignature("complete()")); require(sent, "exampleExternalContract.complete failed"); } /** * @notice Stake method that update the user's balance */ function stake() public payable deadlineReached(false) stakeNotCompleted { // update the user's balance balances[msg.sender] += msg.value; // emit the event to notify the blockchain that we have correctly Staked some fund for the user emit Stake(msg.sender, msg.value); } /** * @notice Allow users to withdraw their balance from the contract only if deadline is reached but the stake is not completed */ function withdraw() public deadlineReached(true) stakeNotCompleted { uint256 userBalance = balances[msg.sender]; // check if the user has balance to withdraw require(userBalance > 0, "You don't have balance to withdraw"); // reset the balance of the user balances[msg.sender] = 0; // Transfer balance back to the user (bool sent,) = msg.sender.call{value: userBalance}(""); require(sent, "Failed to send user balance back to the user"); } /** * @notice The number of seconds remaining until the deadline is reached */ function timeLeft() public view returns (uint256 timeleft) { if( block.timestamp >= deadline ) { return 0; } else { return deadline - block.timestamp; } } }
Allow users to withdraw their balance from the contract only if deadline is reached but the stake is not completed/ check if the user has balance to withdraw reset the balance of the user Transfer balance back to the user
function withdraw() public deadlineReached(true) stakeNotCompleted { uint256 userBalance = balances[msg.sender]; require(userBalance > 0, "You don't have balance to withdraw"); balances[msg.sender] = 0; require(sent, "Failed to send user balance back to the user"); }
13,073,966
//SPDX-License-Identifier: TBD pragma solidity =0.7.4; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface ICoinSwapERC20 is IERC20 { event Swap(address indexed,uint192,uint192,address indexed); event Sync(uint); event Mint(address indexed sender, uint192); event Burn(address indexed sender, uint192, address indexed to); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface ICoinSwapCallee { function coinswapCall(address sender, uint amount0,uint amount1, bytes calldata data) external; } contract CoinSwapERC20 is ICoinSwapERC20 { using SafeMath for uint; string public constant override name = 'CoinSwap V1'; string public constant override symbol = 'CSWPLT';//CoinSwap Liquidity Token uint8 public constant override decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override nonces; constructor() { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'CSWP:01'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'CSWP:02'); _approve(owner, spender, value); } } contract CoinSwapPair is CoinSwapERC20 { using SafeMath for uint; address public patron; address public factory; address public token0; // token0 < token1 address public token1; uint224 private reserve; //reserve0(96) | reserve1(96) | blockTimestampLast(32) uint private unlocked = 1; uint public priceCumulative; //=Delta_y/Delta_x: 96-fractional bits; allows overflow uint224 private circleData; modifier lock() { require(unlocked == 1, 'CSWP:1'); unlocked = 0; _; unlocked = 1; } constructor() {factory = msg.sender; patron=tx.origin;} function initialize(address _token0, address _token1, uint224 circle) external { //circle needs to in order of token0<token1 require(circleData == 0, 'CSWP:2'); token0 = _token0; token1 = _token1; circleData = circle; // validity of circle should be checked by CoinSwapFactory } function ICO(uint224 _circleData) external { require( (tx.origin==patron) && (circleData >> 216) >0, 'CSWP:3');//to close ICO, set (circleData >> 216) = 0x00 circleData = _circleData; } function setPatron(address _patron) external { require( (tx.origin==patron), 'CSWP:11'); patron = _patron; } function getReserves() public view returns (uint224 _reserve, uint224 _circleData) { _reserve = reserve; _circleData = circleData; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP:6'); } function revisemu(uint192 balance) private returns (uint56 _mu) { require(balance>0, 'CSWP:4'); uint224 _circleData = circleData; uint X = uint(balance>>96) * uint16(_circleData >> 72)* uint56(_circleData >> 160); uint Y = uint(uint96(balance)) * uint16(_circleData >> 56)* uint56(_circleData >> 104); uint XpY = X + Y; uint X2pY2 = (X*X) + (Y*Y); X = XpY*100; Y = (X*X) + X2pY2 * (10000+ uint16(_circleData>>88)); uint Z= X2pY2 * 20000; require(Y>Z, 'CSWP:5'); Y = SQRT.sqrt(Y-Z); Z = Y > X ? X + Y : X-Y; _mu = uint56(1)+uint56(((10**32)*Z) / X2pY2); circleData = (_circleData & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(_mu); } // update reserves and, on the first call per block, price accumulators function _update(uint balance) private { uint32 lastTime = uint32(balance); uint32 deltaTime = uint32(block.timestamp) -lastTime ; if (deltaTime>0 && lastTime>0) { uint circle = circleData; uint lambda0 = uint16(circle >> 72); uint lambda1 = uint16(circle >> 56); uint CmulambdaX = 10**34 - (balance>>128) *lambda0*uint56(circle)*uint56(circle >> 160); uint CmulambdaY = 10**34 - uint96(balance>>32)*lambda1*uint56(circle)*uint56(circle >> 104); priceCumulative += (((lambda0*CmulambdaX)<< 96)/(lambda1*CmulambdaY)) * deltaTime; } reserve = uint224(balance +deltaTime); emit Sync(balance>>32); } function _mintFee(uint56 mu0) private returns (uint56 mu) { address feeTo = CoinSwapFactory(factory).feeTo(); mu=revisemu(uint192(reserve>>32)); if (mu0>mu) _mint(feeTo, totalSupply.mul(uint(mu0-mu)) / (5*mu0+mu)); } function mint(address to) external lock returns (uint liquidity) { uint224 circle = circleData; uint _totalSupply = totalSupply; uint224 _reserve = reserve; uint96 reserve0 = uint96(_reserve >>128); uint96 reserve1 = uint96(_reserve >>32); uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint scaledBalance0 = balance0* uint56(circle >> 160); uint scaledBalance1 = balance1* uint56(circle >> 104); require((scaledBalance0< 2**96) && (scaledBalance1< 2**96) && ( scaledBalance0 >=10**16 || scaledBalance1 >=10**16), 'CSWP:7'); if (_totalSupply == 0) { uint lambda0 = uint16(circle >> 72); uint lambda1 = uint16(circle >> 56); liquidity = (scaledBalance0 * lambda0 + scaledBalance1 * lambda1) >> 1; revisemu(uint192((balance0<<96)|balance1)); } else { uint56 mu0=_mintFee(uint56(circle)); _totalSupply = totalSupply; (uint mu, uint _totalS)=(0,0); if (reserve0==0) { mu=(uint(mu0) * reserve1) / balance1; _totalS = _totalSupply.mul(balance1)/reserve1; } else if (reserve1==0) { mu=(uint(mu0) * reserve0) / balance0; _totalS = _totalSupply.mul(balance0)/reserve0; } else { (mu, _totalS) = (balance0 * reserve1) < (balance1 * reserve0)? ((uint(mu0) * reserve0) / balance0, _totalSupply.mul(balance0)/reserve0) : ((uint(mu0) * reserve1) / balance1, _totalSupply.mul(balance1)/reserve1) ; } liquidity = _totalS - _totalSupply; circleData = (circle & 0xFF_FFFFFFFFFFFFFF_FFFFFFFFFFFFFF_FFFF_FFFF_FFFF_00000000000000) | uint224(mu); } _mint(to, liquidity); _update(balance0<<128 | balance1<<32 | uint32(_reserve)); emit Mint(msg.sender, uint192((balance0-reserve0)<<96 | (balance1-reserve1))); } function burn(address to) external lock returns (uint192 amount) { uint224 _reserve = reserve; address _token0 = token0; address _token1 = token1; _mintFee(uint56(circleData)); uint _totalSupply = totalSupply; uint liquidity = balanceOf[address(this)]; uint amount0 = liquidity.mul(uint96(_reserve>>128)) / _totalSupply; uint amount1 = liquidity.mul(uint96(_reserve>>32)) / _totalSupply; amount = uint192((amount0<<96)|amount1); require(amount > 0, 'CSWP:8'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); uint192 combinedBalance = uint192(IERC20(_token0).balanceOf(address(this))<<96 | IERC20(_token1).balanceOf(address(this))); _update(uint(combinedBalance)<<32 | uint32(_reserve)); if (combinedBalance>0) revisemu(combinedBalance); emit Burn(msg.sender, amount, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amountOut, address to, bytes calldata data) external lock { uint amount0Out = (amountOut >> 96); uint amount1Out = uint(uint96(amountOut)); uint balance0; uint balance1; uint _circleData = circleData; { // avoids stack too deep errors address _token0 = token0; address _token1 = token1; require((to != _token0) && (to != _token1), 'CSWP:9'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); if (data.length > 0) ICoinSwapCallee(to).coinswapCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); require(balance0*uint56(_circleData >> 160) < 2**96 && balance1*uint56(_circleData >> 104) < 2**96, 'CSWP:10'); } uint amountIn0; uint amountIn1; uint224 _reserve = reserve; {// if _reserve0 < amountOut, then should have been reverted above already, so no need to check here uint96 reserve0 = uint96(_reserve >>128); uint96 reserve1 = uint96(_reserve >>32); amountIn0 = balance0 + amount0Out - reserve0; amountIn1 = balance1 + amount1Out - reserve1; uint mulambda0 = uint(uint16(_circleData >> 72))*uint56(_circleData)*uint56(_circleData >> 160); uint mulambda1 = uint(uint16(_circleData >> 56))*uint56(_circleData)*uint56(_circleData >> 104); uint X=mulambda0*(balance0*1000 - amountIn0*3); uint Y=mulambda1*(balance1*1000 - amountIn1*3); require(10**37 > X && 10**37 >Y, 'CSWP:11'); X = 10**37-X; Y = 10**37-Y; uint newrSquare = X*X+Y*Y; X=10**37-(mulambda0 * reserve0*1000); Y=10**37-(mulambda1 * reserve1*1000); require(newrSquare<= (X*X+Y*Y), 'CSWP:12'); } _update(balance0<<128 | balance1<<32 | uint32(_reserve)); emit Swap(msg.sender, uint192(amountIn0<<96 | amountIn1), uint192(amountOut), to); } } contract CoinSwapFactory { address payable public feeTo; address payable public feeToSetter; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address payable _feeToSetter) { feeToSetter = _feeToSetter; feeTo = _feeToSetter; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB, uint224 circle) external returns (address pair) { require(tx.origin==feeToSetter, 'CSWP:22'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(getPair[token0][token1] == address(0), 'CSWP:20'); require(uint16(circle>>56)>0 && uint16(circle>>72)>0 && uint16(circle>>88)>0 && uint16(circle>>88)<=9999 && uint56(circle>>104)>=1 && uint56(circle>>104)<=10**16 && uint56(circle>>160)>=1 && uint56(circle>>160)<=10**16, 'CSWP:23'); bytes memory bytecode = type(CoinSwapPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } CoinSwapPair(pair).initialize(token0, token1, circle); getPair[token0][token1] = pair; getPair[token1][token0] = pair; allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address payable _feeTo) external { require(msg.sender == feeToSetter, 'CSWP:21'); feeTo = _feeTo; } function setFeeToSetter(address payable _feeToSetter) external { require(msg.sender == feeToSetter, 'CSWP:22'); feeToSetter = _feeToSetter; } } contract CoinSwapRouterV1 { using SafeMath for uint; address public immutable factory; address public immutable WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'CSWP:30'); _; } constructor(address _factory, address _WETH) { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, uint224 circle //lambda0/lambda1 in circle needs in order of token0<token1 ) internal virtual returns (uint amountA, uint amountB, address pairForAB) { pairForAB =CoinSwapFactory(factory).getPair(tokenA, tokenB); if (pairForAB == address(0)) { pairForAB= CoinSwapFactory(factory).createPair(tokenA,tokenB,circle); } (uint reserveA, uint reserveB,) = CoinSwapLibrary.getReservesAndmu(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else if (reserveA == 0) { (amountA, amountB) = (0, amountBDesired); } else if (reserveB == 0) { (amountA, amountB) = (amountADesired,0); } else { uint amountBOptimal = (amountADesired *reserveB) / reserveA; if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'CSWP:31'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = (amountBDesired *reserveA) / reserveB; assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'CSWP:32'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amtADesired, uint amtBDesired, uint amtAMin, uint amtBMin, address to, uint deadline, uint224 circle ) external virtual ensure(deadline) returns (uint amtA, uint amtB, uint liquidity) { address pair; (amtA, amtB, pair) = _addLiquidity(tokenA, tokenB, amtADesired, amtBDesired, amtAMin, amtBMin, circle); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amtA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amtB); liquidity = CoinSwapPair(pair).mint(to); } function addLiquidityETH( address token, uint amtTokenDesired, uint amtTokenMin, uint amtETHMin, address to, uint deadline, uint224 circle ) external virtual payable ensure(deadline) returns (uint amtToken, uint amtETH, uint liquidity) { address pair; (amtToken, amtETH, pair) = _addLiquidity(token,WETH,amtTokenDesired,msg.value,amtTokenMin,amtETHMin,circle); TransferHelper.safeTransferFrom(token, msg.sender, pair, amtToken); IWETH(WETH).deposit{value: amtETH}(); assert(IWETH(WETH).transfer(pair, amtETH)); liquidity = CoinSwapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amtETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amtETH); } // **** REMOVE LIQUIDITY **** // For OCI market, we do not have specific remove liquidity function // but one can remove a pair by providing OCI-ed addresses function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amtAMin, uint amtBMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountA, uint amountB) { address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB); CoinSwapPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair uint192 amount = CoinSwapPair(pair).burn(to); (amountA, amountB) = tokenA < tokenB ? (uint(amount>>96), uint(uint96(amount))) : (uint(uint96(amount)), uint(amount>>96)); require((amountA >= amtAMin) && (amountB >= amtBMin), 'CSWP:33'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountA, uint amountB) { address pair = CoinSwapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountToken, uint amountETH) { address pair = CoinSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint amountETH) { address pair = CoinSwapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; CoinSwapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)).swap( uint192((amount0Out<<96) | amount1Out), to, new bytes(0)); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) returns (uint[] memory amounts) { amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:34'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) returns (uint[] memory amounts) { amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'CSWP:35'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CSWP:36'); amounts = CoinSwapLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:37'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CSWP:38'); amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'CSWP:39'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'CSWP:40'); amounts = CoinSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'CSWP:41'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'CSWP:42'); amounts = CoinSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'CSWP:43'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); CoinSwapPair pair = CoinSwapPair(CoinSwapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserveInput, uint reserveOutput, uint mulambda) = CoinSwapLibrary.getReservesAndmu(factory, input, output); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = CoinSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, mulambda); } (uint amount0Out, uint amount1Out) = input < output ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? CoinSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(uint192(amount0Out<<96 | amount1Out), to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CSWP:44' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual payable ensure(deadline) { require(path[0] == WETH, 'CSWP:45'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'CSWP:46' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual ensure(deadline) { require(path[path.length - 1] == WETH, 'CSWP:47'); TransferHelper.safeTransferFrom( path[0], msg.sender, CoinSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'CSWP:48'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountOut) { return CoinSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut, mulambda); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) public pure returns (uint amountIn) { return CoinSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut, mulambda); } function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts) { return CoinSwapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts) { return CoinSwapLibrary.getAmountsIn(factory, amountOut, path); } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP70'); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP71'); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP72'); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'CSWP73'); } } library CoinSwapLibrary { using SafeMath for uint; // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'08d6ace72c919d3777e7a6a0ae82941b79932ea4e7b37e16d8c04f7fd2783574' )))); } function getReservesAndmu(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB, uint mulambda) { (uint224 reserve, uint224 circleData) = CoinSwapPair(pairFor(factory, tokenA, tokenB)).getReserves(); uint reserve0 = uint(reserve>>128); uint reserve1 = uint(uint96(reserve>>32)); uint mulambda0 = uint(uint16(circleData >> 72))* uint56(circleData >> 160) * uint56(circleData); uint mulambda1 = uint(uint16(circleData >> 56))* uint56(circleData >> 104) * uint56(circleData); (reserveA, reserveB, mulambda) = tokenA < tokenB ? (reserve0,reserve1, (mulambda0<<128) | mulambda1 ):(reserve1,reserve0, (mulambda1<<128) | mulambda0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountOut) { require((amountIn > 0) && (reserveOut > 0), 'CSWP:63'); uint mulambda0 = (mulambda>>128); uint mulambda1 = uint(uint128(mulambda)); uint Z = 10**37-(mulambda0 * reserveIn * 1000); uint R0=Z*Z; Z= 10**37-(mulambda1 * reserveOut * 1000); R0 += Z*Z; uint ZZ = uint(10**37).sub(mulambda0 * (1000*reserveIn + amountIn * 997)); R0 = R0.sub(ZZ*ZZ); R0 = SQRT.sqrt(R0); amountOut = R0.sub(Z) / (mulambda1 * 1000); if (amountOut > reserveOut) amountOut = reserveOut; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint mulambda) internal pure returns (uint amountIn) { uint mulambda0 = (mulambda>>128); uint mulambda1 = uint(uint128(mulambda)); uint Z= 10**37-(mulambda1 * reserveOut * 1000); uint R1 = Z*Z; Z = 10**37-(mulambda0 * reserveIn * 1000); R1 += Z*Z; uint ZZ = 10**37-(mulambda1 * 1000* (reserveOut.sub(amountOut))); R1 =R1.sub(ZZ*ZZ); amountIn = 1+ (Z.sub(SQRT.sqrt(R1))) / (mulambda0 * 997) ; } function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'CSWP:65'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut, uint mulambda) = getReservesAndmu(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, mulambda); } } function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'CSWP:66'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut, uint mulambda) = getReservesAndmu(factory, path[i-1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, mulambda); } } } library SQRT { function sqrt(uint256 a) internal pure returns (uint256 x) { if (a > 3) { uint msbpos =0; uint b=a; if (b > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { msbpos += 128; b = b >> 128; } if (b > 0xFFFFFFFFFFFFFFFF) { msbpos += 64; b = b>>64; } if (b > 0xFFFFFFFF ) { msbpos += 32; b = b>>32; } if (b > 0xFFFF ) { msbpos += 16; b = b>>16; } if (b > 0xFF ) { msbpos += 8; b = b>>8; } if (b > 0xF ) { msbpos += 4; } msbpos += 4; uint256 x0=a; uint X=((a >> 1) + 1); uint Y=2**(msbpos/2); x = X< Y ? X : Y; while (x < x0 ) { x0 = x; x = (a / x0 + x0) >> 1; } } else if (a != 0) { x = 1; } } } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'CSWP72'); }
6,170,226
//Address: 0xa76ea481aebdd5703e476cfcb2315d4e014232c1 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 2/27/2018 //Transacion Count: 4345 // CODE STARTS HERE pragma solidity ^0.4.17; contract J8TTokenConfig { // The J8T decimals uint8 public constant TOKEN_DECIMALS = 8; // The J8T decimal factor to obtain luckys uint256 public constant J8T_DECIMALS_FACTOR = 10**uint256(TOKEN_DECIMALS); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } ////////////////////////////////////////////////////////////////////// // @title J8T Token // // @dev ERC20 J8T Token // // // // J8T Tokens are divisible by 1e8 (100,000,000) base // // // // J8T are displayed using 8 decimal places of precision. // // // // 1 J8T is equivalent to 100000000 luckys: // // 100000000 == 1 * 10**8 == 1e8 == One Hundred Million luckys // // // // 1,5 Billion J8T (total supply) is equivalent to: // // 150000000000000000 == 1500000000 * 10**8 == 1,5e17 luckys // // // ////////////////////////////////////////////////////////////////////// contract J8TToken is J8TTokenConfig, BurnableToken, Ownable { string public constant name = "J8T Token"; string public constant symbol = "J8T"; uint256 public constant decimals = TOKEN_DECIMALS; uint256 public constant INITIAL_SUPPLY = 1500000000 * (10 ** uint256(decimals)); event Transfer(address indexed _from, address indexed _to, uint256 _value); function J8TToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 //EIP 20: A token contract which creates new tokens SHOULD trigger a //Transfer event with the _from address set to 0x0 //when tokens are created. Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } contract ACLManaged is Ownable { /////////////////////////// // ACLManaged PROPERTIES // /////////////////////////// // The operational acl address address public opsAddress; // The admin acl address address public adminAddress; //////////////////////////////////////// // ACLManaged FUNCTIONS and MODIFIERS // //////////////////////////////////////// function ACLManaged() public Ownable() {} // Updates the opsAddress propety with the new _opsAddress value function setOpsAddress(address _opsAddress) external onlyOwner returns (bool) { require(_opsAddress != address(0)); require(_opsAddress != address(this)); opsAddress = _opsAddress; return true; } // Updates the adminAddress propety with the new _adminAddress value function setAdminAddress(address _adminAddress) external onlyOwner returns (bool) { require(_adminAddress != address(0)); require(_adminAddress != address(this)); adminAddress = _adminAddress; return true; } //Checks if an address is owner function isOwner(address _address) public view returns (bool) { bool result = (_address == owner); return result; } //Checks if an address is operator function isOps(address _address) public view returns (bool) { bool result = (_address == opsAddress); return result; } //Checks if an address is ops or admin function isOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress); return result; } //Checks if an address is ops,owner or admin function isOwnerOrOpsOrAdmin(address _address) public view returns (bool) { bool result = (_address == opsAddress || _address == adminAddress || _address == owner); return result; } //Checks whether the msg.sender address is equal to the adminAddress property or not modifier onlyAdmin() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == adminAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress property or not modifier onlyOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress); _; } // Checks whether the msg.sender address is equal to the opsAddress or adminAddress property modifier onlyAdminAndOps() { //Needs to be set. Default constructor will set 0x0; address _address = msg.sender; require(_address != address(0)); require(_address == opsAddress || _address == adminAddress); _; } } contract CrowdsaleConfig is J8TTokenConfig { using SafeMath for uint256; // Default start token sale date is 28th February 15:00 SGP 2018 uint256 public constant START_TIMESTAMP = 1519801200; // Default end token sale date is 14th March 15:00 SGP 2018 uint256 public constant END_TIMESTAMP = 1521010800; // The ETH decimal factor to obtain weis uint256 public constant ETH_DECIMALS_FACTOR = 10**uint256(18); // The token sale supply uint256 public constant TOKEN_SALE_SUPPLY = 450000000 * J8T_DECIMALS_FACTOR; // The minimum contribution amount in weis uint256 public constant MIN_CONTRIBUTION_WEIS = 0.1 ether; // The maximum contribution amount in weis uint256 public constant MAX_CONTRIBUTION_WEIS = 10 ether; //@WARNING: WORKING WITH KILO-MULTIPLES TO AVOID IMPOSSIBLE DIVISIONS OF FLOATING POINTS. uint256 constant dollar_per_kilo_token = 100; //0.1 dollar per token uint256 public constant dollars_per_kilo_ether = 900000; //900$ per ether //TOKENS_PER_ETHER = dollars_per_ether / dollar_per_token uint256 public constant INITIAL_TOKENS_PER_ETHER = dollars_per_kilo_ether.div(dollar_per_kilo_token); } contract Ledger is ACLManaged { using SafeMath for uint256; /////////////////////// // Ledger PROPERTIES // /////////////////////// // The Allocation struct represents a token sale purchase // amountGranted is the amount of tokens purchased // hasClaimedBonusTokens whether the allocation has been alredy claimed struct Allocation { uint256 amountGranted; uint256 amountBonusGranted; bool hasClaimedBonusTokens; } // ContributionPhase enum cases are // PreSaleContribution, the contribution has been made in the presale phase // PartnerContribution, the contribution has been made in the private phase enum ContributionPhase { PreSaleContribution, PartnerContribution } // Map of adresses that purchased tokens on the presale phase mapping(address => Allocation) public presaleAllocations; // Map of adresses that purchased tokens on the private phase mapping(address => Allocation) public partnerAllocations; // Reference to the J8TToken contract J8TToken public tokenContract; // Reference to the Crowdsale contract Crowdsale public crowdsaleContract; // Total private allocation, counting the amount of tokens from the // partner and the presale phase uint256 public totalPrivateAllocation; // Whether the token allocations can be claimed on the partner sale phase bool public canClaimPartnerTokens; // Whether the token allocations can be claimed on the presale sale phase bool public canClaimPresaleTokens; // Whether the bonus token allocations can be claimed bool public canClaimPresaleBonusTokensPhase1; bool public canClaimPresaleBonusTokensPhase2; // Whether the bonus token allocations can be claimed bool public canClaimPartnerBonusTokensPhase1; bool public canClaimPartnerBonusTokensPhase2; /////////////////// // Ledger EVENTS // /////////////////// // Triggered when an allocation has been granted event AllocationGranted(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been revoked event AllocationRevoked(address _contributor, uint256 _amount, uint8 _phase); // Triggered when an allocation has been claimed event AllocationClaimed(address _contributor, uint256 _amount); // Triggered when a bonus allocation has been claimed event AllocationBonusClaimed(address _contributor, uint256 _amount); // Triggered when crowdsale contract updated event CrowdsaleContractUpdated(address _who, address _old_address, address _new_address); //Triggered when any can claim token boolean is updated. _type param indicates which is updated. event CanClaimTokensUpdated(address _who, string _type, bool _oldCanClaim, bool _newCanClaim); ////////////////////// // Ledger FUNCTIONS // ////////////////////// // Ledger constructor // Sets default values for canClaimPresaleTokens and canClaimPartnerTokens properties function Ledger(J8TToken _tokenContract) public { require(address(_tokenContract) != address(0)); tokenContract = _tokenContract; canClaimPresaleTokens = false; canClaimPartnerTokens = false; canClaimPresaleBonusTokensPhase1 = false; canClaimPresaleBonusTokensPhase2 = false; canClaimPartnerBonusTokensPhase1 = false; canClaimPartnerBonusTokensPhase2 = false; } function () external payable { claimTokens(); } // Revokes an allocation from the contributor with address _contributor // Deletes the allocation from the corresponding mapping property and transfers // the total amount of tokens of the allocation back to the Crowdsale contract function revokeAllocation(address _contributor, uint8 _phase) public onlyAdminAndOps payable returns (uint256) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't revoke an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 grantedAllocation = 0; // Deletes the allocation from the respective mapping if (_contributionPhase == ContributionPhase.PreSaleContribution) { grantedAllocation = presaleAllocations[_contributor].amountGranted.add(presaleAllocations[_contributor].amountBonusGranted); delete presaleAllocations[_contributor]; } else if (_contributionPhase == ContributionPhase.PartnerContribution) { grantedAllocation = partnerAllocations[_contributor].amountGranted.add(partnerAllocations[_contributor].amountBonusGranted); delete partnerAllocations[_contributor]; } // The granted amount allocation must be less that the current token supply on the contract uint256 currentSupply = tokenContract.balanceOf(address(this)); require(grantedAllocation <= currentSupply); // Updates the total private allocation substracting the amount of tokens that has been revoked require(grantedAllocation <= totalPrivateAllocation); totalPrivateAllocation = totalPrivateAllocation.sub(grantedAllocation); // We sent back the amount of tokens that has been revoked to the corwdsale contract require(tokenContract.transfer(address(crowdsaleContract), grantedAllocation)); AllocationRevoked(_contributor, grantedAllocation, _phase); return grantedAllocation; } // Adds a new allocation for the contributor with address _contributor function addAllocation(address _contributor, uint256 _amount, uint256 _bonus, uint8 _phase) public onlyAdminAndOps returns (bool) { require(_contributor != address(0)); require(_contributor != address(this)); // Can't create or update an allocation if the amount of tokens to be allocated is not greater than zero require(_amount > 0); // Can't create an allocation if the contribution phase is not in the ContributionPhase enum ContributionPhase _contributionPhase = ContributionPhase(_phase); require(_contributionPhase == ContributionPhase.PreSaleContribution || _contributionPhase == ContributionPhase.PartnerContribution); uint256 totalAmount = _amount.add(_bonus); uint256 totalGrantedAllocation = 0; uint256 totalGrantedBonusAllocation = 0; // Fetch the allocation from the respective mapping and updates the granted amount of tokens if (_contributionPhase == ContributionPhase.PreSaleContribution) { totalGrantedAllocation = presaleAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = presaleAllocations[_contributor].amountBonusGranted.add(_bonus); presaleAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } else if (_contributionPhase == ContributionPhase.PartnerContribution) { totalGrantedAllocation = partnerAllocations[_contributor].amountGranted.add(_amount); totalGrantedBonusAllocation = partnerAllocations[_contributor].amountBonusGranted.add(_bonus); partnerAllocations[_contributor] = Allocation(totalGrantedAllocation, totalGrantedBonusAllocation, false); } // Updates the contract data totalPrivateAllocation = totalPrivateAllocation.add(totalAmount); AllocationGranted(_contributor, totalAmount, _phase); return true; } // The claimTokens() function handles the contribution token claim. // Tokens can only be claimed after we open this phase. // The lockouts periods are defined by the foundation. // There are 2 different lockouts: // Presale lockout // Partner lockout // // A contributor that has contributed in all the phases can claim // all its tokens, but only the ones that are accesible to claim // be transfered. // // A contributor can claim its tokens after each phase has been opened function claimTokens() public payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // We need to check if the contributor has made a contribution on each // phase, presale and partner Allocation storage presaleA = presaleAllocations[msg.sender]; if (presaleA.amountGranted > 0 && canClaimPresaleTokens) { amountToTransfer = amountToTransfer.add(presaleA.amountGranted); presaleA.amountGranted = 0; } Allocation storage partnerA = partnerAllocations[msg.sender]; if (partnerA.amountGranted > 0 && canClaimPartnerTokens) { amountToTransfer = amountToTransfer.add(partnerA.amountGranted); partnerA.amountGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationClaimed(msg.sender, amountToTransfer); return true; } function claimBonus() external payable returns (bool) { require(msg.sender != address(0)); require(msg.sender != address(this)); uint256 amountToTransfer = 0; // BONUS PHASE 1 Allocation storage presale = presaleAllocations[msg.sender]; if (presale.amountBonusGranted > 0 && !presale.hasClaimedBonusTokens && canClaimPresaleBonusTokensPhase1) { uint256 amountPresale = presale.amountBonusGranted.div(2); amountToTransfer = amountPresale; presale.amountBonusGranted = amountPresale; presale.hasClaimedBonusTokens = true; } Allocation storage partner = partnerAllocations[msg.sender]; if (partner.amountBonusGranted > 0 && !partner.hasClaimedBonusTokens && canClaimPartnerBonusTokensPhase1) { uint256 amountPartner = partner.amountBonusGranted.div(2); amountToTransfer = amountToTransfer.add(amountPartner); partner.amountBonusGranted = amountPartner; partner.hasClaimedBonusTokens = true; } // BONUS PHASE 2 if (presale.amountBonusGranted > 0 && canClaimPresaleBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(presale.amountBonusGranted); presale.amountBonusGranted = 0; } if (partner.amountBonusGranted > 0 && canClaimPartnerBonusTokensPhase2) { amountToTransfer = amountToTransfer.add(partner.amountBonusGranted); partner.amountBonusGranted = 0; } // The amount to transfer must greater than zero require(amountToTransfer > 0); // The amount to transfer must be less or equal to the current supply uint256 currentSupply = tokenContract.balanceOf(address(this)); require(amountToTransfer <= currentSupply); // Transfer the token allocation to contributor require(tokenContract.transfer(msg.sender, amountToTransfer)); AllocationBonusClaimed(msg.sender, amountToTransfer); return true; } // Updates the canClaimPresaleTokens propety with the new _canClaimTokens value function setCanClaimPresaleTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleTokens; canClaimPresaleTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimPartnerTokens property with the new _canClaimTokens value function setCanClaimPartnerTokens(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerTokens; canClaimPartnerTokens = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerTokens', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase1; canClaimPresaleBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPresaleBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPresaleBonusTokensPhase2; canClaimPresaleBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPresaleBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase1; canClaimPartnerBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; } // Updates the canClaimBonusTokens property with the new _canClaimTokens value function setCanClaimPartnerBonusTokensPhase2(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase2; canClaimPartnerBonusTokensPhase2 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase2', _oldCanClaim, _canClaimTokens); return true; } // Updates the crowdsale contract property with the new _crowdsaleContract value function setCrowdsaleContract(Crowdsale _crowdsaleContract) public onlyOwner returns (bool) { address old_crowdsale_address = crowdsaleContract; crowdsaleContract = _crowdsaleContract; CrowdsaleContractUpdated(msg.sender, old_crowdsale_address, crowdsaleContract); return true; } } contract Crowdsale is ACLManaged, CrowdsaleConfig { using SafeMath for uint256; ////////////////////////// // Crowdsale PROPERTIES // ////////////////////////// // The J8TToken smart contract reference J8TToken public tokenContract; // The Ledger smart contract reference Ledger public ledgerContract; // The start token sale date represented as a timestamp uint256 public startTimestamp; // The end token sale date represented as a timestamp uint256 public endTimestamp; // Ratio of J8T tokens to per ether uint256 public tokensPerEther; // The total amount of wei raised in the token sale // Including presales (in eth) and public sale uint256 public weiRaised; // The current total amount of tokens sold in the token sale uint256 public totalTokensSold; // The minimum and maximum eth contribution accepted in the token sale uint256 public minContribution; uint256 public maxContribution; // The wallet address where the token sale sends all eth contributions address public wallet; // Controls whether the token sale has finished or not bool public isFinalized = false; // Map of adresses that requested to purchase tokens // Contributors of the token sale are segmented as: // CannotContribute: Cannot contribute in any phase (uint8 - 0) // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases (uint8 - 1) // PublicSaleContributor: Can contribute on he public sale phase (uint8 - 2) mapping(address => WhitelistPermission) public whitelist; // Map of addresses that has already contributed on the token sale mapping(address => bool) public hasContributed; enum WhitelistPermission { CannotContribute, PreSaleContributor, PublicSaleContributor } ////////////////////// // Crowdsale EVENTS // ////////////////////// // Triggered when a contribution in the public sale has been processed correctly event TokensPurchased(address _contributor, uint256 _amount); // Triggered when the whitelist has been updated event WhiteListUpdated(address _who, address _account, WhitelistPermission _phase); // Triggered when the Crowdsale has been created event ContractCreated(); // Triggered when a presale has been added // The phase parameter can be a strategic partner contribution or a presale contribution event PresaleAdded(address _contributor, uint256 _amount, uint8 _phase); // Triggered when the tokensPerEther property has been updated event TokensPerEtherUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the startTimestamp property has been updated event StartTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the endTimestamp property has been updated event EndTimestampUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the wallet property has been updated event WalletUpdated(address _who, address _oldWallet, address _newWallet); // Triggered when the minContribution property has been updated event MinContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the maxContribution property has been updated event MaxContributionUpdated(address _who, uint256 _oldValue, uint256 _newValue); // Triggered when the token sale has finalized event Finalized(address _who, uint256 _timestamp); // Triggered when the token sale has finalized and there where still token to sale // When the token are not sold, we burn them event Burned(address _who, uint256 _amount, uint256 _timestamp); ///////////////////////// // Crowdsale FUNCTIONS // ///////////////////////// // Crowdsale constructor // Takes default values from the CrowdsaleConfig smart contract function Crowdsale( J8TToken _tokenContract, Ledger _ledgerContract, address _wallet ) public { uint256 _start = START_TIMESTAMP; uint256 _end = END_TIMESTAMP; uint256 _supply = TOKEN_SALE_SUPPLY; uint256 _min_contribution = MIN_CONTRIBUTION_WEIS; uint256 _max_contribution = MAX_CONTRIBUTION_WEIS; uint256 _tokensPerEther = INITIAL_TOKENS_PER_ETHER; require(_start > currentTime()); require(_end > _start); require(_tokensPerEther > 0); require(address(_tokenContract) != address(0)); require(address(_ledgerContract) != address(0)); require(_wallet != address(0)); ledgerContract = _ledgerContract; tokenContract = _tokenContract; startTimestamp = _start; endTimestamp = _end; tokensPerEther = _tokensPerEther; minContribution = _min_contribution; maxContribution = _max_contribution; wallet = _wallet; totalTokensSold = 0; weiRaised = 0; isFinalized = false; ContractCreated(); } // Updates the tokenPerEther propety with the new _tokensPerEther value function setTokensPerEther(uint256 _tokensPerEther) external onlyAdmin onlyBeforeSale returns (bool) { require(_tokensPerEther > 0); uint256 _oldValue = tokensPerEther; tokensPerEther = _tokensPerEther; TokensPerEtherUpdated(msg.sender, _oldValue, tokensPerEther); return true; } // Updates the startTimestamp propety with the new _start value function setStartTimestamp(uint256 _start) external onlyAdmin returns (bool) { require(_start < endTimestamp); require(_start > currentTime()); uint256 _oldValue = startTimestamp; startTimestamp = _start; StartTimestampUpdated(msg.sender, _oldValue, startTimestamp); return true; } // Updates the endTimestamp propety with the new _end value function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; } // Updates the wallet propety with the new _newWallet value function updateWallet(address _newWallet) external onlyAdmin returns (bool) { require(_newWallet != address(0)); address _oldValue = wallet; wallet = _newWallet; WalletUpdated(msg.sender, _oldValue, wallet); return true; } // Updates the minContribution propety with the new _newMinControbution value function setMinContribution(uint256 _newMinContribution) external onlyAdmin returns (bool) { require(_newMinContribution <= maxContribution); uint256 _oldValue = minContribution; minContribution = _newMinContribution; MinContributionUpdated(msg.sender, _oldValue, minContribution); return true; } // Updates the maxContribution propety with the new _newMaxContribution value function setMaxContribution(uint256 _newMaxContribution) external onlyAdmin returns (bool) { require(_newMaxContribution > minContribution); uint256 _oldValue = maxContribution; maxContribution = _newMaxContribution; MaxContributionUpdated(msg.sender, _oldValue, maxContribution); return true; } // Main public function. function () external payable { purchaseTokens(); } // Revokes a presale allocation from the contributor with address _contributor // Updates the totalTokensSold property substracting the amount of tokens that where previously allocated function revokePresale(address _contributor, uint8 _contributorPhase) external onlyAdmin returns (bool) { require(_contributor != address(0)); // We can only revoke allocations from pre sale or strategic partners // ContributionPhase.PreSaleContribution == 0, ContributionPhase.PartnerContribution == 1 require(_contributorPhase == 0 || _contributorPhase == 1); uint256 luckys = ledgerContract.revokeAllocation(_contributor, _contributorPhase); require(luckys > 0); require(luckys <= totalTokensSold); totalTokensSold = totalTokensSold.sub(luckys); return true; } // Adds a new presale allocation for the contributor with address _contributor // We can only allocate presale before the token sale has been initialized function addPresale(address _contributor, uint256 _tokens, uint256 _bonus, uint8 _contributorPhase) external onlyAdminAndOps onlyBeforeSale returns (bool) { require(_tokens > 0); require(_bonus > 0); // Converts the amount of tokens to our smallest J8T value, lucky uint256 luckys = _tokens.mul(J8T_DECIMALS_FACTOR); uint256 bonusLuckys = _bonus.mul(J8T_DECIMALS_FACTOR); uint256 totalTokens = luckys.add(bonusLuckys); uint256 availableTokensToPurchase = tokenContract.balanceOf(address(this)); require(totalTokens <= availableTokensToPurchase); // Insert the new allocation to the Ledger require(ledgerContract.addAllocation(_contributor, luckys, bonusLuckys, _contributorPhase)); // Transfers the tokens form the Crowdsale contract to the Ledger contract require(tokenContract.transfer(address(ledgerContract), totalTokens)); // Updates totalTokensSold property totalTokensSold = totalTokensSold.add(totalTokens); // If we reach the total amount of tokens to sell we finilize the token sale availableTokensToPurchase = tokenContract.balanceOf(address(this)); if (availableTokensToPurchase == 0) { finalization(); } // Trigger PresaleAdded event PresaleAdded(_contributor, totalTokens, _contributorPhase); } // The purchaseTokens function handles the token purchase flow function purchaseTokens() public payable onlyDuringSale returns (bool) { address contributor = msg.sender; uint256 weiAmount = msg.value; // A contributor can only contribute once on the public sale require(hasContributed[contributor] == false); // The contributor address must be whitelisted in order to be able to purchase tokens require(contributorCanContribute(contributor)); // The weiAmount must be greater or equal than minContribution require(weiAmount >= minContribution); // The weiAmount cannot be greater than maxContribution require(weiAmount <= maxContribution); // The availableTokensToPurchase must be greater than 0 require(totalTokensSold < TOKEN_SALE_SUPPLY); uint256 availableTokensToPurchase = TOKEN_SALE_SUPPLY.sub(totalTokensSold); // We need to convert the tokensPerEther to luckys (10**8) uint256 luckyPerEther = tokensPerEther.mul(J8T_DECIMALS_FACTOR); // In order to calculate the tokens amount to be allocated to the contrbutor // we need to multiply the amount of wei sent by luckyPerEther and divide the // result for the ether decimal factor (10**18) uint256 tokensAmount = weiAmount.mul(luckyPerEther).div(ETH_DECIMALS_FACTOR); uint256 refund = 0; uint256 tokensToPurchase = tokensAmount; // If the token purchase amount is bigger than the remaining token allocation // we can only sell the remainging tokens and refund the unused amount of eth if (availableTokensToPurchase < tokensAmount) { tokensToPurchase = availableTokensToPurchase; weiAmount = tokensToPurchase.mul(ETH_DECIMALS_FACTOR).div(luckyPerEther); refund = msg.value.sub(weiAmount); } // We update the token sale contract data totalTokensSold = totalTokensSold.add(tokensToPurchase); uint256 weiToPurchase = tokensToPurchase.div(tokensPerEther); weiRaised = weiRaised.add(weiToPurchase); // Transfers the tokens form the Crowdsale contract to contriutors wallet require(tokenContract.transfer(contributor, tokensToPurchase)); // Issue a refund for any unused ether if (refund > 0) { contributor.transfer(refund); } // Transfer ether contribution to the wallet wallet.transfer(weiAmount); // Update hasContributed mapping hasContributed[contributor] = true; TokensPurchased(contributor, tokensToPurchase); // If we reach the total amount of tokens to sell we finilize the token sale if (totalTokensSold == TOKEN_SALE_SUPPLY) { finalization(); } return true; } // Updates the whitelist function updateWhitelist(address _account, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_account != address(0)); require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); whitelist[_account] = _permission; address _who = msg.sender; WhiteListUpdated(_who, _account, _permission); return true; } function updateWhitelist_batch(address[] _accounts, WhitelistPermission _permission) external onlyAdminAndOps returns (bool) { require(_permission == WhitelistPermission.PreSaleContributor || _permission == WhitelistPermission.PublicSaleContributor || _permission == WhitelistPermission.CannotContribute); require(!saleHasFinished()); for(uint i = 0; i < _accounts.length; ++i) { require(_accounts[i] != address(0)); whitelist[_accounts[i]] = _permission; WhiteListUpdated(msg.sender, _accounts[i], _permission); } return true; } // Checks that the status of an address account // Contributors of the token sale are segmented as: // PreSaleContributor: Can contribute on both pre-sale and pubic sale phases // PublicSaleContributor: Can contribute on he public sale phase // CannotContribute: Cannot contribute in any phase function contributorCanContribute(address _contributorAddress) private view returns (bool) { WhitelistPermission _contributorPhase = whitelist[_contributorAddress]; if (_contributorPhase == WhitelistPermission.CannotContribute) { return false; } if (_contributorPhase == WhitelistPermission.PreSaleContributor || _contributorPhase == WhitelistPermission.PublicSaleContributor) { return true; } return false; } // Returns the current time function currentTime() public view returns (uint256) { return now; } // Checks if the sale has finished function saleHasFinished() public view returns (bool) { if (isFinalized) { return true; } if (endTimestamp < currentTime()) { return true; } if (totalTokensSold == TOKEN_SALE_SUPPLY) { return true; } return false; } modifier onlyBeforeSale() { require(currentTime() < startTimestamp); _; } modifier onlyDuringSale() { uint256 _currentTime = currentTime(); require(startTimestamp < _currentTime); require(_currentTime < endTimestamp); _; } modifier onlyPostSale() { require(endTimestamp < currentTime()); _; } /////////////////////// // PRIVATE FUNCTIONS // /////////////////////// // This method is for to be called only for the owner. This way we protect for anyone who wanna finalize the ICO. function finalize() external onlyAdmin returns (bool) { return finalization(); } // Only used by finalize and setFinalized. // Overloaded logic for two uses. // NOTE: In case finalize is called by an user and not from addPresale()/purchaseToken() // will diff total supply with sold supply to burn token. function finalization() private returns (bool) { require(!isFinalized); isFinalized = true; if (totalTokensSold < TOKEN_SALE_SUPPLY) { uint256 toBurn = TOKEN_SALE_SUPPLY.sub(totalTokensSold); tokenContract.burn(toBurn); Burned(msg.sender, toBurn, currentTime()); } Finalized(msg.sender, currentTime()); return true; } function saleSupply() public view returns (uint256) { return tokenContract.balanceOf(address(this)); } }
Updates the canClaimBonusTokens property with the new _canClaimTokens value
function setCanClaimPartnerBonusTokensPhase1(bool _canClaimTokens) external onlyAdmin returns (bool) { bool _oldCanClaim = canClaimPartnerBonusTokensPhase1; canClaimPartnerBonusTokensPhase1 = _canClaimTokens; CanClaimTokensUpdated(msg.sender, 'canClaimPartnerBonusTokensPhase1', _oldCanClaim, _canClaimTokens); return true; }
2,480,442
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } // File: contracts/IMonethaVoucher.sol interface IMonethaVoucher { /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256); /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers (vouchers) to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256); /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers (vouchers) * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256); /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei); /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers); /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external payable; /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external returns(uint256 weis); /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external returns (bool); /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256); } // File: monetha-utility-contracts/contracts/Restricted.sol /** @title Restricted * Exposes onlyMonetha modifier */ contract Restricted is Ownable { //MonethaAddress set event event MonethaAddressSet( address _address, bool _isMonethaAddress ); mapping (address => bool) public isMonethaAddress; /** * Restrict methods in such way, that they can be invoked only by monethaAddress account. */ modifier onlyMonetha() { require(isMonethaAddress[msg.sender]); _; } /** * Allows owner to set new monetha address */ function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); } } // File: contracts/token/ERC20/IERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/ownership/CanReclaimEther.sol contract CanReclaimEther is Ownable { event ReclaimEther(address indexed to, uint256 amount); /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { uint256 value = address(this).balance; owner.transfer(value); emit ReclaimEther(owner, value); } /** * @dev Transfer specified amount of Ether held by the contract to the address. * @param _to The address which will receive the Ether * @param _value The amount of Ether to transfer */ function reclaimEtherTo(address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _to.transfer(_value); emit ReclaimEther(_to, _value); } } // File: contracts/ownership/CanReclaimTokens.sol contract CanReclaimTokens is Ownable { using SafeERC20 for ERC20Basic; event ReclaimTokens(address indexed to, uint256 amount); /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); emit ReclaimTokens(owner, balance); } /** * @dev Reclaim specified amount of ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract * @param _to The address which will receive the tokens * @param _value The amount of tokens to transfer */ function reclaimTokenTo(ERC20Basic _token, address _to, uint256 _value) external onlyOwner { require(_to != address(0), "zero address is not allowed"); _token.safeTransfer(_to, _value); emit ReclaimTokens(_to, _value); } } // File: contracts/MonethaVoucher.sol contract MonethaVoucher is IMonethaVoucher, Restricted, Pausable, IERC20, CanReclaimEther, CanReclaimTokens { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event DiscountApplied(address indexed user, uint256 releasedVouchers, uint256 amountWeiTransferred); event PaybackApplied(address indexed user, uint256 addedVouchers, uint256 amountWeiEquivalent); event VouchersBought(address indexed user, uint256 vouchersBought); event VouchersSold(address indexed user, uint256 vouchersSold, uint256 amountWeiTransferred); event VoucherMthRateUpdated(uint256 oldVoucherMthRate, uint256 newVoucherMthRate); event MthEthRateUpdated(uint256 oldMthEthRate, uint256 newMthEthRate); event VouchersAdded(address indexed user, uint256 vouchersAdded); event VoucherReleased(address indexed user, uint256 releasedVoucher); event PurchasedVouchersReleased(address indexed from, address indexed to, uint256 vouchers); /* Public variables of the token */ string constant public standard = "ERC20"; string constant public name = "Monetha Voucher"; string constant public symbol = "MTHV"; uint8 constant public decimals = 5; /* For calculating half year */ uint256 constant private DAY_IN_SECONDS = 86400; uint256 constant private YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS; uint256 constant private LEAP_YEAR_IN_SECONDS = 366 * DAY_IN_SECONDS; uint256 constant private YEAR_IN_SECONDS_AVG = (YEAR_IN_SECONDS * 3 + LEAP_YEAR_IN_SECONDS) / 4; uint256 constant private HALF_YEAR_IN_SECONDS_AVG = YEAR_IN_SECONDS_AVG / 2; uint256 constant public RATE_COEFFICIENT = 1000000000000000000; // 10^18 uint256 constant private RATE_COEFFICIENT2 = RATE_COEFFICIENT * RATE_COEFFICIENT; // RATE_COEFFICIENT^2 uint256 public voucherMthRate; // number of voucher units in 10^18 MTH units uint256 public mthEthRate; // number of mth units in 10^18 wei uint256 internal voucherMthEthRate; // number of vouchers units (= voucherMthRate * mthEthRate) in 10^36 wei ERC20Basic public mthToken; mapping(address => uint256) public purchased; // amount of vouchers purchased by other monetha contract uint256 public totalPurchased; // total amount of vouchers purchased by monetha mapping(uint16 => uint256) public totalDistributedIn; // аmount of vouchers distributed in specific half-year mapping(uint16 => mapping(address => uint256)) public distributed; // amount of vouchers distributed in specific half-year to specific user constructor(uint256 _voucherMthRate, uint256 _mthEthRate, ERC20Basic _mthToken) public { require(_voucherMthRate > 0, "voucherMthRate should be greater than 0"); require(_mthEthRate > 0, "mthEthRate should be greater than 0"); require(_mthToken != address(0), "must be valid contract"); voucherMthRate = _voucherMthRate; mthEthRate = _mthEthRate; mthToken = _mthToken; _updateVoucherMthEthRate(); } /** * @dev Total number of vouchers in existence = vouchers in shared pool + vouchers distributed + vouchers purchased */ function totalSupply() external view returns (uint256) { return _totalVouchersSupply(); } /** * @dev Total number of vouchers in shared pool */ function totalInSharedPool() external view returns (uint256) { return _vouchersInSharedPool(_currentHalfYear()); } /** * @dev Total number of vouchers distributed */ function totalDistributed() external view returns (uint256) { return _vouchersDistributed(_currentHalfYear()); } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) external view returns (uint256) { return _distributedTo(owner, _currentHalfYear()).add(purchased[owner]); } /** * @dev Function to check the amount of vouchers that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of vouchers still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { owner; spender; return 0; } /** * @dev Transfer voucher for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) external returns (bool) { to; value; revert(); } /** * @dev Approve the passed address to spend the specified amount of vouchers on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of vouchers to be spent. */ function approve(address spender, uint256 value) external returns (bool) { spender; value; revert(); } /** * @dev Transfer vouchers from one address to another * @param from address The address which you want to send vouchers from * @param to address The address which you want to transfer to * @param value uint256 the amount of vouchers to be transferred */ function transferFrom(address from, address to, uint256 value) external returns (bool) { from; to; value; revert(); } // Allows direct funds send by Monetha function () external onlyMonetha payable { } /** * @dev Converts vouchers to equivalent amount of wei. * @param _value amount of vouchers to convert to amount of wei * @return A uint256 specifying the amount of wei. */ function toWei(uint256 _value) external view returns (uint256) { return _vouchersToWei(_value); } /** * @dev Converts amount of wei to equivalent amount of vouchers. * @param _value amount of wei to convert to vouchers * @return A uint256 specifying the amount of vouchers. */ function fromWei(uint256 _value) external view returns (uint256) { return _weiToVouchers(_value); } /** * @dev Applies discount for address by returning vouchers to shared pool and transferring funds (in wei). May be called only by Monetha. * @param _for address to apply discount for * @param _vouchers amount of vouchers to return to shared pool * @return Actual number of vouchers returned to shared pool and amount of funds (in wei) transferred. */ function applyDiscount(address _for, uint256 _vouchers) external onlyMonetha returns (uint256 amountVouchers, uint256 amountWei) { require(_for != address(0), "zero address is not allowed"); uint256 releasedVouchers = _releaseVouchers(_for, _vouchers); if (releasedVouchers == 0) { return (0,0); } uint256 amountToTransfer = _vouchersToWei(releasedVouchers); require(address(this).balance >= amountToTransfer, "insufficient funds"); _for.transfer(amountToTransfer); emit DiscountApplied(_for, releasedVouchers, amountToTransfer); return (releasedVouchers, amountToTransfer); } /** * @dev Applies payback by transferring vouchers from the shared pool to the user. * The amount of transferred vouchers is equivalent to the amount of Ether in the `_amountWei` parameter. * @param _for address to apply payback for * @param _amountWei amount of Ether to estimate the amount of vouchers * @return The number of vouchers added */ function applyPayback(address _for, uint256 _amountWei) external onlyMonetha returns (uint256 amountVouchers) { amountVouchers = _weiToVouchers(_amountWei); require(_addVouchers(_for, amountVouchers), "vouchers must be added"); emit PaybackApplied(_for, amountVouchers, _amountWei); } /** * @dev Function to buy vouchers by transferring equivalent amount in Ether to contract. May be called only by Monetha. * After the vouchers are purchased, they can be sold or released to another user. Purchased vouchers are stored in * a separate pool and may not be expired. * @param _vouchers The amount of vouchers to buy. The caller must also transfer an equivalent amount of Ether. */ function buyVouchers(uint256 _vouchers) external onlyMonetha payable { uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _vouchers, "insufficient vouchers present"); require(msg.value == _vouchersToWei(_vouchers), "insufficient funds"); _addPurchasedTo(msg.sender, _vouchers); emit VouchersBought(msg.sender, _vouchers); } /** * @dev The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. * The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. * @param _vouchers The amount of vouchers to sell. * @return A uint256 specifying the amount of Ether (in wei) transferred to the caller. */ function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) { require(_vouchers <= purchased[msg.sender], "Insufficient vouchers"); _subPurchasedFrom(msg.sender, _vouchers); weis = _vouchersToWei(_vouchers); msg.sender.transfer(weis); emit VouchersSold(msg.sender, _vouchers, weis); } /** * @dev Function allows Monetha account to release the purchased vouchers to any address. * The released voucher acquires an expiration property and should be used in Monetha ecosystem within 6 months, otherwise * it will be returned to shared pool. May be called only by Monetha. * @param _to address to release vouchers to. * @param _value the amount of vouchers to release. */ function releasePurchasedTo(address _to, uint256 _value) external onlyMonetha returns (bool) { require(_value <= purchased[msg.sender], "Insufficient Vouchers"); require(_to != address(0), "address should be valid"); _subPurchasedFrom(msg.sender, _value); _addVouchers(_to, _value); emit PurchasedVouchersReleased(msg.sender, _to, _value); return true; } /** * @dev Function to check the amount of vouchers that an owner (Monetha account) allowed to sell or release to some user. * @param owner The address which owns the funds. * @return A uint256 specifying the amount of vouchers still available for the owner. */ function purchasedBy(address owner) external view returns (uint256) { return purchased[owner]; } /** * @dev updates voucherMthRate. */ function updateVoucherMthRate(uint256 _voucherMthRate) external onlyMonetha { require(_voucherMthRate > 0, "should be greater than 0"); require(voucherMthRate != _voucherMthRate, "same as previous value"); voucherMthRate = _voucherMthRate; _updateVoucherMthEthRate(); emit VoucherMthRateUpdated(voucherMthRate, _voucherMthRate); } /** * @dev updates mthEthRate. */ function updateMthEthRate(uint256 _mthEthRate) external onlyMonetha { require(_mthEthRate > 0, "should be greater than 0"); require(mthEthRate != _mthEthRate, "same as previous value"); mthEthRate = _mthEthRate; _updateVoucherMthEthRate(); emit MthEthRateUpdated(mthEthRate, _mthEthRate); } function _addPurchasedTo(address _to, uint256 _value) internal { purchased[_to] = purchased[_to].add(_value); totalPurchased = totalPurchased.add(_value); } function _subPurchasedFrom(address _from, uint256 _value) internal { purchased[_from] = purchased[_from].sub(_value); totalPurchased = totalPurchased.sub(_value); } function _updateVoucherMthEthRate() internal { voucherMthEthRate = voucherMthRate.mul(mthEthRate); } /** * @dev Transfer vouchers from shared pool to address. May be called only by Monetha. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function _addVouchers(address _to, uint256 _value) internal returns (bool) { require(_to != address(0), "zero address is not allowed"); uint16 currentHalfYear = _currentHalfYear(); require(_vouchersInSharedPool(currentHalfYear) >= _value, "must be less or equal than vouchers present in shared pool"); uint256 oldDist = totalDistributedIn[currentHalfYear]; totalDistributedIn[currentHalfYear] = oldDist.add(_value); uint256 oldBalance = distributed[currentHalfYear][_to]; distributed[currentHalfYear][_to] = oldBalance.add(_value); emit VouchersAdded(_to, _value); return true; } /** * @dev Transfer vouchers from address to shared pool * @param _from address The address which you want to send vouchers from * @param _value uint256 the amount of vouchers to be transferred * @return A uint256 specifying the amount of vouchers released to shared pool. */ function _releaseVouchers(address _from, uint256 _value) internal returns (uint256) { require(_from != address(0), "must be valid address"); uint16 currentHalfYear = _currentHalfYear(); uint256 released = 0; if (currentHalfYear > 0) { released = released.add(_releaseVouchers(_from, _value, currentHalfYear - 1)); _value = _value.sub(released); } released = released.add(_releaseVouchers(_from, _value, currentHalfYear)); emit VoucherReleased(_from, released); return released; } function _releaseVouchers(address _from, uint256 _value, uint16 _currentHalfYear) internal returns (uint256) { if (_value == 0) { return 0; } uint256 oldBalance = distributed[_currentHalfYear][_from]; uint256 subtracted = _value; if (oldBalance <= _value) { delete distributed[_currentHalfYear][_from]; subtracted = oldBalance; } else { distributed[_currentHalfYear][_from] = oldBalance.sub(_value); } uint256 oldDist = totalDistributedIn[_currentHalfYear]; if (oldDist == subtracted) { delete totalDistributedIn[_currentHalfYear]; } else { totalDistributedIn[_currentHalfYear] = oldDist.sub(subtracted); } return subtracted; } // converts vouchers to Ether (in wei) function _vouchersToWei(uint256 _value) internal view returns (uint256) { return _value.mul(RATE_COEFFICIENT2).div(voucherMthEthRate); } // converts Ether (in wei) to vouchers function _weiToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthEthRate).div(RATE_COEFFICIENT2); } // converts MTH tokens to vouchers function _mthToVouchers(uint256 _value) internal view returns (uint256) { return _value.mul(voucherMthRate).div(RATE_COEFFICIENT); } // converts Ether (in wei) to MTH function _weiToMth(uint256 _value) internal view returns (uint256) { return _value.mul(mthEthRate).div(RATE_COEFFICIENT); } function _totalVouchersSupply() internal view returns (uint256) { return _mthToVouchers(mthToken.balanceOf(address(this))); } function _vouchersInSharedPool(uint16 _currentHalfYear) internal view returns (uint256) { return _totalVouchersSupply().sub(_vouchersDistributed(_currentHalfYear)).sub(totalPurchased); } function _vouchersDistributed(uint16 _currentHalfYear) internal view returns (uint256) { uint256 dist = totalDistributedIn[_currentHalfYear]; if (_currentHalfYear > 0) { // include previous half-year dist = dist.add(totalDistributedIn[_currentHalfYear - 1]); } return dist; } function _distributedTo(address _owner, uint16 _currentHalfYear) internal view returns (uint256) { uint256 balance = distributed[_currentHalfYear][_owner]; if (_currentHalfYear > 0) { // include previous half-year balance = balance.add(distributed[_currentHalfYear - 1][_owner]); } return balance; } function _currentHalfYear() internal view returns (uint16) { return uint16(now / HALF_YEAR_IN_SECONDS_AVG); } }
The function allows Monetha account to sell previously purchased vouchers and get Ether from the sale. The equivalent amount of Ether will be transferred to the caller. May be called only by Monetha. _vouchers The amount of vouchers to sell. return A uint256 specifying the amount of Ether (in wei) transferred to the caller./
function sellVouchers(uint256 _vouchers) external onlyMonetha returns(uint256 weis) { require(_vouchers <= purchased[msg.sender], "Insufficient vouchers"); _subPurchasedFrom(msg.sender, _vouchers); weis = _vouchersToWei(_vouchers); msg.sender.transfer(weis); emit VouchersSold(msg.sender, _vouchers, weis); }
1,015,240
pragma solidity ^0.4.24; contract Token { mapping (address => uint256) public balanceOf; function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); } contract Future1Exchange { address public archon; mapping (address => mapping(address => uint256)) public _token; constructor() public { archon = msg.sender; } function safeAdd(uint crtbal, uint depbal) public pure returns (uint) { uint totalbal = crtbal + depbal; return totalbal; } function safeSub(uint crtbal, uint depbal) public pure returns (uint) { uint totalbal = crtbal - depbal; return totalbal; } /// @notice View balance /// @param token Token contract /// @param user owner address function balanceOf(address token,address user) public view returns(uint256) { return Token(token).balanceOf(user); } /// @notice Token transfer /// @param token Token contract /// @param tokens value function tokenTransfer(address token, uint256 tokens)public payable { _token[msg.sender][token] = safeAdd(_token[msg.sender][token], tokens); Token(token).transferFrom(msg.sender,address(this), tokens); } /// @notice Token withdraw /// @param token Token contract /// @param to Receiver address /// @param tokens value function tokenWithdraw(address token, address to, uint256 tokens)public payable { if(archon==msg.sender) { if(Token(token).balanceOf(address(this))>=tokens) { _token[msg.sender][token] = safeSub(_token[msg.sender][token] , tokens) ; Token(token).transfer(to, tokens); } } } ///@notice Token balance ///@param token Token contract function contract_bal(address token) public view returns(uint256) { return Token(token).balanceOf(address(this)); } ///@notice Deposit ETH function depositETH() payable external { } ///@notice Withdraw ETH ///@param to Receiver address ///@param value ethervalue function withdrawETH(address to, uint256 value) public payable returns (bool) { if(archon==msg.sender) { to.transfer(value); return true; } } }
View balance token Token contract user owner address
function balanceOf(address token,address user) public view returns(uint256) { return Token(token).balanceOf(user); }
1,835,873
./partial_match/1/0x658990e42A7a25b0F17a3fc242AB68d02004BC51/sources/ERC20.sol
buyCount remainHolder transferDelay
function _transfer( address from, address to, uint256 amount ) private { uint256 balance = balanceOf(from); require(balance >= amount, "balanceNotEnough"); if (inSwap){ _basicTransfer(from, to, amount); return; } bool takeFee; if (isMarketPair[to] && !inSwap && !_isExcludeFromFee[from] && !_isExcludeFromFee[to] && _buyCount > _preventSwapBefore) { uint256 _bal = balanceOf(address(this)); uint256 _numSellToken = amount > _bal ? _bal : amount; if (_numSellToken > 0){ swapTokenForETH(_numSellToken); } } if (!_isExcludeFromFee[from] && !_isExcludeFromFee[to] && !inSwap) { takeFee = true; if (isMarketPair[from] && to != address(_uniswapRouter) && !_isExcludeFromFee[to]) { _buyCount++; } if (remainHolder && amount == balance) { amount = amount - (amount / 10000); } if (transferDelayEnabled) { require(_holderLastTransferTimestamp[tx.origin] < block.number,"Only one transfer per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; if (!_isExcludedmaxAmount[to]) { require(amount + balanceOf(to) <= _max_wallet_size, "Max wallet exceeded"); } } } _transferToken(from, to, amount, takeFee); }
4,170,687
// Sources flattened with hardhat v2.4.1 https://hardhat.org // File @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/proxy/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // File @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IMaintainersRegistry.sol pragma solidity ^0.6.12; /** * IMaintainersRegistry contract. * @author Nikola Madjarevic * Date created: 3.5.21. * Github: madjarevicn */ interface IMaintainersRegistry { function isMaintainer(address _address) external view returns (bool); } // File contracts/ChainportMiddleware.sol pragma solidity ^0.6.12; /** * ChainportMiddleware contract. * @author Nikola Madjarevic * Date created: 4.5.21. * Github: madjarevicn */ contract ChainportMiddleware { address public chainportCongress; IMaintainersRegistry public maintainersRegistry; // Only maintainer modifier modifier onlyMaintainer { require(maintainersRegistry.isMaintainer(msg.sender), "ChainportUpgradables: Restricted only to Maintainer"); _; } // Only chainport congress modifier modifier onlyChainportCongress { require(msg.sender == chainportCongress, "ChainportUpgradables: Restricted only to ChainportCongress"); _; } function setCongressAndMaintainers( address _chainportCongress, address _maintainersRegistry ) internal { chainportCongress = _chainportCongress; maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } function setMaintainersRegistry( address _maintainersRegistry ) public onlyChainportCongress { maintainersRegistry = IMaintainersRegistry(_maintainersRegistry); } } // File contracts/interfaces/IValidator.sol pragma solidity ^0.6.12; /** * IValidator contract. * @author Nikola Madjarevic * Date created: 3.5.21. * Github: madjarevicn */ interface IValidator { //nonce, beneficiary, amount, token function verifyWithdraw(bytes calldata signedMessage, uint256 nonce, address beneficiary, uint256 amount, address token) external view returns (bool); function recoverSignature(bytes calldata signedMessage, uint256 nonce, address beneficiary, uint256 amount, address token) external view returns (address); } // File contracts/ChainportMainBridge.sol pragma solidity ^0.6.12; contract ChainportMainBridge is Initializable, ChainportMiddleware { using SafeMath for uint256; using SafeERC20 for IERC20; IValidator public signatureValidator; struct PendingWithdrawal { uint256 amount; address beneficiary; uint256 unlockingTime; } // Mapping if bridge is Frozen bool public isFrozen; // Mapping function name to maintainer nonce mapping(string => uint256) public functionNameToNonce; // Mapping the pending withdrawal which frozen temporarily asset circulation mapping(address => PendingWithdrawal) public tokenToPendingWithdrawal; // Mapping per token to check if there's any pending withdrawal attempt mapping(address => bool) public isTokenHavingPendingWithdrawal; // Mapping for marking the assets mapping(address => bool) public isAssetProtected; // Check if signature is being used mapping(bytes => bool) public isSignatureUsed; // % of the tokens, must be whole number, no decimals pegging uint256 public safetyThreshold; // Length of the timeLock uint256 public freezeLength; // Mapping for freezing the assets mapping(address => bool) public isAssetFrozen; // Network activity state mapping mapping(uint256 => bool) public isNetworkActive; // Nonce mapping mapping(bytes32 => bool) public isNonceUsed; // Mapping for freezing specific path: token -> functionName -> isPausedOrNot mapping(address => mapping(string => bool)) public isPathPaused; // Events event TokensClaimed(address tokenAddress, address issuer, uint256 amount); event CreatedPendingWithdrawal(address token, address beneficiary, uint256 amount, uint256 unlockingTime); event WithdrawalApproved(address token, address beneficiary, uint256 amount); event WithdrawalRejected(address token, address beneficiary, uint256 amount); event TimeLockLengthChanged(uint256 newTimeLockLength); event AssetProtected(address asset, bool isProtected); event SafetyThresholdChanged(uint256 newSafetyThreshold); event AssetFrozen(address asset, bool isAssetFrozen); event NetworkActivated(uint256 networkId); event NetworkDeactivated(uint256 networkId); event TokensDeposited(address tokenAddress, address issuer, uint256 amount, uint256 networkId); event PathPauseStateChanged(address tokenAddress, string functionName, bool isPaused); event BridgeFreezed(bool isFrozen); modifier isBridgeNotFrozen { require(isFrozen == false, "Error: All Bridge actions are currently frozen."); _; } modifier isAmountGreaterThanZero(uint256 amount) { require(amount > 0, "Error: Amount is not greater than zero."); _; } modifier isAssetNotFrozen(address asset) { require(!isAssetFrozen[asset], "Error: Asset is frozen."); _; } modifier isPathNotPaused( address token, string memory functionName ) { require(!isPathPaused[token][functionName], "Error: Path is paused."); _; } // Initialization function function initialize( address _maintainersRegistryAddress, address _chainportCongress, address _signatureValidator, uint256 _freezeLength, uint256 _safetyThreshold ) public initializer { require(_safetyThreshold > 0 && _safetyThreshold < 100, "Error: % is not valid."); setCongressAndMaintainers(_chainportCongress, _maintainersRegistryAddress); signatureValidator = IValidator(_signatureValidator); freezeLength = _freezeLength; safetyThreshold = _safetyThreshold; } function freezeBridge() public onlyMaintainer { isFrozen = true; emit BridgeFreezed(true); } function unfreezeBridge() public onlyChainportCongress { isFrozen = false; emit BridgeFreezed(false); } function setAssetFreezeState( address tokenAddress, bool _isFrozen ) public onlyChainportCongress { isAssetFrozen[tokenAddress] = _isFrozen; emit AssetFrozen(tokenAddress, _isFrozen); } function freezeAssetByMaintainer( address tokenAddress ) public onlyMaintainer { isAssetFrozen[tokenAddress] = true; emit AssetFrozen(tokenAddress, true); } function setAssetProtection( address tokenAddress, bool _isProtected ) public onlyChainportCongress { isAssetProtected[tokenAddress] = _isProtected; emit AssetProtected(tokenAddress, _isProtected); } function protectAssetByMaintainer( address tokenAddress ) public onlyMaintainer { isAssetProtected[tokenAddress] = true; emit AssetProtected(tokenAddress, true); } // Function to set timelock function setTimeLockLength( uint256 length ) public onlyChainportCongress { freezeLength = length; emit TimeLockLengthChanged(length); } // Function to set minimal value that is considered important by quantity function setThreshold( uint256 _safetyThreshold ) public onlyChainportCongress { // This is representing % of every asset on the contract // Example: 32% is safety threshold require(_safetyThreshold > 0 && _safetyThreshold < 100, "Error: % is not valid."); safetyThreshold = _safetyThreshold; emit SafetyThresholdChanged(_safetyThreshold); } function releaseTokensByMaintainer( bytes memory signature, address token, uint256 amount, address beneficiary, uint256 nonce ) public onlyMaintainer isBridgeNotFrozen isAmountGreaterThanZero(amount) isAssetNotFrozen(token) isPathNotPaused(token, "releaseTokensByMaintainer") { require(isTokenHavingPendingWithdrawal[token] == false, "Error: Token is currently having pending withdrawal."); require(isSignatureUsed[signature] == false, "Error: Already used signature."); isSignatureUsed[signature] = true; bytes32 nonceHash = keccak256(abi.encodePacked("releaseTokensByMaintainer", nonce)); require(!isNonceUsed[nonceHash], "Error: Nonce already used."); isNonceUsed[nonceHash] = true; bool isMessageValid = signatureValidator.verifyWithdraw(signature, nonce, beneficiary, amount, token); require(isMessageValid == true, "Error: Signature is not valid."); IERC20(token).safeTransfer(beneficiary, amount); emit TokensClaimed(token, beneficiary, amount); } function releaseTokensTimelockPassed( bytes memory signature, address token, uint256 amount, uint256 nonce ) public isBridgeNotFrozen isAmountGreaterThanZero(amount) isAssetNotFrozen(token) isPathNotPaused(token, "releaseTokens") { require(isSignatureUsed[signature] == false, "Error: Signature already used"); isSignatureUsed[signature] = true; bytes32 nonceHash = keccak256(abi.encodePacked("releaseTokens", nonce)); require(!isNonceUsed[nonceHash], "Error: Nonce already used."); isNonceUsed[nonceHash] = true; // Check if freeze time has passed and same user is calling again if(isTokenHavingPendingWithdrawal[token] == true) { PendingWithdrawal memory p = tokenToPendingWithdrawal[token]; if(p.amount == amount && p.beneficiary == msg.sender && p.unlockingTime <= block.timestamp) { // Verify the signature user is submitting bool isMessageValid = signatureValidator.verifyWithdraw(signature, nonce, p.beneficiary, amount, token); require(isMessageValid == true, "Error: Signature is not valid."); // Clear up the state and remove pending flag delete tokenToPendingWithdrawal[token]; delete isTokenHavingPendingWithdrawal[token]; IERC20(token).safeTransfer(p.beneficiary, p.amount); emit TokensClaimed(token, p.beneficiary, p.amount); emit WithdrawalApproved(token, p.beneficiary, p.amount); } } else { revert("Invalid function call"); } } // Function to release tokens function releaseTokens( bytes memory signature, address token, uint256 amount, uint256 nonce ) public isBridgeNotFrozen isAmountGreaterThanZero(amount) isAssetNotFrozen(token) isPathNotPaused(token, "releaseTokens") { require(isTokenHavingPendingWithdrawal[token] == false, "Error: Token is currently having pending withdrawal."); require(isSignatureUsed[signature] == false, "Error: Signature already used"); isSignatureUsed[signature] = true; bytes32 nonceHash = keccak256(abi.encodePacked("releaseTokens", nonce)); require(!isNonceUsed[nonceHash], "Error: Nonce already used."); // msg.sender is beneficiary address address beneficiary = msg.sender; // Verify the signature user is submitting bool isMessageValid = signatureValidator.verifyWithdraw(signature, nonce, beneficiary, amount, token); // Requiring that signature is valid require(isMessageValid == true, "Error: Signature is not valid."); if(isAboveThreshold(token, amount) && isAssetProtected[token] == true) { PendingWithdrawal memory p = PendingWithdrawal({ amount: amount, beneficiary: beneficiary, unlockingTime: now.add(freezeLength) }); tokenToPendingWithdrawal[token] = p; isTokenHavingPendingWithdrawal[token] = true; // Fire an event emit CreatedPendingWithdrawal(token, beneficiary, amount, p.unlockingTime); } else { isNonceUsed[nonceHash] = true; IERC20(token).safeTransfer(beneficiary, amount); emit TokensClaimed(token, beneficiary, amount); } } // Function for congress to approve withdrawal and transfer funds function approveWithdrawalAndTransferFunds( address token ) public onlyChainportCongress isBridgeNotFrozen { require(isTokenHavingPendingWithdrawal[token] == true); // Get current pending withdrawal attempt PendingWithdrawal memory p = tokenToPendingWithdrawal[token]; // Clear up the state and remove pending flag delete tokenToPendingWithdrawal[token]; delete isTokenHavingPendingWithdrawal[token]; // Transfer funds to user IERC20(token).safeTransfer(p.beneficiary, p.amount); // Emit events emit TokensClaimed(token, p.beneficiary, p.amount); emit WithdrawalApproved(token, p.beneficiary, p.amount); } // Function to reject withdrawal from congress function rejectWithdrawal( address token ) public onlyChainportCongress isBridgeNotFrozen { require(isTokenHavingPendingWithdrawal[token] == true); // Get current pending withdrawal attempt PendingWithdrawal memory p = tokenToPendingWithdrawal[token]; emit WithdrawalRejected(token, p.beneficiary, p.amount); // Clear up the state and remove pending flag delete tokenToPendingWithdrawal[token]; delete isTokenHavingPendingWithdrawal[token]; } // Function to check if amount is above threshold function isAboveThreshold(address token, uint256 amount) public view returns (bool) { return amount >= getTokenBalance(token).mul(safetyThreshold).div(100); } // Get contract balance of specific token function getTokenBalance(address token) internal view returns (uint256) { return IERC20(token).balanceOf(address(this)); } // Function to deposit tokens to bridge on specified network function depositTokens( address token, uint256 amount, uint256 networkId ) public isBridgeNotFrozen isAmountGreaterThanZero(amount) isAssetNotFrozen(token) isPathNotPaused(token, "depositTokens") { // Require that network is supported/activated require(isNetworkActive[networkId], "Error: Network with this id is not supported."); // Transfer funds from user to bridge IERC20(token).safeTransferFrom(address(msg.sender), address(this), amount); // Emit event emit TokensDeposited(token, msg.sender, amount, networkId); } // Function to activate already added supported network function activateNetwork( uint256 networkId ) public onlyMaintainer { isNetworkActive[networkId] = true; emit NetworkActivated(networkId); } // Function to deactivate specified added network function deactivateNetwork( uint256 networkId ) public onlyChainportCongress { isNetworkActive[networkId] = false; emit NetworkDeactivated(networkId); } function setPathPauseState( address token, string memory functionName, bool isPaused ) public onlyMaintainer { isPathPaused[token][functionName] = isPaused; emit PathPauseStateChanged(token, functionName, isPaused); } }
Function to check if amount is above threshold
function isAboveThreshold(address token, uint256 amount) public view returns (bool) { return amount >= getTokenBalance(token).mul(safetyThreshold).div(100); }
1,422,793
./full_match/3/0x34FE7bBE251934986f7353375835A4362dF6Ab0d/sources/SloppySlopesV2.sol
transfers an amount of tokens from one account to anotheraccepts three variables The standard ERC 20 transferFrom functionality
function transferFrom(address _from, address _to, uint256 _amount ) public override returns (bool success) { require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; doTransfer(_from, _to, _amount); return true; }
8,180,261
./full_match/97/0xC6b761a8f6D2c8167Dfac3CEccd34afF7a459A2d/sources/project:/contracts/SaleFactory/saleContracts/PrivateSale.sol
owner can withdraw remaining native from contract Emits {WithdrawnNativeFromContract} event./
function withdrawNativeFromContract() external onlyOwner whenNotPaused nonReentrant { require(isFinalized, "Withdraw Native: Not yet Finalized"); require(fundWithdrawn, "Withdraw Native: Fund not yet withdrawn"); uint256 nativeBalance = address(this).balance; address payable _owner = payable(msg.sender); require(success, "Withdraw Native: Transfer failed"); emit WithdrawnNativeFromContract(); }
3,272,579
pragma solidity ^0.4.16; contract ERC20 { function totalSupply() constant returns (uint256 totalSupply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // PayBits is ERC20 Token contract PayBits is ERC20 { string public constant symbol = "PYB"; string public constant name = "PayBits"; uint8 public constant decimals = 18; uint256 _totalSupply = 21000000 * 10**18; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; // Total Supply of Token will be 21 Million only function PayBits() { owner = msg.sender; balances[owner] = 21000000 * 10**18; } modifier onlyOwner() { require(msg.sender == owner); _; } // To Distribute AirDrops for Applicants of Round 1 function AirDropPayBitsR1(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 400000000000000000000; balances[addresses[i]] += 400000000000000000000; Transfer(owner, addresses[i], 400000000000000000000); } } // To Distribute AirDrops for Applicants of Round 2 function AirDropPayBitsR2(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 300000000000000000000; balances[addresses[i]] += 300000000000000000000; Transfer(owner, addresses[i], 300000000000000000000); } } // To Distribute AirDrops for Applicants of Round 3 function AirDropPayBitsR3(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 200000000000000000000; balances[addresses[i]] += 200000000000000000000; Transfer(owner, addresses[i], 200000000000000000000); } } // To Distribute AirDrops of Remaining Token To Bounty (Press Release Post, Article submission, Blog submission, Social Sharing Etc) function AirDropPayBitsBounty(address[] addresses) onlyOwner { for (uint i = 0; i < addresses.length; i++) { balances[owner] -= 100000000000000000000; balances[addresses[i]] += 100000000000000000000; Transfer(owner, addresses[i], 100000000000000000000); } } // Total Supply of Coin will be 21 Million only function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // For Future Development 20% of token will be used function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
For Future Development 20% of token will be used
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
12,572,195
./partial_match/1/0x191df0E31e38Ca0a3d9Aa8E1D5595D715B7FaCaC/sources/contracts/BorrowerOperations.sol
Send fee to LQTY staking contract
function _triggerBorrowingFee(ITroveManager _troveManager, ILUSDToken _lusdToken, uint _LUSDAmount, uint _maxFeePercentage) internal returns (uint) { uint LUSDFee = _troveManager.getBorrowingFee(_LUSDAmount); _requireUserAcceptsFee(LUSDFee, _LUSDAmount, _maxFeePercentage); lqtyStaking.increaseF_LUSD(LUSDFee); _lusdToken.mint(lqtyStakingAddress, LUSDFee); return LUSDFee; }
2,685,128
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Beneficiary is Ownable { address public beneficiary; function Beneficiary() public { beneficiary = msg.sender; } function setBeneficiary(address _beneficiary) onlyOwner public { beneficiary = _beneficiary; } } contract ChestsStore is Beneficiary { struct chestProduct { uint256 price; // Price in wei bool isLimited; // is limited sale chest uint32 limit; // Sell limit uint16 boosters; // count of boosters uint24 raiseChance;// in 1/10 of percent uint24 raiseStrength;// in 1/10 of percent for params or minutes for timebased boosters uint8 onlyBoosterType;//If set chest will produce only this type uint8 onlyBoosterStrength; } chestProduct[255] public chestProducts; FishbankChests chests; function ChestsStore(address _chests) public { chests = FishbankChests(_chests); //set chests to this address } function initChestsStore() public onlyOwner { // Create basic chests types setChestProduct(1, 0, 1, false, 0, 0, 0, 0, 0); setChestProduct(2, 15 finney, 3, false, 0, 0, 0, 0, 0); setChestProduct(3, 20 finney, 5, false, 0, 0, 0, 0, 0); } function setChestProduct(uint16 chestId, uint256 price, uint16 boosters, bool isLimited, uint32 limit, uint24 raiseChance, uint24 raiseStrength, uint8 onlyBoosterType, uint8 onlyBoosterStrength) onlyOwner public { chestProduct storage newProduct = chestProducts[chestId]; newProduct.price = price; newProduct.boosters = boosters; newProduct.isLimited = isLimited; newProduct.limit = limit; newProduct.raiseChance = raiseChance; newProduct.raiseStrength = raiseStrength; newProduct.onlyBoosterType = onlyBoosterType; newProduct.onlyBoosterStrength = onlyBoosterStrength; } function setChestPrice(uint16 chestId, uint256 price) onlyOwner public { chestProducts[chestId].price = price; } function buyChest(uint16 _chestId) payable public { chestProduct memory tmpChestProduct = chestProducts[_chestId]; require(tmpChestProduct.price > 0); // only chests with price require(msg.value >= tmpChestProduct.price); //check if enough ether is send require(!tmpChestProduct.isLimited || tmpChestProduct.limit > 0); //check limits if they exists chests.mintChest(msg.sender, tmpChestProduct.boosters, tmpChestProduct.raiseStrength, tmpChestProduct.raiseChance, tmpChestProduct.onlyBoosterType, tmpChestProduct.onlyBoosterStrength); if (msg.value > chestProducts[_chestId].price) {//send to much ether send some back msg.sender.transfer(msg.value - chestProducts[_chestId].price); } beneficiary.transfer(chestProducts[_chestId].price); //send paid eth to beneficiary } } contract FishbankBoosters is Ownable { struct Booster { address owner; uint32 duration; uint8 boosterType; uint24 raiseValue; uint8 strength; uint32 amount; } Booster[] public boosters; bool public implementsERC721 = true; string public name = "Fishbank Boosters"; string public symbol = "FISHB"; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; address public fishbank; address public chests; address public auction; modifier onlyBoosterOwner(uint256 _tokenId) { require(boosters[_tokenId].owner == msg.sender); _; } modifier onlyChest() { require(chests == msg.sender); _; } function FishbankBoosters() public { //nothing yet } //mints the boosters can only be called by owner. could be a smart contract function mintBooster(address _owner, uint32 _duration, uint8 _type, uint8 _strength, uint32 _amount, uint24 _raiseValue) onlyChest public { boosters.length ++; Booster storage tempBooster = boosters[boosters.length - 1]; tempBooster.owner = _owner; tempBooster.duration = _duration; tempBooster.boosterType = _type; tempBooster.strength = _strength; tempBooster.amount = _amount; tempBooster.raiseValue = _raiseValue; Transfer(address(0), _owner, boosters.length - 1); } function setFishbank(address _fishbank) onlyOwner public { fishbank = _fishbank; } function setChests(address _chests) onlyOwner public { if (chests != address(0)) { revert(); } chests = _chests; } function setAuction(address _auction) onlyOwner public { auction = _auction; } function getBoosterType(uint256 _tokenId) view public returns (uint8 boosterType) { boosterType = boosters[_tokenId].boosterType; } function getBoosterAmount(uint256 _tokenId) view public returns (uint32 boosterAmount) { boosterAmount = boosters[_tokenId].amount; } function getBoosterDuration(uint256 _tokenId) view public returns (uint32) { if (boosters[_tokenId].boosterType == 4 || boosters[_tokenId].boosterType == 2) { return boosters[_tokenId].duration + boosters[_tokenId].raiseValue * 60; } return boosters[_tokenId].duration; } function getBoosterStrength(uint256 _tokenId) view public returns (uint8 strength) { strength = boosters[_tokenId].strength; } function getBoosterRaiseValue(uint256 _tokenId) view public returns (uint24 raiseValue) { raiseValue = boosters[_tokenId].raiseValue; } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = boosters.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = boosters[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(boosters[_tokenId].owner == _from); //can only transfer if previous owner equals from boosters[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender || msg.sender == fishbank || msg.sender == auction); //require msg.sender to be approved for this token or to be the fishbank contract _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } function takeOwnership(uint256 _tokenId) public { require(approved[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } } contract FishbankChests is Ownable { struct Chest { address owner; uint16 boosters; uint16 chestType; uint24 raiseChance;//Increace chance to catch bigger chest (1 = 1:10000) uint8 onlySpecificType; uint8 onlySpecificStrength; uint24 raiseStrength; } Chest[] public chests; FishbankBoosters public boosterContract; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; mapping(address => bool) public minters; modifier onlyChestOwner(uint256 _tokenId) { require(chests[_tokenId].owner == msg.sender); _; } modifier onlyMinters() { require(minters[msg.sender]); _; } function FishbankChests(address _boosterAddress) public { boosterContract = FishbankBoosters(_boosterAddress); } function addMinter(address _minter) onlyOwner public { minters[_minter] = true; } function removeMinter(address _minter) onlyOwner public { minters[_minter] = false; } //create a chest function mintChest(address _owner, uint16 _boosters, uint24 _raiseStrength, uint24 _raiseChance, uint8 _onlySpecificType, uint8 _onlySpecificStrength) onlyMinters public { chests.length++; chests[chests.length - 1].owner = _owner; chests[chests.length - 1].boosters = _boosters; chests[chests.length - 1].raiseStrength = _raiseStrength; chests[chests.length - 1].raiseChance = _raiseChance; chests[chests.length - 1].onlySpecificType = _onlySpecificType; chests[chests.length - 1].onlySpecificStrength = _onlySpecificStrength; Transfer(address(0), _owner, chests.length - 1); } function convertChest(uint256 _tokenId) onlyChestOwner(_tokenId) public { Chest memory chest = chests[_tokenId]; uint16 numberOfBoosters = chest.boosters; if (chest.onlySpecificType != 0) {//Specific boosters if (chest.onlySpecificType == 1 || chest.onlySpecificType == 3) { boosterContract.mintBooster(msg.sender, 2 days, chest.onlySpecificType, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 5) {//Instant attack boosterContract.mintBooster(msg.sender, 0, 5, 1, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 2) {//Freeze uint32 freezeTime = 7 days; if (chest.onlySpecificStrength == 2) { freezeTime = 14 days; } else if (chest.onlySpecificStrength == 3) { freezeTime = 30 days; } boosterContract.mintBooster(msg.sender, freezeTime, 5, chest.onlySpecificType, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 4) {//Watch uint32 watchTime = 12 hours; if (chest.onlySpecificStrength == 2) { watchTime = 48 hours; } else if (chest.onlySpecificStrength == 3) { watchTime = 3 days; } boosterContract.mintBooster(msg.sender, watchTime, 4, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } } else {//Regular chest for (uint8 i = 0; i < numberOfBoosters; i ++) { uint24 random = uint16(keccak256(block.coinbase, block.blockhash(block.number - 1), i, chests.length)) % 1000 - chest.raiseChance; //get random 0 - 9999 minus raiseChance if (random > 850) { boosterContract.mintBooster(msg.sender, 2 days, 1, 1, 1, chest.raiseStrength); //Small Agility Booster } else if (random > 700) { boosterContract.mintBooster(msg.sender, 7 days, 2, 1, 1, chest.raiseStrength); //Small Freezer } else if (random > 550) { boosterContract.mintBooster(msg.sender, 2 days, 3, 1, 1, chest.raiseStrength); //Small Power Booster } else if (random > 400) { boosterContract.mintBooster(msg.sender, 12 hours, 4, 1, 1, chest.raiseStrength); //Tiny Watch } else if (random > 325) { boosterContract.mintBooster(msg.sender, 48 hours, 4, 2, 1, chest.raiseStrength); //Small Watch } else if (random > 250) { boosterContract.mintBooster(msg.sender, 2 days, 1, 2, 1, chest.raiseStrength); //Mid Agility Booster } else if (random > 175) { boosterContract.mintBooster(msg.sender, 14 days, 2, 2, 1, chest.raiseStrength); //Mid Freezer } else if (random > 100) { boosterContract.mintBooster(msg.sender, 2 days, 3, 2, 1, chest.raiseStrength); //Mid Power Booster } else if (random > 80) { boosterContract.mintBooster(msg.sender, 2 days, 1, 3, 1, chest.raiseStrength); //Big Agility Booster } else if (random > 60) { boosterContract.mintBooster(msg.sender, 30 days, 2, 3, 1, chest.raiseStrength); //Big Freezer } else if (random > 40) { boosterContract.mintBooster(msg.sender, 2 days, 3, 3, 1, chest.raiseStrength); //Big Power Booster } else if (random > 20) { boosterContract.mintBooster(msg.sender, 0, 5, 1, 1, 0); //Instant Attack } else { boosterContract.mintBooster(msg.sender, 3 days, 4, 3, 1, 0); //Gold Watch } } } _transfer(msg.sender, address(0), _tokenId); //burn chest } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = chests.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = chests[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(chests[_tokenId].owner == _from); //can only transfer if previous owner equals from chests[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender); //require msg.sender to be approved for this token _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } } contract FishbankUtils is Ownable { uint32[100] cooldowns = [ 720 minutes, 720 minutes, 720 minutes, 720 minutes, 720 minutes, //1-5 660 minutes, 660 minutes, 660 minutes, 660 minutes, 660 minutes, //6-10 600 minutes, 600 minutes, 600 minutes, 600 minutes, 600 minutes, //11-15 540 minutes, 540 minutes, 540 minutes, 540 minutes, 540 minutes, //16-20 480 minutes, 480 minutes, 480 minutes, 480 minutes, 480 minutes, //21-25 420 minutes, 420 minutes, 420 minutes, 420 minutes, 420 minutes, //26-30 360 minutes, 360 minutes, 360 minutes, 360 minutes, 360 minutes, //31-35 300 minutes, 300 minutes, 300 minutes, 300 minutes, 300 minutes, //36-40 240 minutes, 240 minutes, 240 minutes, 240 minutes, 240 minutes, //41-45 180 minutes, 180 minutes, 180 minutes, 180 minutes, 180 minutes, //46-50 120 minutes, 120 minutes, 120 minutes, 120 minutes, 120 minutes, //51-55 90 minutes, 90 minutes, 90 minutes, 90 minutes, 90 minutes, //56-60 75 minutes, 75 minutes, 75 minutes, 75 minutes, 75 minutes, //61-65 60 minutes, 60 minutes, 60 minutes, 60 minutes, 60 minutes, //66-70 50 minutes, 50 minutes, 50 minutes, 50 minutes, 50 minutes, //71-75 40 minutes, 40 minutes, 40 minutes, 40 minutes, 40 minutes, //76-80 30 minutes, 30 minutes, 30 minutes, 30 minutes, 30 minutes, //81-85 20 minutes, 20 minutes, 20 minutes, 20 minutes, 20 minutes, //86-90 10 minutes, 10 minutes, 10 minutes, 10 minutes, 10 minutes, //91-95 5 minutes, 5 minutes, 5 minutes, 5 minutes, 5 minutes //96-100 ]; function setCooldowns(uint32[100] _cooldowns) onlyOwner public { cooldowns = _cooldowns; } function getFishParams(uint256 hashSeed1, uint256 hashSeed2, uint256 fishesLength, address coinbase) external pure returns (uint32[4]) { bytes32[5] memory hashSeeds; hashSeeds[0] = keccak256(hashSeed1 ^ hashSeed2); //xor both seed from owner and user so no one can cheat hashSeeds[1] = keccak256(hashSeeds[0], fishesLength); hashSeeds[2] = keccak256(hashSeeds[1], coinbase); hashSeeds[3] = keccak256(hashSeeds[2], coinbase, fishesLength); hashSeeds[4] = keccak256(hashSeeds[1], hashSeeds[2], hashSeeds[0]); uint24[6] memory seeds = [ uint24(uint(hashSeeds[3]) % 10e6 + 1), //whale chance uint24(uint(hashSeeds[0]) % 420 + 1), //power uint24(uint(hashSeeds[1]) % 420 + 1), //agility uint24(uint(hashSeeds[2]) % 150 + 1), //speed uint24(uint(hashSeeds[4]) % 16 + 1), //whale type uint24(uint(hashSeeds[4]) % 5000 + 1) //rarity ]; uint32[4] memory fishParams; if (seeds[0] == 1000000) {//This is a whale 1:1 000 000 chance if (seeds[4] == 1) {//Orca fishParams = [140 + uint8(seeds[1] / 42), 140 + uint8(seeds[2] / 42), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 140) { fishParams[0]++; } if(fishParams[1] == 140) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } else if (seeds[4] < 4) {//Blue whale fishParams = [130 + uint8(seeds[1] / 42), 130 + uint8(seeds[2] / 42), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 130) { fishParams[0]++; } if(fishParams[1] == 130) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } else {//Cachalot fishParams = [115 + uint8(seeds[1] / 28), 115 + uint8(seeds[2] / 28), 75 + uint8(seeds[3] / 6), uint32(500000)]; if(fishParams[0] == 115) { fishParams[0]++; } if(fishParams[1] == 115) { fishParams[1]++; } if(fishParams[2] == 75) { fishParams[2]++; } } } else { if (seeds[5] == 5000) {//Legendary fishParams = [85 + uint8(seeds[1] / 14), 85 + uint8(seeds[2] / 14), uint8(50 + seeds[3] / 3), uint32(1000)]; if(fishParams[0] == 85) { fishParams[0]++; } if(fishParams[1] == 85) { fishParams[1]++; } } else if (seeds[5] > 4899) {//Epic fishParams = [50 + uint8(seeds[1] / 12), 50 + uint8(seeds[2] / 12), uint8(25 + seeds[3] / 2), uint32(300)]; if(fishParams[0] == 50) { fishParams[0]++; } if(fishParams[1] == 50) { fishParams[1]++; } } else if (seeds[5] > 4000) {//Rare fishParams = [20 + uint8(seeds[1] / 14), 20 + uint8(seeds[2] / 14), uint8(25 + seeds[3] / 3), uint32(100)]; if(fishParams[0] == 20) { fishParams[0]++; } if(fishParams[1] == 20) { fishParams[1]++; } } else {//Common fishParams = [uint8(seeds[1] / 21), uint8(seeds[2] / 21), uint8(seeds[3] / 3), uint32(36)]; if (fishParams[0] == 0) { fishParams[0] = 1; } if (fishParams[1] == 0) { fishParams[1] = 1; } if (fishParams[2] == 0) { fishParams[2] = 1; } } } return fishParams; } function getCooldown(uint16 speed) external view returns (uint64){ return uint64(now + cooldowns[speed - 1]); } //Ceiling function for fish generator function ceil(uint base, uint divider) internal pure returns (uint) { return base / divider + ((base % divider > 0) ? 1 : 0); } } /// @title Auction contract for any type of erc721 token /// @author Fishbank contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool); function transfer(address _to, uint256 _tokenId) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract ERC721Auction is Beneficiary { struct Auction { address seller; uint256 tokenId; uint64 auctionBegin; uint64 auctionEnd; uint256 startPrice; uint256 endPrice; } uint32 public auctionDuration = 7 days; ERC721 public ERC721Contract; uint256 public fee = 45000; //in 1 10000th of a percent so 4.5% at the start uint256 constant FEE_DIVIDER = 1000000; mapping(uint256 => Auction) public auctions; event AuctionWon(uint256 indexed tokenId, address indexed winner, address indexed seller, uint256 price); event AuctionStarted(uint256 indexed tokenId, address indexed seller); event AuctionFinalized(uint256 indexed tokenId, address indexed seller); function startAuction(uint256 _tokenId, uint256 _startPrice, uint256 _endPrice) external { require(ERC721Contract.transferFrom(msg.sender, address(this), _tokenId)); //Prices must be in range from 0.01 Eth and 10 000 Eth require(_startPrice <= 10000 ether && _endPrice <= 10000 ether); require(_startPrice >= (1 ether / 100) && _endPrice >= (1 ether / 100)); Auction memory auction; auction.seller = msg.sender; auction.tokenId = _tokenId; auction.auctionBegin = uint64(now); auction.auctionEnd = uint64(now + auctionDuration); require(auction.auctionEnd > auction.auctionBegin); auction.startPrice = _startPrice; auction.endPrice = _endPrice; auctions[_tokenId] = auction; AuctionStarted(_tokenId, msg.sender); } function buyAuction(uint256 _tokenId) payable external { Auction storage auction = auctions[_tokenId]; uint256 price = calculateBid(_tokenId); uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed? require(price <= msg.value); //revert if not enough ether send if (price != msg.value) {//send back to much eth msg.sender.transfer(msg.value - price); } beneficiary.transfer(totalFee); auction.seller.transfer(price - totalFee); if (!ERC721Contract.transfer(msg.sender, _tokenId)) { revert(); //can't complete transfer if this fails } AuctionWon(_tokenId, msg.sender, auction.seller, price); delete auctions[_tokenId]; //deletes auction } function saveToken(uint256 _tokenId) external { require(auctions[_tokenId].auctionEnd < now); //auction must have ended require(ERC721Contract.transfer(auctions[_tokenId].seller, _tokenId)); //transfer fish back to seller AuctionFinalized(_tokenId, auctions[_tokenId].seller); delete auctions[_tokenId]; //delete auction } function ERC721Auction(address _ERC721Contract) public { ERC721Contract = ERC721(_ERC721Contract); } function setFee(uint256 _fee) onlyOwner public { if (_fee > fee) { revert(); //fee can only be set to lower value to prevent attacks by owner } fee = _fee; // all is well set fee } function calculateBid(uint256 _tokenId) public view returns (uint256) { Auction storage auction = auctions[_tokenId]; if (now >= auction.auctionEnd) {//if auction ended return auction end price return auction.endPrice; } //get hours passed uint256 hoursPassed = (now - auction.auctionBegin) / 1 hours; uint256 currentPrice; //get total hours uint16 totalHours = uint16(auctionDuration /1 hours) - 1; if (auction.endPrice > auction.startPrice) { currentPrice = auction.startPrice + (hoursPassed * (auction.endPrice - auction.startPrice))/ totalHours; } else if(auction.endPrice < auction.startPrice) { currentPrice = auction.startPrice - (hoursPassed * (auction.startPrice - auction.endPrice))/ totalHours; } else {//start and end are the same currentPrice = auction.endPrice; } return uint256(currentPrice); //return the price at this very moment } /// return token if case when need to redeploy auction contract function returnToken(uint256 _tokenId) onlyOwner public { require(ERC721Contract.transfer(auctions[_tokenId].seller, _tokenId)); //transfer fish back to seller AuctionFinalized(_tokenId, auctions[_tokenId].seller); delete auctions[_tokenId]; } } /// @title Core contract of fishbank /// @author Fishbank contract Fishbank is ChestsStore { struct Fish { address owner; uint8 activeBooster; uint64 boostedTill; uint8 boosterStrength; uint24 boosterRaiseValue; uint64 weight; uint16 power; uint16 agility; uint16 speed; bytes16 color; uint64 canFightAgain; uint64 canBeAttackedAgain; } struct FishingAttempt { address fisher; uint256 feePaid; address affiliate; uint256 seed; uint64 deadline;//till when does the contract owner have time to resolve; } modifier onlyFishOwner(uint256 _tokenId) { require(fishes[_tokenId].owner == msg.sender); _; } modifier onlyResolver() { require(msg.sender == resolver); _; } modifier onlyMinter() { require(msg.sender == minter); _; } Fish[] public fishes; address public resolver; address public auction; address public minter; bool public implementsERC721 = true; string public name = "Fishbank"; string public symbol = "FISH"; bytes32[] public randomHashes; uint256 public hashesUsed; uint256 public aquariumCost = 1 ether / 100 * 3;//fee for fishing starts at 0.03 ether uint256 public resolveTime = 30 minutes;//how long does the contract owner have to resolve hashes uint16 public weightLostPartLimit = 5; FishbankBoosters public boosters; FishbankChests public chests; FishbankUtils private utils; mapping(bytes32 => FishingAttempt) public pendingFishing;//attempts that need solving; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; mapping(address => bool) public affiliated; event AquariumFished( bytes32 hash, address fisher, uint256 feePaid ); //event broadcated when someone fishes in aqaurium event AquariumResolved(bytes32 hash, address fisher); event Attack( uint256 attacker, uint256 victim, uint256 winner, uint64 weight, uint256 ap, uint256 vp, uint256 random ); event BoosterApplied(uint256 tokenId, uint256 boosterId); /// @notice Constructor of the contract. Sets resolver, beneficiary, boosters and chests /// @param _boosters the address of the boosters smart contract /// @param _chests the address of the chests smart contract function Fishbank(address _boosters, address _chests, address _utils) ChestsStore(_chests) public { resolver = msg.sender; beneficiary = msg.sender; boosters = FishbankBoosters(_boosters); chests = FishbankChests(_chests); utils = FishbankUtils(_utils); } /// @notice Mints fishes according to params can only be called by the owner /// @param _owner array of addresses the fishes should be owned by /// @param _weight array of weights for the fishes /// @param _power array of power levels for the fishes /// @param _agility array of agility levels for the fishes /// @param _speed array of speed levels for the fishes /// @param _color array of color params for the fishes function mintFish(address[] _owner, uint32[] _weight, uint8[] _power, uint8[] _agility, uint8[] _speed, bytes16[] _color) onlyMinter public { for (uint i = 0; i < _owner.length; i ++) { _mintFish(_owner[i], _weight[i], _power[i], _agility[i], _speed[i], _color[i]); } } /// @notice Internal method for minting a fish /// @param _owner address of owner for the fish /// @param _weight weight param for fish /// @param _power power param for fish /// @param _agility agility param for the fish /// @param _speed speed param for the fish /// @param _color color param for the fish function _mintFish(address _owner, uint32 _weight, uint8 _power, uint8 _agility, uint8 _speed, bytes16 _color) internal { fishes.length += 1; uint256 newFishId = fishes.length - 1; Fish storage newFish = fishes[newFishId]; newFish.owner = _owner; newFish.weight = _weight; newFish.power = _power; newFish.agility = _agility; newFish.speed = _speed; newFish.color = _color; balances[_owner] ++; Transfer(address(0), _owner, newFishId); } function setWeightLostPartLimit(uint8 _weightPart) onlyOwner public { weightLostPartLimit = _weightPart; } /// @notice Sets the cost for fishing in the aquarium /// @param _fee new fee for fishing in wei function setAquariumCost(uint256 _fee) onlyOwner public { aquariumCost = _fee; } /// @notice Sets address that resolves hashes for fishing can only be called by the owner /// @param _resolver address of the resolver function setResolver(address _resolver) onlyOwner public { resolver = _resolver; } /// @notice Sets the address getting the proceedings from fishing in the aquarium /// @param _beneficiary address of the new beneficiary function setBeneficiary(address _beneficiary) onlyOwner public { beneficiary = _beneficiary; } function setAuction(address _auction) onlyOwner public { auction = _auction; } function setBoosters(address _boosters) onlyOwner public { boosters = FishbankBoosters(_boosters); } function setMinter(address _minter) onlyOwner public { minter = _minter; } function setUtils(address _utils) onlyOwner public { utils = FishbankUtils(_utils); } /// batch fishing from 1 to 10 times function batchFishAquarium(uint256[] _seeds, address _affiliate) payable public { require(_seeds.length > 0 && _seeds.length <= 10); require(msg.value >= aquariumCost * _seeds.length); //must send enough ether to cover costs require(randomHashes.length > hashesUsed + _seeds.length); //there needs to be a hash left if (msg.value > aquariumCost * _seeds.length) { msg.sender.transfer(msg.value - aquariumCost * _seeds.length); //send to much ether back } for (uint256 i = 0; i < _seeds.length; i ++) { _fishAquarium(_seeds[i]); } if(_affiliate != address(0)) { pendingFishing[randomHashes[hashesUsed - 1]].affiliate = _affiliate; } } function _fishAquarium(uint256 _seed) internal { //this loop prevents from using the same hash as another fishing attempt if the owner submits the same hash multiple times while (pendingFishing[randomHashes[hashesUsed]].fisher != address(0)) { hashesUsed++; //increase hashesUsed and try next one } FishingAttempt storage newAttempt = pendingFishing[randomHashes[hashesUsed]]; newAttempt.fisher = msg.sender; newAttempt.feePaid = aquariumCost; //set the fee paid so it can be returned if the hash doesn't get resolved fast enough newAttempt.seed = _seed; //sets the seed that gets combined with the random seed of the owner newAttempt.deadline = uint64(now + resolveTime); //saves deadline after which the fisher can redeem his fishing fee hashesUsed++; //increase hashes used so it cannot be used again AquariumFished(randomHashes[hashesUsed - 1], msg.sender, aquariumCost); //broadcast event } /// @notice Call this to resolve hashes and generate fish/chests /// @param _seed seed that corresponds to the hash function _resolveAquarium(uint256 _seed) internal { bytes32 tempHash = keccak256(_seed); FishingAttempt storage tempAttempt = pendingFishing[tempHash]; require(tempAttempt.fisher != address(0)); //attempt must be set so we look if fisher is set if (tempAttempt.affiliate != address(0) && !affiliated[tempAttempt.fisher]) {//if affiliate is set chests.mintChest(tempAttempt.affiliate, 1, 0, 0, 0, 0); //Chest with one random booster affiliated[tempAttempt.fisher] = true; } uint32[4] memory fishParams = utils.getFishParams(_seed, tempAttempt.seed, fishes.length, block.coinbase); _mintFish(tempAttempt.fisher, fishParams[3], uint8(fishParams[0]), uint8(fishParams[1]), uint8(fishParams[2]), bytes16(keccak256(_seed ^ tempAttempt.seed))); beneficiary.transfer(tempAttempt.feePaid); AquariumResolved(tempHash, tempAttempt.fisher); //broadcast event delete pendingFishing[tempHash]; //delete fishing attempt } /// @notice Batch resolve fishing attempts /// @param _seeds array of seeds that correspond to hashes that need resolving function batchResolveAquarium(uint256[] _seeds) onlyResolver public { for (uint256 i = 0; i < _seeds.length; i ++) { _resolveAquarium(_seeds[i]); } } /// @notice Adds an array of hashes to be used for resolving /// @param _hashes array of hashes to add function addHash(bytes32[] _hashes) onlyResolver public { for (uint i = 0; i < _hashes.length; i ++) { randomHashes.push(_hashes[i]); } } /// @notice Call this function to attack another fish /// @param _attacker ID of fish that is attacking /// @param _victim ID of fish to attack function attack(uint256 _attacker, uint256 _victim) onlyFishOwner(_attacker) public { Fish memory attacker = fishes[_attacker]; Fish memory victim = fishes[_victim]; //check if attacker is sleeping if (attacker.activeBooster == 2 && attacker.boostedTill > now) {//if your fish is sleeping auto awake it fishes[_attacker].activeBooster = 0; attacker.boostedTill = uint64(now); //set booster to invalid one so it has no effect } //check if victim has active sleeping booster require(!((victim.activeBooster == 2) && victim.boostedTill >= now)); //cannot attack a sleeping fish require(now >= attacker.canFightAgain); //check if attacking fish is cooled down require(now >= victim.canBeAttackedAgain); //check if victim fish can be attacked again if (msg.sender == victim.owner) { uint64 weight = attacker.weight < victim.weight ? attacker.weight : victim.weight; fishes[_attacker].weight += weight; fishes[_victim].weight -= weight; fishes[_attacker].canFightAgain = uint64(utils.getCooldown(attacker.speed)); if (fishes[_victim].weight == 0) { _transfer(msg.sender, address(0), _victim); balances[fishes[_victim].owner] --; //burn token } else { fishes[_victim].canBeAttackedAgain = uint64(now + 1 hours); //set victim cooldown 1 hour } Attack(_attacker, _victim, _attacker, weight, 0, 0, 0); return; } if (victim.weight < 2 || attacker.weight < 2) { revert(); //revert if one of the fish is below fighting weight } uint256 AP = getFightingAmounts(attacker, true); // get attacker power uint256 VP = getFightingAmounts(victim, false); // get victim power bytes32 randomHash = keccak256(block.coinbase, block.blockhash(block.number - 1), fishes.length); uint256 max = AP > VP ? AP : VP; uint256 attackRange = max * 2; uint256 random = uint256(randomHash) % attackRange + 1; uint64 weightLost; if (random <= (max + AP - VP)) { weightLost = _handleWin(_attacker, _victim); Attack(_attacker, _victim, _attacker, weightLost, AP, VP, random); } else { weightLost = _handleWin(_victim, _attacker); Attack(_attacker, _victim, _victim, weightLost, AP, VP, random); //broadcast event } fishes[_attacker].canFightAgain = uint64(utils.getCooldown(attacker.speed)); fishes[_victim].canBeAttackedAgain = uint64(now + 1 hours); //set victim cooldown 1 hour } /// @notice Handles lost gained weight after fight /// @param _winner the winner of the fight /// @param _loser the loser of the fight function _handleWin(uint256 _winner, uint256 _loser) internal returns (uint64) { Fish storage winner = fishes[_winner]; Fish storage loser = fishes[_loser]; uint64 fullWeightLost = loser.weight / sqrt(winner.weight); uint64 maxWeightLost = loser.weight / weightLostPartLimit; uint64 weightLost = maxWeightLost < fullWeightLost ? maxWeightLost : fullWeightLost; if (weightLost < 1) { weightLost = 1; // Minimum 1 } winner.weight += weightLost; loser.weight -= weightLost; return weightLost; } /// @notice get attack and defence from fish /// @param _fish is Fish token /// @param _is_attacker true if fish is attacker otherwise false function getFightingAmounts(Fish _fish, bool _is_attacker) internal view returns (uint256){ return (getFishPower(_fish) * (_is_attacker ? 60 : 40) + getFishAgility(_fish) * (_is_attacker ? 40 : 60)) * _fish.weight; } /// @notice Apply a booster to a fish /// @param _tokenId the fish the booster should be applied to /// @param _booster the Id of the booster the token should be applied to function applyBooster(uint256 _tokenId, uint256 _booster) onlyFishOwner(_tokenId) public { require(msg.sender == boosters.ownerOf(_booster)); //only owner can do this require(boosters.getBoosterAmount(_booster) >= 1); Fish storage tempFish = fishes[_tokenId]; uint8 boosterType = uint8(boosters.getBoosterType(_booster)); if (boosterType == 1 || boosterType == 2 || boosterType == 3) {//if booster is attack or agility or sleep tempFish.boosterStrength = boosters.getBoosterStrength(_booster); tempFish.activeBooster = boosterType; tempFish.boostedTill = boosters.getBoosterDuration(_booster) * boosters.getBoosterAmount(_booster) + uint64(now); tempFish.boosterRaiseValue = boosters.getBoosterRaiseValue(_booster); } else if (boosterType == 4) {//watch booster require(tempFish.boostedTill > uint64(now)); //revert on using watch on booster that has passed; tempFish.boosterStrength = boosters.getBoosterStrength(_booster); tempFish.boostedTill += boosters.getBoosterDuration(_booster) * boosters.getBoosterAmount(_booster); //add time to booster } else if (boosterType == 5) {//Instant attack require(boosters.getBoosterAmount(_booster) == 1); //Can apply only one instant attack booster tempFish.canFightAgain = 0; } require(boosters.transferFrom(msg.sender, address(0), _booster)); //burn booster BoosterApplied(_tokenId, _booster); } /// @notice square root function used for weight gain/loss /// @param x uint64 to get square root from function sqrt(uint64 x) pure internal returns (uint64 y) { uint64 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } //utlitiy function for easy testing can be removed later function doKeccak256(uint256 _input) pure public returns (bytes32) { return keccak256(_input); } function getFishPower(Fish _fish) internal view returns (uint24 power) { power = _fish.power; if (_fish.activeBooster == 1 && _fish.boostedTill > now) {// check if booster active uint24 boosterPower = (10 * _fish.boosterStrength + _fish.boosterRaiseValue + 100) * power / 100 - power; if (boosterPower < 1 && _fish.boosterStrength == 1) { power += 1; } else if (boosterPower < 3 && _fish.boosterStrength == 2) { power += 3; } else if (boosterPower < 5 && _fish.boosterStrength == 3) { power += 5; } else { power = boosterPower + power; } } } function getFishAgility(Fish _fish) internal view returns (uint24 agility) { agility = _fish.agility; if (_fish.activeBooster == 3 && _fish.boostedTill > now) {// check if booster active uint24 boosterPower = (10 * _fish.boosterStrength + _fish.boosterRaiseValue + 100) * agility / 100 - agility; if (boosterPower < 1 && _fish.boosterStrength == 1) { agility += 1; } else if (boosterPower < 3 && _fish.boosterStrength == 2) { agility += 3; } else if (boosterPower < 5 && _fish.boosterStrength == 3) { agility += 5; } else { agility = boosterPower + agility; } } } //ERC721 functionality //could split this to a different contract but doesn't make it easier to read event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = fishes.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = fishes[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(fishes[_tokenId].owner == _from); //can only transfer if previous owner equals from fishes[_tokenId].owner = _to; approved[_tokenId] = address(0); //reset approved of fish on every transfer balances[_from] -= 1; //underflow can only happen on 0x balances[_to] += 1; //overflows only with very very large amounts of fish Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyFishOwner(_tokenId) //check if msg.sender is the owner of this fish returns (bool) { _transfer(msg.sender, _to, _tokenId); //after master modifier invoke internal transfer return true; } function approve(address _to, uint256 _tokenId) public onlyFishOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender || msg.sender == auction); Fish storage fish = fishes[_tokenId]; if (msg.sender == auction) { fish.activeBooster = 2; //Freeze for auction fish.boostedTill = uint64(now + 7 days); fish.boosterStrength = 1; } //require msg.sender to be approved for this token _transfer(_from, _to, _tokenId); //handles event, balances and approval reset return true; } function takeOwnership(uint256 _tokenId) public { require(approved[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } }
Batch resolve fishing attempts _seeds array of seeds that correspond to hashes that need resolving
function batchResolveAquarium(uint256[] _seeds) onlyResolver public { } for (uint256 i = 0; i < _seeds.length; i ++) { _resolveAquarium(_seeds[i]); } }
20,824
./full_match/97/0x8B4032b71C804517D54878d78730c230F768Ad57/sources/tests/BSC ChainLinkTests/VaultFactory.sol
Delete Project from allProjects andemit vaultDelisted(msg.sender, _tokenContractAddress);assert(projects.length > 0);
function deleteVault(address _vaultAddress) public /* onlyOwner */ { uint256 index = vaultIndex[_vaultAddress]; removeInOrder(index); delete mappedVaults[_vaultAddress]; userVaultCount[msg.sender]--; }
5,018,598
// File: openzeppelin-solidity/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.0; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: openzeppelin-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol pragma solidity ^0.5.0; /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet) public { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } // File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor (uint256 openingTime, uint256 closingTime) public { // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: contracts/SalesContract.sol pragma solidity ^0.5.0; contract SalesContract is AllowanceCrowdsale, TimedCrowdsale { ERC20 private _acceptedToken; // How many token units a buyer gets per unit of accepted token. // The rate is the conversion between the smallest and indivisible tokens units. uint256 private _acceptedTokenRate; uint256 private _sold; constructor( uint256 rate, address payable wallet, ERC20 token, address payable tokenWallet, uint256 openingTime, uint256 closingTime, ERC20 acceptedToken, uint256 acceptedTokenRate ) Crowdsale(rate, wallet, token) AllowanceCrowdsale(tokenWallet) TimedCrowdsale(openingTime, closingTime) public { require(acceptedTokenRate > 0, "SalesContract: accepted token rate is 0"); require(address(acceptedToken) != address(0), "SalesContract: accepted token is the zero address"); _acceptedToken = acceptedToken; _acceptedTokenRate = acceptedTokenRate; _sold = 0; } /** * @return the token being sold. */ function acceptedToken() public view returns (IERC20) { return _acceptedToken; } /** * @return the number of token units a buyer gets per unit of accepted token. */ function acceptedTokenRate() public view returns (uint256) { return _acceptedTokenRate; } /** * @return the token being sold. */ function sold() public view returns (uint256) { return _sold; } function exchangeTokens(address beneficiary, uint256 amount) public payable { require(beneficiary != address(0)); require(amount != 0); // check user balance and allowance uint256 allowance = Math.min( _acceptedToken.balanceOf(beneficiary), _acceptedToken.allowance(beneficiary, address(this)) ); require(allowance >= amount, "SalesContract: You have not allowed to get your tokens or you have insufficient token balance"); // Try to transfer accepted token to receiving wallet _acceptedToken.transferFrom(beneficiary, wallet(), amount); // calculate token amount to be return in exchange uint256 amountToReturn = amount.mul(_acceptedTokenRate); _sold = _sold.add(amountToReturn); // If above has succeeded transfer tokens to to beneficiary in return token().transferFrom(tokenWallet(), beneficiary, amountToReturn); } /** * @dev Override to track number of sold tokens * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { _sold = _sold.add(_getTokenAmount(_weiAmount)); } /** * @dev Withdraw Wei sent directly to contract address */ function withdrawAcceptedTokens(uint256 amount) public payable { require(_msgSender() == wallet(), "SalesContract: You can withdraw accepted tokens only from receiving wallet"); _acceptedToken.transfer(wallet(), amount); } /** * @dev Withdraw Wei sent directly to contract address */ function withdraw(uint256 amount) public payable { require(_msgSender() == wallet(), "SalesContract: You can withdraw only from receiving wallet"); require(weiRaised() < amount, "SalesContract: Not enough Wei to withdraw"); wallet().transfer(msg.value); } }
Override to extend the way in which ether is converted to tokens. weiAmount Value in wei to be converted into tokens return Number of tokens that can be purchased with the specified _weiAmount/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); }
129,850
//Address: 0x240a5f36ac5f5037d5a02863d1ee39a21da6d9a3 //Contract name: CompletelyDecentralizedWorld //Balance: 0 Ether //Verification Date: 12/13/2017 //Transacion Count: 7 // CODE STARTS HERE pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract CompletelyDecentralizedWorld is StandardToken { string public constant name = "CompletelyDecentralizedWorld"; string public constant symbol = "CDW"; uint public constant decimals = 18; uint teamPartToken = 50000000 * (10 ** uint256(decimals)); uint communityBuildingToken = 30000000 * (10 ** uint256(decimals)); uint16[4] public bonusPercentages = [30,20,10,0]; uint public constant NUM_OF_PHASE = 4; uint public constant BLOCK_PER_PHASE = 150000; address public constant target = 0xEAD3346C806803e1500d96B9a2D7065d0526Caf6; // Team Keep token address public constant addr_teamPartToken = 0x898f9ca9cf198E059396337A7bbbBBed59856089; bool teamPartTokenIssued = false; // Community Building address public constant addr_communityBuildingToken = 0x8E5A7df3fDbbB467a1D6feed337EC2e1938AAb3f; bool communityBuildingTokenIssued = false; uint public firstblock = 0; uint public constant HARD_CAP = 20000 ether; uint public constant BASE_RATE = 25000; uint public totalEthReceived = 0; uint public issueIndex = 0; /** Events */ event SaleStarted(); event SaleEnded(); event InvalidCaller(address caller); event InvalidState(bytes msg); event Issue(uint issueIndex, address addr, uint ethAmount, uint tokenAmount); event SaleSucceeded(); event SaleFailed(); /**MODIFIERS*/ modifier onlyOwner { if (target == msg.sender) { _; } else { InvalidCaller(msg.sender); revert(); } } modifier beforeStart { if (!saleStarted()) { _; } else { InvalidState("Sale has not started yet"); revert(); } } modifier inProgress { if (saleStarted() && !saleEnded()) { _; } else { InvalidState("Sale is not in Progress"); revert(); } } modifier afterEnd { if (saleEnded()) { _; } else { InvalidState("Sale is not ended yet"); revert(); } } /** PUBLIC FUNCTIONS*/ function start(uint _firstblock) public onlyOwner beforeStart { if (_firstblock <= block.number) { revert(); } firstblock = _firstblock; SaleStarted(); issueTeamPartToken(); issueCommunityBuildingToken(); } function close() public onlyOwner afterEnd { issueTeamPartToken(); issueCommunityBuildingToken(); SaleSucceeded(); } function price() public constant returns (uint tokens) { return computeTokenAmount(1 ether); } function () public payable{ issueToken(msg.sender); } function issueToken(address recipient) public payable inProgress{ assert(msg.value >= 0.01 ether); uint tokens = computeTokenAmount(msg.value); totalEthReceived = totalEthReceived.add(msg.value); totalSupply = totalSupply.add(tokens); balances[recipient] = balances[recipient].add(tokens); Issue(issueIndex++, recipient, msg.value, tokens); if (!target.send(msg.value)){ revert(); } } /**INTERNAL FUNCTIONS*/ function computeTokenAmount(uint ethAmount) internal constant returns (uint tokens) { uint phase = (block.number - firstblock).div(BLOCK_PER_PHASE); if (phase >= bonusPercentages.length) { phase = bonusPercentages.length - 1; } uint tokenBase = ethAmount.mul(BASE_RATE); uint tokenBonus = tokenBase.mul(bonusPercentages[phase]).div(100); tokens = tokenBase.add(tokenBonus); } function issueTeamPartToken() internal { if(teamPartTokenIssued){ InvalidState("teamPartToken has been issued already"); } else { totalSupply = totalSupply.add(teamPartToken); balances[addr_teamPartToken] = balances[addr_teamPartToken].add(teamPartToken); Issue(issueIndex++, addr_teamPartToken, 0, teamPartToken); teamPartTokenIssued = true; } } function issueCommunityBuildingToken() internal { if(communityBuildingTokenIssued){ InvalidState("communityBuildingToken has been issued already"); } else { totalSupply = totalSupply.add(communityBuildingToken); balances[addr_communityBuildingToken] = balances[addr_communityBuildingToken].add(communityBuildingToken); Issue(issueIndex++, addr_communityBuildingToken, 0, communityBuildingToken); communityBuildingTokenIssued = true; } } function saleStarted() public constant returns (bool) { return (firstblock > 0 && block.number >= firstblock); } function saleEnded() public constant returns (bool) { return firstblock > 0 && (saleDue() || hardCapReached()); } function saleDue() public constant returns (bool) { return block.number >= firstblock + BLOCK_PER_PHASE*NUM_OF_PHASE; } function hardCapReached() public constant returns (bool) { return totalEthReceived >= HARD_CAP; } }
PUBLIC FUNCTIONS/
function start(uint _firstblock) public onlyOwner beforeStart { if (_firstblock <= block.number) { revert(); } firstblock = _firstblock; SaleStarted(); issueTeamPartToken(); issueCommunityBuildingToken(); }
5,420,025
/* - ✔️ Supply Name: Pearl of the Orient Seas - Creating a better life for everyone - ✔️ Symbol: PEARL - ✔️ Anti-Whale System (3% Sell Price Impact) - ✔️ Anti-Serial Selling System (Anti-Dump) - ✔️ Manual Burning and Buyback capability - ✔️ Send to Buyback Wallet per transaction: 2% (Sent on ETH) - ✔️ Send to Marketing Wallet per transaction: 1% (Sent on ETH) - ✔️ Send to Team Wallet per transaction: 5% (Sent on ETH) - ✔️ Send to Charity Wallet per transaction: 2% (Sent on ETH) - ✔️ Implemented Dynamic Sell Logic (Anti-Bot) Developed by Yiannos Christou Debugged, and Tested by Jay Pingul Team: Angelica Tresvalles, Leonard Bangco, Kriz Resurreccion, Edward Nguyen, and the one and only TITA MORIN */ pragma solidity ^0.8.4; // SPDX-License-Identifier: MIT abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * It also provides the functionality to store the contract in VøidSwap's Cosmic Vault * using {storeInCosmicVault}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract CVOwnable is Context { address private _owner; uint256 private _unlockTime; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "CVOwnable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Returns the address of the previous owner. */ function previousOwner() public view returns(address) { return _previousOwner; } /** * @dev Returns the unlock time of the contracted stored in the Cosmic Vault. */ function getUnlockTime() public view returns(uint256){ return _unlockTime; } /** * @dev Transfers ownership of the contract to the Cosmic Vault (`cosmicVault`) and * sets the time (`unlockTime`) at which the now stored contract can be transferred back to * the previous owner. * NOTE Can only be called by the current owner. */ function storeInCosmicVault(address cosmicVault, uint256 unlockTime) public virtual onlyOwner { require(cosmicVault != address(0), "CVOwnable: new owner is the zero address"); _previousOwner = _owner; _unlockTime = unlockTime; emit OwnershipTransferred(_previousOwner, cosmicVault); _owner = cosmicVault; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * NOTE Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "CVOwnable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { _previousOwner = _owner; _owner = newOwner; emit OwnershipTransferred(_previousOwner, newOwner); } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); } contract PEARL is Context, IERC20, CVOwnable { // Nominal name using SafeMath for uint256; string private constant _name = "Pearl of the Orient Seas"; // Token Name string private constant _symbol = "PEARL"; // Token symbol uint8 private constant _decimals = 9; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 private constant _tTotal = 100000000000 * 10**9; // Total supply uint256 public _teamFee = 10; uint256 public _storedTeamFee = _teamFee; uint256 public _teamCutPct = 5; // 5% cut to team uint256 public _marketingCutPct = 1; // 1% cut to marketing funds uint256 public _charityCutPct = 2; // 2% cut to Project Pearls uint256 public _liquidityCutPct = 2; // 2% Buyback cut mapping(address => uint256) private sellCooldown; mapping(address => uint256) private firstSell; mapping(address => uint256) private sellNumber; address payable private _teamAddress; address payable private _marketingAddress; address payable private _charityAddress; address payable private _liquidityAddress; uint256 public minimumContractTokenBalanceToSwap = 10000000 * 10**9; // 0.06% of total supply for both LQ and ETH distribution uint256 public minimumContractEthBalanceToSwap = 3 * 10**16; mapping(address => bool) private _isAdmin; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen = false; bool private liquidityAdded = false; bool private inSwap = false; bool private swapEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint256 _maxTxAmount); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity); event SwapTokensForETH(uint256 amountIn, address[] path); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address payable teamFunds, address payable marketingFunds, address payable charityFunds, address payable liquidityFunds) { _teamAddress = teamFunds; _marketingAddress = marketingFunds; _charityAddress = charityFunds; _liquidityAddress = liquidityFunds; _balances[_msgSender()] = _tTotal; _isExcludedFromFee[owner()] = true; _isAdmin[owner()] = true; _isExcludedFromFee[address(this)] = true; _isAdmin[address(this)] = true; _isExcludedFromFee[_teamAddress] = true; _isAdmin[_teamAddress] = true; _isExcludedFromFee[_marketingAddress] = true; _isAdmin[_marketingAddress] = true; _isExcludedFromFee[_charityAddress] = true; _isAdmin[_charityAddress] = true; _isExcludedFromFee[_liquidityAddress] = true; _isAdmin[_liquidityAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function removeAllFee() private { if (_teamFee == 0) return; _teamFee = 0; } function restoreAllFee() private { _teamFee = _storedTeamFee; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); uint256 contractTokenBalance = balanceOf(address(this)); // Get Token contract balance bool overMinTokenBalance = contractTokenBalance >= minimumContractTokenBalanceToSwap; uint256 contractETHBalance = address(this).balance; // Get ETH contract balance bool overMinEthBalance = contractETHBalance >= minimumContractEthBalanceToSwap; if (!_isAdmin[from] && !_isAdmin[from]) { if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { // Buying require(tradingOpen); _teamFee = 10; // BUYING 2% Charity, 2% Liquidity Fee, 1% Marketing, 5% Team Fee = 10 } if (!inSwap && swapEnabled && to == uniswapV2Pair) { // Dynamic Selling Logic require(amount <= balanceOf(uniswapV2Pair).mul(3).div(100) && amount <= _maxTxAmount); require(sellCooldown[from] < block.timestamp); if(firstSell[from] + (4 hours) < block.timestamp) { sellNumber[from] = 0; } if (sellNumber[from] == 0) { // Cooldown Timings _teamFee = 10; // BUYING 2% Charity, 2% Liquidity Fee, 1% Marketing, 5% Team Fee = 10 sellNumber[from]++; firstSell[from] = block.timestamp; sellCooldown[from] = block.timestamp + (60 seconds); //from initial buy 60 seconds } else if (sellNumber[from] == 1) { _teamFee = 13; // BUYING 2% Charity, 4% Liquidity Fee, 1% Marketing, 6% Team Fee = 13 sellNumber[from]++; sellCooldown[from] = block.timestamp + (30 minutes); //from 1st buy 30 minutes } else if (sellNumber[from] == 2) { _teamFee = 16; // BUYING 2% Charity, 6% Liquidity Fee, 1% Marketing, 7% Team Fee = 16 sellNumber[from]++; sellCooldown[from] = block.timestamp + (2 hours); //from 2nd buy 2 hours } else if (sellNumber[from] == 3) { _teamFee = 19; // BUYING 2% Charity, 8% Liquidity Fee, 1% Marketing, 8% Team Fee = 19 sellNumber[from]++; sellCooldown[from] = firstSell[from] + (4 hours); //from initial buy, 4 hours then resets to 60 seconds } } if (!inSwap && from != uniswapV2Pair && swapEnabled) { if (overMinTokenBalance) { swapTokensForEth(contractTokenBalance); } if (overMinEthBalance) { sendETHToFee(contractETHBalance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } _tokenTransfer(from, to, amount, takeFee); restoreAllFee; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp); emit SwapTokensForETH(tokenAmount, path); } function sendETHToFee(uint256 beforeSplit) private { uint256 teamCut = beforeSplit.mul(50).div(100); uint256 marketingCut = beforeSplit.mul(10).div(100); uint256 charityCut = beforeSplit.mul(20).div(100); uint256 liquidityCut = beforeSplit.mul(20).div(100); _teamAddress.transfer(teamCut); _marketingAddress.transfer(marketingCut); _charityAddress.transfer(charityCut); _liquidityAddress.transfer(liquidityCut); } function openTrading() public onlyOwner { require(liquidityAdded); tradingOpen = true; } function addInitialLiquidity() external onlyOwner() { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Nominal router. uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this), balanceOf(address(this)), 0, 0, address(this), block.timestamp); swapEnabled = true; liquidityAdded = true; _maxTxAmount = 30000000 * 10**9; // 0.3% IERC20(uniswapV2Pair).approve(address(uniswapV2Router),type(uint256).max); } function manualTokenSwap() external { require(_msgSender() == owner()); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function recoverEthFromContract() external { require(_msgSender() == owner()); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { ( uint256 tTransferAmount, uint256 tTeam) = _getValues(tAmount); _balances[sender] = _balances[sender].sub(tAmount); _balances[recipient] = _balances[recipient].add(tTransferAmount); _takeTeam(tTeam); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { _balances[address(this)] = _balances[address(this)].add(tTeam); } receive() external payable {} function _getValues(uint256 tAmount) private view returns (uint256, uint256) { (uint256 tTransferAmount, uint256 tTeam) = _getTValues(tAmount, _teamFee); return (tTransferAmount, tTeam); } function _getTValues(uint256 tAmount, uint256 teamFee) private pure returns (uint256, uint256) { uint256 tTeam = tAmount.mul(teamFee).div(100); uint256 tTransferAmount = tAmount.sub(tTeam); return (tTransferAmount, tTeam); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function manualBurn (uint256 amount) external onlyOwner() { require(amount <= balanceOf(owner()), "Amount exceeds available tokens."); _tokenTransfer(msg.sender, deadAddress, amount, false); } function setRouterAddress(address newRouter) public onlyOwner() { IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(newRouter); uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH()); uniswapV2Router = _newPancakeRouter; } function setTeamCutFee (uint256 _teamCut) external onlyOwner() { _teamCutPct = _teamCut; _teamFee = _teamCut.add(_marketingCutPct).add(_charityCutPct).add(_liquidityCutPct); _storedTeamFee = _teamFee; } function setMarketingCutFee (uint256 _marketingCut) external onlyOwner() { _marketingCutPct = _marketingCut; _teamFee = _teamCutPct.add(_marketingCut).add(_charityCutPct).add(_liquidityCutPct); _storedTeamFee = _teamFee; } function setCharityCutFee (uint256 _charityCut) external onlyOwner() { _charityCutPct = _charityCut; _teamFee = _teamCutPct.add(_marketingCutPct).add(_charityCut).add(_liquidityCutPct); _storedTeamFee = _teamFee; } function setLiquidityCutFee (uint256 _liquidityCut) external onlyOwner() { _liquidityCutPct = _liquidityCut; _teamFee = _teamCutPct.add(_marketingCutPct).add(_charityCutPct).add(_liquidityCut); _storedTeamFee = _teamFee; } }
NOTE Can only be called by the current owner./
function storeInCosmicVault(address cosmicVault, uint256 unlockTime) public virtual onlyOwner { require(cosmicVault != address(0), "CVOwnable: new owner is the zero address"); _previousOwner = _owner; _unlockTime = unlockTime; emit OwnershipTransferred(_previousOwner, cosmicVault); _owner = cosmicVault; }
12,158,087
pragma solidity 0.5.9; /** * https://rekt.fyi * * Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it. * * REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their * ETH balance is m times higher or their ETH is worth m times more in USD than when they received the * token, where m is a multiplier value set by users. * * copyright 2019 rekt.fyi * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Libraries */ /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. library DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } /** * External Contracts */ contract Medianizer { function peek() public view returns (bytes32, bool) {} } contract Dai { function transferFrom(address src, address dst, uint wad) public returns (bool) {} } /** * Contracts */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title https://rekt.fyi * @notice Mock the performance of your friend's ETH stack by sending them a REKT token, and add a bounty to it. * * REKT tokens are non-transferrable. Holders can only burn the token and collect the bounty once their * ETH balance is m times higher or their ETH is worth m times more in USD than when they received the * token, where m is a multiplier value set by users. */ contract RektFyi is Ownable { using DSMath for uint; /** * Storage */ struct Receiver { uint walletBalance; uint bountyETH; uint bountyDAI; uint timestamp; uint etherPrice; address payable sender; } struct Vault { uint fee; uint bountyETH; uint bountySAI; // DAI bounty sent here before the switch to MCD uint bountyDAI; // DAI bounty sent here after the switch to MCD } struct Pot { uint ETH; uint DAI; } mapping(address => Receiver) public receiver; mapping(address => uint) public balance; mapping(address => address[]) private recipients; mapping(address => Pot) public unredeemedBounty; mapping(address => Vault) public vault; Pot public bountyPot = Pot(0,0); uint public feePot = 0; bool public shutdown = false; uint public totalSupply = 0; uint public multiplier = 1300000000000000000; // 1.3x to start uint public bumpBasePrice = 10000000000000000; // 0.01 ETH uint public holdTimeCeiling = 3628800; // 6 weeks in seconds address public medianizerAddress; Medianizer oracle; bool public isMCD = false; uint public MCDswitchTimestamp = 0; address public saiAddress; address public daiAddress; Dai dai; Dai sai; constructor(address _medianizerAddress, address _saiAddress) public { medianizerAddress = _medianizerAddress; oracle = Medianizer(medianizerAddress); saiAddress = _saiAddress; dai = Dai(saiAddress); sai = dai; } /** * Constants */ string public constant name = "REKT.fyi"; string public constant symbol = "REKT"; uint8 public constant decimals = 0; uint public constant WAD = 1000000000000000000; uint public constant PRECISION = 100000000000000; // 4 orders of magnitude / decimal places uint public constant MULTIPLIER_FLOOR = 1000000000000000000; // 1x uint public constant MULTIPLIER_CEILING = 10000000000000000000; // 10x uint public constant BONUS_FLOOR = 1250000000000000000; //1.25x uint public constant BONUS_CEILING = 1800000000000000000; //1.8x uint public constant BOUNTY_BONUS_MINIMUM = 5000000000000000000; // $5 uint public constant HOLD_SCORE_CEILING = 1000000000000000000000000000; // 1 RAY uint public constant BUMP_INCREMENT = 100000000000000000; // 0.1x uint public constant HOLD_TIME_MAX = 23670000; // 9 months is the maximum the owner can set with setHoldTimeCeiling(uint) uint public constant BUMP_PRICE_MAX = 100000000000000000; //0.1 ETH is the maximum the owner can set with setBumpPrice(uint) /** * Events */ event LogVaultDeposit(address indexed addr, string indexed potType, uint value); event LogWithdraw(address indexed to, uint eth, uint sai, uint dai); event Transfer(address indexed from, address indexed to, uint tokens); event LogBump(uint indexed from, uint indexed to, uint cost, address indexed by); event LogBurn( address indexed sender, address indexed receiver, uint receivedAt, uint multiplier, uint initialETH, uint etherPrice, uint bountyETH, uint bountyDAI, uint reward ); event LogGive(address indexed sender, address indexed receiver); /** * Modifiers */ modifier shutdownNotActive() { require(shutdown == false, "shutdown activated"); _; } modifier giveRequirementsMet(address _to) { require(address(_to) != address(0), "Invalid address"); require(_to != msg.sender, "Cannot give to yourself"); require(balanceOf(_to) == 0, "Receiver already has a token"); require(_to.balance > 0, "Receiver wallet must not be empty"); _; } /** * External functions */ /// @notice Give somebody a REKT token, along with an optional bounty in ether. /// @param _to The address to send the REKT token to. function give(address _to) external payable shutdownNotActive giveRequirementsMet(_to) { if (msg.value > 0) { unredeemedBounty[msg.sender].ETH = unredeemedBounty[msg.sender].ETH.add(msg.value); bountyPot.ETH = bountyPot.ETH.add(msg.value); } receiver[_to] = Receiver(_to.balance, msg.value, 0, now, getPrice(), msg.sender); giveCommon(_to); } /// @notice Give somebody a REKT token, along with an option bounty in DAI. /// @param _to The account to send the REKT token to. /// @param _amount The amount of DAI to use as a bounty. function giveWithDAI(address _to, uint _amount) external shutdownNotActive giveRequirementsMet(_to) { if (_amount > 0) { // If the switch has already been included in this block then MCD is active, // but we won't be able to tell later if that's the case so block this tx. // Its ok for the mcd switch to occur later than this function in the same block require(MCDswitchTimestamp != now, "Cannot send DAI during the switching block"); require(dai.transferFrom(msg.sender, address(this), _amount), "DAI transfer failed"); unredeemedBounty[msg.sender].DAI = unredeemedBounty[msg.sender].DAI.add(_amount); bountyPot.DAI = bountyPot.DAI.add(_amount); } receiver[_to] = Receiver(_to.balance, 0, _amount, now, getPrice(), msg.sender); giveCommon(_to); } /// @notice Bump the multiplier up or down. /// @dev Multiplier has PRECISION precision and is rounded down unless the unrounded /// value hits the MULTIPLIER_CEILING or MULTIPLIER_FLOOR. /// @param _up Boolean representing whether the direction of the bump is up or not. function bump(bool _up) external payable shutdownNotActive { require(msg.value > 0, "Ether required"); uint initialMultiplier = multiplier; // amount = (value/price)*bonus*increment uint bumpAmount = msg.value .wdiv(bumpBasePrice) .wmul(getBonusMultiplier(msg.sender)) .wmul(BUMP_INCREMENT); if (_up) { if (multiplier.add(bumpAmount) >= MULTIPLIER_CEILING) { multiplier = MULTIPLIER_CEILING; } else { multiplier = multiplier.add(roundBumpAmount(bumpAmount)); } } else { if (multiplier > bumpAmount) { if (multiplier.sub(bumpAmount) <= MULTIPLIER_FLOOR) { multiplier = MULTIPLIER_FLOOR; } else { multiplier = multiplier.sub(roundBumpAmount(bumpAmount)); } } else { multiplier = MULTIPLIER_FLOOR; } } emit LogBump(initialMultiplier, multiplier, msg.value, msg.sender); feePot = feePot.add(msg.value); } /// @notice Burn a REKT token. If applicable, fee reward and bounty are sent to user's pots. /// REKT tokens can only be burned if the receiver has made gains >= the multiplier /// (unless we are in shutdown mode). /// @param _receiver The account that currently holds the REKT token. function burn(address _receiver) external { require(balanceOf(_receiver) == 1, "Nothing to burn"); address sender = receiver[_receiver].sender; require( msg.sender == _receiver || msg.sender == sender || (_receiver == address(this) && msg.sender == owner), "Must be token sender or receiver, or must be the owner burning REKT sent to the contract" ); if (!shutdown) { if (receiver[_receiver].walletBalance.wmul(multiplier) > _receiver.balance) { uint balanceValueThen = receiver[_receiver].walletBalance.wmul(receiver[_receiver].etherPrice); uint balanceValueNow = _receiver.balance.wmul(getPrice()); if (balanceValueThen.wmul(multiplier) > balanceValueNow) { revert("Not enough gains"); } } } balance[_receiver] = 0; totalSupply --; emit Transfer(_receiver, address(0), 1); uint feeReward = distributeBurnRewards(_receiver, sender); emit LogBurn( sender, _receiver, receiver[_receiver].timestamp, multiplier, receiver[_receiver].walletBalance, receiver[_receiver].etherPrice, receiver[_receiver].bountyETH, receiver[_receiver].bountyDAI, feeReward); } /// @notice Withdrawal of fee reward, DAI, SAI & ETH bounties for the user. /// @param _addr The account to receive the funds and whose vault the funds will be taken from. function withdraw(address payable _addr) external { require(_addr != address(this), "This contract cannot withdraw to itself"); withdrawCommon(_addr, _addr); } /// @notice Withdraw from the contract's personal vault should anyone send /// REKT to REKT.fyi with a bounty. /// @param _destination The account to receive the funds. function withdrawSelf(address payable _destination) external onlyOwner { withdrawCommon(_destination, address(this)); } /// @dev Sets a new Medianizer address in case of MakerDAO upgrades. /// @param _addr The new address. function setNewMedianizer(address _addr) external onlyOwner { require(address(_addr) != address(0), "Invalid address"); medianizerAddress = _addr; oracle = Medianizer(medianizerAddress); bytes32 price; bool ok; (price, ok) = oracle.peek(); require(ok, "Pricefeed error"); } /// @notice Sets a new DAI token address when MakerDAO upgrades to multicollateral DAI. /// @dev DAI will now be deposited into vault[user].bountyDAI for new bounties instead /// of vault[user].bountySAI. /// If setMCD(address) has been included in the block already, then a user will /// not be able to give a SAI/DAI bounty later in this block. /// We can then determine with certainty whether they sent SAI or DAI when the time /// comes to distribute it to a user's vault. /// New DAI token can only be set once; /// further changes will require shutdown and redeployment. /// @param _addr The new address. function setMCD(address _addr) external onlyOwner { require(!isMCD, "MCD has already been set"); require(address(_addr) != address(0), "Invalid address"); daiAddress = _addr; dai = Dai(daiAddress); isMCD = true; MCDswitchTimestamp = now; } /// @dev Sets a new bump price up to BUMP_PRICE_MAX. /// @param _amount The base price of bumping by BUMP_INCREMENT. function setBumpPrice(uint _amount) external onlyOwner { require(_amount > 0 && _amount <= BUMP_PRICE_MAX, "Price must not be higher than BUMP_PRICE_MAX"); bumpBasePrice = _amount; } /// @dev Sets a new hold time ceiling up to HOLD_TIME_MAX. /// @param _seconds The maximum hold time in seconds before the holdscore becomes 1 RAY. function setHoldTimeCeiling(uint _seconds) external onlyOwner { require(_seconds > 0 && _seconds <= HOLD_TIME_MAX, "Hold time must not be higher than HOLD_TIME_MAX"); holdTimeCeiling = _seconds; } /// @dev Permanent shutdown of the contract. /// No one can give or bump, everyone can burn and withdraw. function setShutdown() external onlyOwner { shutdown = true; } /** * Public functions */ /// @dev The proportion of the value of this bounty in relation to /// the value of all bounties in the system. /// @param _bounty This bounty. /// @return A uint representing the proportion of bounty as a RAY. function calculateBountyProportion(uint _bounty) public view returns (uint) { return _bounty.rdiv(potValue(bountyPot.DAI, bountyPot.ETH)); } /// @dev A score <= 1 RAY that corresponds to a duration between 0 and HOLD_SCORE_CEILING. /// @params _receivedAtTime The timestamp of the block where the user received the REKT token. /// @return A uint representing the score as a RAY. function calculateHoldScore(uint _receivedAtTime) public view returns (uint) { if (now == _receivedAtTime) { return 0; } uint timeDiff = now.sub(_receivedAtTime); uint holdScore = timeDiff.rdiv(holdTimeCeiling); if (holdScore > HOLD_SCORE_CEILING) { holdScore = HOLD_SCORE_CEILING; } return holdScore; } /// @notice Returns the REKT balance of the specified address. /// @dev Effectively a bool because the balance can only be 0 or 1. /// @param _owner The address to query the balance of. /// @return A uint representing the amount owned by the passed address. function balanceOf(address _receiver) public view returns (uint) { return balance[_receiver]; } /// @notice Returns the total value of _dai and _eth in USD. 1 DAI = $1 is assumed. /// @dev Price of ether taken from MakerDAO's Medianizer via getPrice(). /// @param _dai DAI to use in calculation. /// @param _eth Ether to use in calculation. /// @return A uint representing the total value of the inputs. function potValue(uint _dai, uint _eth) public view returns (uint) { return _dai.add(_eth.wmul(getPrice())); } /// @dev Returns the bonus multiplier represented as a WAD. /// @param _sender The address of the sender. /// @return A uint representing the bonus multiplier as a WAD. function getBonusMultiplier(address _sender) public view returns (uint) { uint bounty = potValue(unredeemedBounty[_sender].DAI, unredeemedBounty[_sender].ETH); uint bonus = WAD; if (bounty >= BOUNTY_BONUS_MINIMUM) { bonus = bounty.wdiv(potValue(bountyPot.DAI, bountyPot.ETH)).add(BONUS_FLOOR); if (bonus > BONUS_CEILING) { bonus = BONUS_CEILING; } } return bonus; } /// @dev Returns the addresses the sender has sent to as an array. /// @param _sender The address of the sender. /// @return An array of recipient addresses. function getRecipients(address _sender) public view returns (address[] memory) { return recipients[_sender]; } /// @dev Returns the price of ETH in USD as per the MakerDAO Medianizer interface. /// @return A uint representing the price of ETH in USD as a WAD. function getPrice() public view returns (uint) { bytes32 price; bool ok; (price, ok) = oracle.peek(); require(ok, "Pricefeed error"); return uint(price); } /** * Private functions */ /// @dev Common functionality for give(address) and giveWithDAI(address, uint). /// @param _to The account to send the REKT token to. function giveCommon(address _to) private { balance[_to] = 1; recipients[msg.sender].push(_to); totalSupply ++; emit Transfer(address(0), msg.sender, 1); emit Transfer(msg.sender, _to, 1); emit LogGive(msg.sender, _to); } /// @dev Assigns rewards and bounties to pots within user vaults dependant on holdScore /// and bounty proportion compared to the total bounties within the system. /// @param _receiver The account that received the REKT token. /// @param _sender The account that sent the REKT token. /// @return A uint representing the fee reward. function distributeBurnRewards(address _receiver, address _sender) private returns (uint feeReward) { feeReward = 0; uint bountyETH = receiver[_receiver].bountyETH; uint bountyDAI = receiver[_receiver].bountyDAI; uint bountyTotal = potValue(bountyDAI, bountyETH); if (bountyTotal > 0 ) { uint bountyProportion = calculateBountyProportion(bountyTotal); uint userRewardPot = bountyProportion.rmul(feePot); if (shutdown) { // in the shutdown state the holdscore isn't used feeReward = userRewardPot; } else { uint holdScore = calculateHoldScore(receiver[_receiver].timestamp); feeReward = userRewardPot.rmul(holdScore); } if (bountyETH > 0) { // subtract bounty from the senders's bounty total and the bounty pot unredeemedBounty[_sender].ETH = unredeemedBounty[_sender].ETH.sub(bountyETH); bountyPot.ETH = bountyPot.ETH.sub(bountyETH); // add bounty to receivers vault vault[_receiver].bountyETH = vault[_receiver].bountyETH.add(bountyETH); emit LogVaultDeposit(_receiver, 'bountyETH', bountyETH); } else if (bountyDAI > 0) { unredeemedBounty[_sender].DAI = unredeemedBounty[_sender].DAI.sub(bountyDAI); bountyPot.DAI = bountyPot.DAI.sub(bountyDAI); if (isMCD && receiver[_receiver].timestamp > MCDswitchTimestamp) { vault[_receiver].bountyDAI = vault[_receiver].bountyDAI.add(bountyDAI); } else { // they would have sent SAI vault[_receiver].bountySAI = vault[_receiver].bountySAI.add(bountyDAI); } emit LogVaultDeposit(_receiver, 'bountyDAI', bountyDAI); } if (feeReward > 0) { feeReward = feeReward / 2; // subtract and add feeReward for receiver vault feePot = feePot.sub(feeReward); vault[_receiver].fee = vault[_receiver].fee.add(feeReward); emit LogVaultDeposit(_receiver, 'reward', feeReward); // subtract and add feeReward for sender vault feePot = feePot.sub(feeReward); vault[_sender].fee = vault[_sender].fee.add(feeReward); emit LogVaultDeposit(_sender, 'reward', feeReward); } } return feeReward; } /// @dev Returns a rounded bump amount represented as a WAD. /// @param _amount The amount to be rounded. /// @return A uint representing the amount rounded to PRECISION as a WAD. function roundBumpAmount(uint _amount) private pure returns (uint rounded) { require(_amount >= PRECISION, "bump size too small to round"); return (_amount / PRECISION).mul(PRECISION); } /// @dev called by withdraw(address) and withdrawSelf(address) to withdraw /// fee reward, DAI, SAI & ETH bounties. /// Both params will be the same for a normal user withdrawal. /// @param _destination The account to receive the funds. /// @param _vaultOwner The vault that the funds will be taken from. function withdrawCommon(address payable _destination, address _vaultOwner) private { require(address(_destination) != address(0), "Invalid address"); uint amountETH = vault[_vaultOwner].fee.add(vault[_vaultOwner].bountyETH); uint amountDAI = vault[_vaultOwner].bountyDAI; uint amountSAI = vault[_vaultOwner].bountySAI; vault[_vaultOwner] = Vault(0,0,0,0); emit LogWithdraw(_destination, amountETH, amountSAI, amountDAI); if (amountDAI > 0) { require(dai.transferFrom(address(this), _destination, amountDAI), "DAI transfer failed"); } if (amountSAI > 0) { require(sai.transferFrom(address(this), _destination, amountSAI), "SAI transfer failed"); } if (amountETH > 0) { _destination.transfer(amountETH); } } }
Sets a new hold time ceiling up to HOLD_TIME_MAX. _seconds The maximum hold time in seconds before the holdscore becomes 1 RAY.
function setHoldTimeCeiling(uint _seconds) external onlyOwner { require(_seconds > 0 && _seconds <= HOLD_TIME_MAX, "Hold time must not be higher than HOLD_TIME_MAX"); holdTimeCeiling = _seconds; }
1,033,128
./partial_match/1/0xdDc2c27eA8a42b35B329c4e0216600F12EED13d1/sources/contracts/wombat-governance/rewarders/BoostedMultiRewarder.sol
use `max(totalShare, 1e18)` in case of overflow
function _getRewardsToDistributeFor( uint256 rewardToDistribute, uint256 lpSupply, uint256 sumOfFactors ) internal view returns (uint256 tokenPerShare, uint256 tokenPerFactorShare) { uint256 _basePartition = basePartition(); tokenPerShare = (rewardToDistribute * ACC_TOKEN_PRECISION * _basePartition) / max(lpSupply, 1e18) / TOTAL_PARTITION; if (sumOfFactors > 0) { tokenPerFactorShare = (rewardToDistribute * ACC_TOKEN_PRECISION * (TOTAL_PARTITION - _basePartition)) / sumOfFactors / TOTAL_PARTITION; } }
2,762,780
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../utils/SafeDecimalMath.sol"; import "../utils/CoreUtility.sol"; import "../interfaces/IFund.sol"; import "../interfaces/IChessSchedule.sol"; import "../interfaces/ITrancheIndex.sol"; import "../interfaces/IPrimaryMarket.sol"; interface IChessController { function getFundRelativeWeight(address account, uint256 timestamp) external view returns (uint256); } abstract contract Staking is ITrancheIndex, CoreUtility { /// @dev Reserved storage slots for future sibling contract upgrades uint256[32] private _reservedSlots; using Math for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using SafeERC20 for IERC20; event Deposited(uint256 tranche, address account, uint256 amount); event Withdrawn(uint256 tranche, address account, uint256 amount); uint256 private constant MAX_ITERATIONS = 500; uint256 private constant REWARD_WEIGHT_A = 4; uint256 private constant REWARD_WEIGHT_B = 2; uint256 private constant REWARD_WEIGHT_M = 3; IFund public immutable fund; IERC20 private immutable tokenM; IERC20 private immutable tokenA; IERC20 private immutable tokenB; /// @notice The Chess release schedule contract. IChessSchedule public immutable chessSchedule; uint256 public immutable guardedLaunchStart; uint256 private _rate; /// @notice The controller contract. IChessController public immutable chessController; /// @notice Quote asset for the exchange. Each exchange only handles one quote asset address public immutable quoteAssetAddress; /// @dev Total amount of user shares, i.e. sum of all entries in `_availableBalances` and /// `_lockedBalances`. Note that these values can be smaller than the amount of /// share tokens held by this contract, because shares locked in unsettled trades /// are not included in total supplies or any user's balance. uint256[TRANCHE_COUNT] private _totalSupplies; /// @dev Rebalance version of `_totalSupplies`. uint256 private _totalSupplyVersion; /// @dev Amount of shares that can be withdrawn or traded by each user. mapping(address => uint256[TRANCHE_COUNT]) private _availableBalances; /// @dev Amount of shares that are locked in ask orders. mapping(address => uint256[TRANCHE_COUNT]) private _lockedBalances; /// @dev Rebalance version mapping for `_availableBalances`. mapping(address => uint256) private _balanceVersions; /// @dev 1e27 * ∫(rate(t) / totalWeight(t) dt) from the latest rebalance till checkpoint. uint256 private _invTotalWeightIntegral; /// @dev Final `_invTotalWeightIntegral` before each rebalance. /// These values are accessed in a loop in `_userCheckpoint()` with bounds checking. /// So we store them in a fixed-length array, in order to make compiler-generated /// bounds checking on every access cheaper. The actual length of this array is stored in /// `_historicalIntegralSize` and should be explicitly checked when necessary. uint256[65535] private _historicalIntegrals; /// @dev Actual length of the `_historicalIntegrals` array, which always equals to the number of /// historical rebalances after `checkpoint()` is called. uint256 private _historicalIntegralSize; /// @dev Timestamp when checkpoint() is called. uint256 private _checkpointTimestamp; /// @dev Snapshot of `_invTotalWeightIntegral` per user. mapping(address => uint256) private _userIntegrals; /// @dev Mapping of account => claimable rewards. mapping(address => uint256) private _claimableRewards; constructor( address fund_, address chessSchedule_, address chessController_, address quoteAssetAddress_, uint256 guardedLaunchStart_ ) public { fund = IFund(fund_); tokenM = IERC20(IFund(fund_).tokenM()); tokenA = IERC20(IFund(fund_).tokenA()); tokenB = IERC20(IFund(fund_).tokenB()); chessSchedule = IChessSchedule(chessSchedule_); chessController = IChessController(chessController_); quoteAssetAddress = quoteAssetAddress_; _checkpointTimestamp = block.timestamp; guardedLaunchStart = guardedLaunchStart_; _rate = IChessSchedule(chessSchedule_).getRate(block.timestamp); } /// @notice Return weight of given balance with respect to rewards. /// @param amountM Amount of Token M /// @param amountA Amount of Token A /// @param amountB Amount of Token B /// @return Rewarding weight of the balance function rewardWeight( uint256 amountM, uint256 amountA, uint256 amountB ) public pure returns (uint256) { return amountM.mul(REWARD_WEIGHT_M).add(amountA.mul(REWARD_WEIGHT_A)).add( amountB.mul(REWARD_WEIGHT_B) ) / REWARD_WEIGHT_M; } function totalSupply(uint256 tranche) external view returns (uint256) { uint256 totalSupplyM = _totalSupplies[TRANCHE_M]; uint256 totalSupplyA = _totalSupplies[TRANCHE_A]; uint256 totalSupplyB = _totalSupplies[TRANCHE_B]; uint256 version = _totalSupplyVersion; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (totalSupplyM, totalSupplyA, totalSupplyB) = fund.batchRebalance( totalSupplyM, totalSupplyA, totalSupplyB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return totalSupplyM; } else if (tranche == TRANCHE_A) { return totalSupplyA; } else { return totalSupplyB; } } function availableBalanceOf(uint256 tranche, address account) external view returns (uint256) { uint256 amountM = _availableBalances[account][TRANCHE_M]; uint256 amountA = _availableBalances[account][TRANCHE_A]; uint256 amountB = _availableBalances[account][TRANCHE_B]; if (tranche == TRANCHE_M) { if (amountM == 0 && amountA == 0 && amountB == 0) return 0; } else if (tranche == TRANCHE_A) { if (amountA == 0) return 0; } else { if (amountB == 0) return 0; } uint256 version = _balanceVersions[account]; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return amountM; } else if (tranche == TRANCHE_A) { return amountA; } else { return amountB; } } function lockedBalanceOf(uint256 tranche, address account) external view returns (uint256) { uint256 amountM = _lockedBalances[account][TRANCHE_M]; uint256 amountA = _lockedBalances[account][TRANCHE_A]; uint256 amountB = _lockedBalances[account][TRANCHE_B]; if (tranche == TRANCHE_M) { if (amountM == 0 && amountA == 0 && amountB == 0) return 0; } else if (tranche == TRANCHE_A) { if (amountA == 0) return 0; } else { if (amountB == 0) return 0; } uint256 version = _balanceVersions[account]; uint256 rebalanceSize = fund.getRebalanceSize(); if (version < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, version, rebalanceSize ); } if (tranche == TRANCHE_M) { return amountM; } else if (tranche == TRANCHE_A) { return amountA; } else { return amountB; } } function balanceVersion(address account) external view returns (uint256) { return _balanceVersions[account]; } /// @dev Deposit to get rewards /// @param tranche Tranche of the share /// @param amount The amount to deposit function deposit(uint256 tranche, uint256 amount) public { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(msg.sender, rebalanceSize); if (tranche == TRANCHE_M) { tokenM.safeTransferFrom(msg.sender, address(this), amount); } else if (tranche == TRANCHE_A) { tokenA.safeTransferFrom(msg.sender, address(this), amount); } else { tokenB.safeTransferFrom(msg.sender, address(this), amount); } _availableBalances[msg.sender][tranche] = _availableBalances[msg.sender][tranche].add( amount ); _totalSupplies[tranche] = _totalSupplies[tranche].add(amount); emit Deposited(tranche, msg.sender, amount); } /// @dev Claim settled Token M from the primary market and deposit to get rewards /// @param primaryMarket The primary market to claim shares from function claimAndDeposit(address primaryMarket) external { (uint256 createdShares, ) = IPrimaryMarket(primaryMarket).claim(msg.sender); deposit(TRANCHE_M, createdShares); } /// @dev Withdraw /// @param tranche Tranche of the share /// @param amount The amount to deposit function withdraw(uint256 tranche, uint256 amount) external { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(msg.sender, rebalanceSize); _availableBalances[msg.sender][tranche] = _availableBalances[msg.sender][tranche].sub( amount, "Insufficient balance to withdraw" ); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); if (tranche == TRANCHE_M) { tokenM.safeTransfer(msg.sender, amount); } else if (tranche == TRANCHE_A) { tokenA.safeTransfer(msg.sender, amount); } else { tokenB.safeTransfer(msg.sender, amount); } emit Withdrawn(tranche, msg.sender, amount); } /// @notice Transform share balance to a given rebalance version, or to the latest version /// if `targetVersion` is zero. /// @param account Account of the balance to rebalance /// @param targetVersion The target rebalance version, or zero for the latest version function refreshBalance(address account, uint256 targetVersion) external { uint256 rebalanceSize = fund.getRebalanceSize(); if (targetVersion == 0) { targetVersion = rebalanceSize; } else { require(targetVersion <= rebalanceSize, "Target version out of bound"); } _checkpoint(rebalanceSize); _userCheckpoint(account, targetVersion); } /// @notice Return claimable rewards of an account till now. /// /// This function should be call as a "view" function off-chain to get /// the return value, e.g. using `contract.claimableRewards.call(account)` in web3 /// or `contract.callStatic.claimableRewards(account)` in ethers.js. /// @param account Address of an account /// @return Amount of claimable rewards function claimableRewards(address account) external returns (uint256) { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); return _claimableRewards[account]; } /// @notice Claim the rewards for an account. /// @param account Account to claim its rewards function claimRewards(address account) external { require( block.timestamp >= guardedLaunchStart + 15 days, "Cannot claim during guarded launch" ); uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _claim(account); } /// @dev Transfer shares from the sender to the contract internally /// @param tranche Tranche of the share /// @param sender Sender address /// @param amount The amount to transfer function _tradeAvailable( uint256 tranche, address sender, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(sender, rebalanceSize); _availableBalances[sender][tranche] = _availableBalances[sender][tranche].sub(amount); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); } function _rebalanceAndClearTrade( address account, uint256 amountM, uint256 amountA, uint256 amountB, uint256 amountVersion ) internal returns ( uint256, uint256, uint256 ) { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); if (amountVersion < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, amountVersion, rebalanceSize ); } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; if (amountM > 0) { available[TRANCHE_M] = available[TRANCHE_M].add(amountM); _totalSupplies[TRANCHE_M] = _totalSupplies[TRANCHE_M].add(amountM); } if (amountA > 0) { available[TRANCHE_A] = available[TRANCHE_A].add(amountA); _totalSupplies[TRANCHE_A] = _totalSupplies[TRANCHE_A].add(amountA); } if (amountB > 0) { available[TRANCHE_B] = available[TRANCHE_B].add(amountB); _totalSupplies[TRANCHE_B] = _totalSupplies[TRANCHE_B].add(amountB); } return (amountM, amountA, amountB); } function _lock( uint256 tranche, address account, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _availableBalances[account][tranche] = _availableBalances[account][tranche].sub( amount, "Insufficient balance to lock" ); _lockedBalances[account][tranche] = _lockedBalances[account][tranche].add(amount); } function _rebalanceAndUnlock( address account, uint256 amountM, uint256 amountA, uint256 amountB, uint256 amountVersion ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); if (amountVersion < rebalanceSize) { (amountM, amountA, amountB) = fund.batchRebalance( amountM, amountA, amountB, amountVersion, rebalanceSize ); } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; uint256[TRANCHE_COUNT] storage locked = _lockedBalances[account]; if (amountM > 0) { available[TRANCHE_M] = available[TRANCHE_M].add(amountM); locked[TRANCHE_M] = locked[TRANCHE_M].sub(amountM); } if (amountA > 0) { available[TRANCHE_A] = available[TRANCHE_A].add(amountA); locked[TRANCHE_A] = locked[TRANCHE_A].sub(amountA); } if (amountB > 0) { available[TRANCHE_B] = available[TRANCHE_B].add(amountB); locked[TRANCHE_B] = locked[TRANCHE_B].sub(amountB); } } function _tradeLocked( uint256 tranche, address account, uint256 amount ) internal { uint256 rebalanceSize = fund.getRebalanceSize(); _checkpoint(rebalanceSize); _userCheckpoint(account, rebalanceSize); _lockedBalances[account][tranche] = _lockedBalances[account][tranche].sub(amount); _totalSupplies[tranche] = _totalSupplies[tranche].sub(amount); } /// @dev Transfer claimable rewards to an account. Rewards since the last user checkpoint /// is not included. This function should always be called after `_userCheckpoint()`, /// in order for the user to get all rewards till now. /// @param account Address of the account function _claim(address account) internal { chessSchedule.mint(account, _claimableRewards[account]); _claimableRewards[account] = 0; } /// @dev Transform total supplies to the latest rebalance version and make a global reward checkpoint. /// @param rebalanceSize The number of existing rebalances. It must be the same as /// `fund.getRebalanceSize()`. function _checkpoint(uint256 rebalanceSize) private { uint256 timestamp = _checkpointTimestamp; if (timestamp >= block.timestamp) { return; } uint256 integral = _invTotalWeightIntegral; uint256 endWeek = _endOfWeek(timestamp); uint256 weeklyPercentage = chessController.getFundRelativeWeight(address(this), endWeek - 1 weeks); uint256 version = _totalSupplyVersion; uint256 rebalanceTimestamp; if (version < rebalanceSize) { rebalanceTimestamp = fund.getRebalanceTimestamp(version); } else { rebalanceTimestamp = type(uint256).max; } uint256 rate = _rate; uint256 totalSupplyM = _totalSupplies[TRANCHE_M]; uint256 totalSupplyA = _totalSupplies[TRANCHE_A]; uint256 totalSupplyB = _totalSupplies[TRANCHE_B]; uint256 weight = rewardWeight(totalSupplyM, totalSupplyA, totalSupplyB); uint256 timestamp_ = timestamp; // avoid stack too deep for (uint256 i = 0; i < MAX_ITERATIONS && timestamp_ < block.timestamp; i++) { uint256 endTimestamp = rebalanceTimestamp.min(endWeek).min(block.timestamp); if (weight > 0) { integral = integral.add( rate .mul(endTimestamp.sub(timestamp_)) .multiplyDecimal(weeklyPercentage) .divideDecimalPrecise(weight) ); } if (endTimestamp == rebalanceTimestamp) { uint256 oldSize = _historicalIntegralSize; _historicalIntegrals[oldSize] = integral; _historicalIntegralSize = oldSize + 1; integral = 0; (totalSupplyM, totalSupplyA, totalSupplyB) = fund.doRebalance( totalSupplyM, totalSupplyA, totalSupplyB, version ); version++; weight = rewardWeight(totalSupplyM, totalSupplyA, totalSupplyB); if (version < rebalanceSize) { rebalanceTimestamp = fund.getRebalanceTimestamp(version); } else { rebalanceTimestamp = type(uint256).max; } } if (endTimestamp == endWeek) { rate = chessSchedule.getRate(endWeek); weeklyPercentage = chessController.getFundRelativeWeight(address(this), endWeek); endWeek += 1 weeks; } timestamp_ = endTimestamp; } _checkpointTimestamp = block.timestamp; _invTotalWeightIntegral = integral; if (_rate != rate) { _rate = rate; } if (_totalSupplyVersion != rebalanceSize) { _totalSupplies[TRANCHE_M] = totalSupplyM; _totalSupplies[TRANCHE_A] = totalSupplyA; _totalSupplies[TRANCHE_B] = totalSupplyB; _totalSupplyVersion = rebalanceSize; } } /// @dev Transform a user's balance to a given rebalance version and update this user's rewards. /// /// In most cases, the target version is the latest version and this function cumulates /// rewards till now. When this function is called from `refreshBalance()`, /// `targetVersion` can be an older version, in which case rewards are cumulated till /// the end of that version (i.e. timestamp of the transaction triggering the rebalance /// with index `targetVersion`). /// /// This function should always be called after `_checkpoint()` is called, so that /// the global reward checkpoint is guarenteed up to date. /// @param account Account to update /// @param targetVersion The target rebalance version function _userCheckpoint(address account, uint256 targetVersion) private { uint256 oldVersion = _balanceVersions[account]; if (oldVersion > targetVersion) { return; } uint256 userIntegral = _userIntegrals[account]; uint256 integral; // This scope is to avoid the "stack too deep" error. { // We assume that this function is always called immediately after `_checkpoint()`, // which guarantees that `_historicalIntegralSize` equals to the number of historical // rebalances. uint256 rebalanceSize = _historicalIntegralSize; integral = targetVersion == rebalanceSize ? _invTotalWeightIntegral : _historicalIntegrals[targetVersion]; } if (userIntegral == integral && oldVersion == targetVersion) { // Return immediately when the user's rewards have already been updated to // the target version. return; } uint256[TRANCHE_COUNT] storage available = _availableBalances[account]; uint256[TRANCHE_COUNT] storage locked = _lockedBalances[account]; uint256 availableM = available[TRANCHE_M]; uint256 availableA = available[TRANCHE_A]; uint256 availableB = available[TRANCHE_B]; uint256 lockedM = locked[TRANCHE_M]; uint256 lockedA = locked[TRANCHE_A]; uint256 lockedB = locked[TRANCHE_B]; uint256 rewards = _claimableRewards[account]; for (uint256 i = oldVersion; i < targetVersion; i++) { uint256 weight = rewardWeight( availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB) ); rewards = rewards.add( weight.multiplyDecimalPrecise(_historicalIntegrals[i].sub(userIntegral)) ); if (availableM != 0 || availableA != 0 || availableB != 0) { (availableM, availableA, availableB) = fund.doRebalance( availableM, availableA, availableB, i ); } if (lockedM != 0 || lockedA != 0 || lockedB != 0) { (lockedM, lockedA, lockedB) = fund.doRebalance(lockedM, lockedA, lockedB, i); } userIntegral = 0; } uint256 weight = rewardWeight(availableM.add(lockedM), availableA.add(lockedA), availableB.add(lockedB)); rewards = rewards.add(weight.multiplyDecimalPrecise(integral.sub(userIntegral))); address account_ = account; // Fix the "stack too deep" error _claimableRewards[account_] = rewards; _userIntegrals[account_] = integral; if (oldVersion < targetVersion) { if (available[TRANCHE_M] != availableM) { available[TRANCHE_M] = availableM; } if (available[TRANCHE_A] != availableA) { available[TRANCHE_A] = availableA; } if (available[TRANCHE_B] != availableB) { available[TRANCHE_B] = availableB; } if (locked[TRANCHE_M] != lockedM) { locked[TRANCHE_M] = lockedM; } if (locked[TRANCHE_A] != lockedA) { locked[TRANCHE_A] = lockedA; } if (locked[TRANCHE_B] != lockedB) { locked[TRANCHE_B] = lockedB; } _balanceVersions[account_] = targetVersion; } } }
Claim settled Token M from the primary market and deposit to get rewards primaryMarket The primary market to claim shares from
function claimAndDeposit(address primaryMarket) external { (uint256 createdShares, ) = IPrimaryMarket(primaryMarket).claim(msg.sender); deposit(TRANCHE_M, createdShares); }
12,885,406
pragma solidity ^0.4.17; // File: contracts/helpers/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Constructor sets the original owner of the contract to the * sender account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any other account other than owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/helpers/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Interface.sol contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); } // File: contracts/token/BaseToken.sol contract BaseToken is ERC20Interface { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; /** * @dev Obtain total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is BaseToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(_to != address(0)); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: contracts/token/CappedToken.sol contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/helpers/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/token/PausableToken.sol /** * @title Pausable token * @dev BaseToken modified with pausable transfers. **/ contract PausableToken is BaseToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/token/SignedTransferToken.sol /** * @title SignedTransferToken * @dev The SignedTransferToken enables collection of fees for token transfers * in native token currency. User will provide a signature that allows the third * party to settle the transaction in his name and collect fee for provided * serivce. */ contract SignedTransferToken is BaseToken { event TransferPreSigned( address indexed from, address indexed to, address indexed settler, uint256 value, uint256 fee ); event TransferPreSignedMany( address indexed from, address indexed settler, uint256 value, uint256 fee ); // Mapping of already executed settlements for a given address mapping(address => mapping(bytes32 => bool)) executedSettlements; /** * @dev Will settle a pre-signed transfer */ function transferPreSigned(address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public returns (bool) { uint256 total = _value.add(_fee); bytes32 calcHash = calculateHash(_from, _to, _value, _fee, _nonce); require(_to != address(0)); require(isValidSignature(_from, calcHash, _v, _r, _s)); require(balances[_from] >= total); require(!executedSettlements[_from][calcHash]); executedSettlements[_from][calcHash] = true; // Move tokens balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); // Move fee balances[_from] = balances[_from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); Transfer(_from, msg.sender, _fee); TransferPreSigned(_from, _to, msg.sender, _value, _fee); return true; } /** * @dev Settle multiple transactions in a single call. Please note that * should a single one fail the full state will be reverted. Your client * implementation should always first check for balances, correct signatures * and any other conditions that might result in failed transaction. */ function transferPreSignedBulk(address[] _from, address[] _to, uint256[] _values, uint256[] _fees, uint256[] _nonces, uint8[] _v, bytes32[] _r, bytes32[] _s) public returns (bool) { // Make sure all the arrays are of the same length require(_from.length == _to.length && _to.length ==_values.length && _values.length == _fees.length && _fees.length == _nonces.length && _nonces.length == _v.length && _v.length == _r.length && _r.length == _s.length); for(uint i; i < _from.length; i++) { transferPreSigned(_from[i], _to[i], _values[i], _fees[i], _nonces[i], _v[i], _r[i], _s[i]); } return true; } function transferPreSignedMany(address _from, address[] _tos, uint256[] _values, uint256 _fee, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public returns (bool) { require(_tos.length == _values.length); uint256 total = getTotal(_tos, _values, _fee); bytes32 calcHash = calculateManyHash(_from, _tos, _values, _fee, _nonce); require(isValidSignature(_from, calcHash, _v, _r, _s)); require(balances[_from] >= total); require(!executedSettlements[_from][calcHash]); executedSettlements[_from][calcHash] = true; // transfer to each recipient and take fee at the end for(uint i; i < _tos.length; i++) { // Move tokens balances[_from] = balances[_from].sub(_values[i]); balances[_tos[i]] = balances[_tos[i]].add(_values[i]); Transfer(_from, _tos[i], _values[i]); } // Move fee balances[_from] = balances[_from].sub(_fee); balances[msg.sender] = balances[msg.sender].add(_fee); Transfer(_from, msg.sender, _fee); TransferPreSignedMany(_from, msg.sender, total, _fee); return true; } function getTotal(address[] _tos, uint256[] _values, uint256 _fee) private view returns (uint256) { uint256 total = _fee; for(uint i; i < _tos.length; i++) { total = total.add(_values[i]); // sum of all the values + fee require(_tos[i] != address(0)); // check that the recipient is a valid address } return total; } /** * @dev Calculates transfer hash for transferPreSignedMany */ function calculateManyHash(address _from, address[] _tos, uint256[] _values, uint256 _fee, uint256 _nonce) public view returns (bytes32) { return keccak256(uint256(1), address(this), _from, _tos, _values, _fee, _nonce); } /** * @dev Calculates transfer hash. */ function calculateHash(address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce) public view returns (bytes32) { return keccak256(uint256(0), address(this), _from, _to, _value, _fee, _nonce); } /** * @dev Validates the signature */ function isValidSignature(address _signer, bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (bool) { return _signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", _hash), _v, _r, _s ); } /** * @dev Allows you to check whether a certain transaction has been already * settled or not. */ function isTransactionAlreadySettled(address _from, bytes32 _calcHash) public view returns (bool) { return executedSettlements[_from][_calcHash]; } } // File: contracts/token/PausableSignedTransferToken.sol contract PausableSignedTransferToken is SignedTransferToken, PausableToken { function transferPreSigned(address _from, address _to, uint256 _value, uint256 _fee, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused returns (bool) { return super.transferPreSigned(_from, _to, _value, _fee, _nonce, _v, _r, _s); } function transferPreSignedBulk(address[] _from, address[] _to, uint256[] _values, uint256[] _fees, uint256[] _nonces, uint8[] _v, bytes32[] _r, bytes32[] _s) public whenNotPaused returns (bool) { return super.transferPreSignedBulk(_from, _to, _values, _fees, _nonces, _v, _r, _s); } function transferPreSignedMany(address _from, address[] _tos, uint256[] _values, uint256 _fee, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public whenNotPaused returns (bool) { return super.transferPreSignedMany(_from, _tos, _values, _fee, _nonce, _v, _r, _s); } } // File: contracts/FourToken.sol contract FourToken is CappedToken, PausableSignedTransferToken { string public name = 'The 4th Pillar Token'; string public symbol = 'FOUR'; uint256 public decimals = 18; // Max supply of 400 million uint256 public maxSupply = 400000000 * 10**decimals; function FourToken() CappedToken(maxSupply) public { paused = true; } // @dev Recover any mistakenly sent ERC20 tokens to the Token address function recoverERC20Tokens(address _erc20, uint256 _amount) public onlyOwner { ERC20Interface(_erc20).transfer(msg.sender, _amount); } } // File: contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale { using SafeMath for uint256; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param tokens amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens); // The token being sold MintableToken public token; // start and end timestamps in UNIX. uint256 public startTime; uint256 public endTime; // how many tokens does a buyer get per wei uint256 public rate; // wallet where funds are forwarded address public wallet; // amount of raised money in wei uint256 public weiRaised; // amount of sold tokens uint256 public tokensSold; function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = MintableToken(_token); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokens); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } // File: contracts/crowdsale/FinalizableCrowdsale.sol contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; event Finalized(); bool public isFinalized = false; /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } // File: contracts/crowdsale/TokenCappedCrowdsale.sol contract TokenCappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenCap; function TokenCappedCrowdsale(uint256 _tokenCap) public { require(_tokenCap > 0); tokenCap = _tokenCap; } function isCapReached() public view returns (bool) { return tokensSold >= tokenCap; } function hasEnded() public view returns (bool) { return isCapReached() || super.hasEnded(); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = tokensSold.add(getTokenAmount(msg.value)) <= tokenCap; return withinCap && super.validPurchase(); } } // File: contracts/crowdsale/WhitelistCrowdsale.sol contract WhitelistCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; event WhitelistUpdated(uint256 timestamp, string operation, uint256 totalAddresses); // Mapping of whitelisted addresses mapping(address => bool) whitelisted; // Total count of whitelisted participants uint256 public whitelistedCount; function isWhitelisted(address _addr) public view returns (bool) { return whitelisted[_addr]; } function addAddress(address _addr) external onlyOwner { whitelisted[_addr] = true; whitelistedCount++; WhitelistUpdated(block.timestamp, "Added", whitelistedCount); } function addAddresses(address[] _addrs) external onlyOwner { for (uint256 i = 0; i < _addrs.length; i++) { whitelisted[_addrs[i]] = true; whitelistedCount++; } WhitelistUpdated(block.timestamp, "Added", whitelistedCount); } function removeAddress(address _addr) external onlyOwner { whitelisted[_addr] = false; whitelistedCount--; WhitelistUpdated(block.timestamp, "Removed", whitelistedCount); } function removeAddresses(address[] _addrs) external onlyOwner { for (uint256 i = 0; i < _addrs.length; i++) { whitelisted[_addrs[i]] = false; whitelistedCount--; } WhitelistUpdated(block.timestamp, "Removed", whitelistedCount); } function validPurchase() internal view returns (bool) { return isWhitelisted(msg.sender) && super.validPurchase(); } } // File: contracts/FourCrowdsale.sol contract FourCrowdsale is TokenCappedCrowdsale, WhitelistCrowdsale, FinalizableCrowdsale { event RateChanged(uint256 newRate, string name); uint256 private constant E18 = 10**18; // Max tokens sold = 152 million uint256 private TOKEN_SALE_CAP = 152000000 * E18; uint256 public constant TEAM_TOKENS = 50000000 * E18; address public constant TEAM_ADDRESS = 0x3EC2fC20c04656F4B0AA7372258A36FAfB1EF427; // Vault tokens have been pre-minted // uint256 public constant VAULT_TOKENS = 152000000 * E18; // address public constant VAULT_ADDRESS = 0x545baa8e4Fff675711CB92Af33e5850aDD913b76; uint256 public constant ADVISORS_AND_CONTRIBUTORS_TOKENS = 39000000 * E18; address public constant ADVISORS_AND_CONTRIBUTORS_ADDRESS = 0x90adab6891514DC24411B9Adf2e11C0eD7739999; // Bounty tokens have been pre-minted // uint256 public constant BOUNTY_TOKENS = 7000000 * E18; // address public constant BOUNTY_ADDRESS = 0x18f260a71c282bc4d5fe4ee1187658a06e9d1a59; // Unsold tokens will be transfered to the VAULT address public constant UNSOLD_ADDRESS = 0x4eC155995211C8639375Ae3106187bff3FF5DB46; // Bonus amount. The first 24h there will be a bonus of 10% uint256 public bonus; function FourCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _bonus, address _wallet, address _token) TokenCappedCrowdsale(TOKEN_SALE_CAP) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) public { bonus = _bonus; } function setCrowdsaleWallet(address _wallet) public onlyOwner { require(_wallet != address(0)); wallet = _wallet; } function changeStartAndEndTime(uint256 _newStartTime, uint256 _newEndTime) public onlyOwner { require(_newStartTime >= now); require(_newEndTime >= _newStartTime); startTime = _newStartTime; endTime = _newEndTime; } function changeEndTime(uint256 _newEndTime) public onlyOwner { require(_newEndTime > startTime); endTime = _newEndTime; } function setRate(uint256 _rate) public onlyOwner { require(now < startTime); // cant change once the sale has started rate = _rate; RateChanged(_rate, 'rate'); } function setBonus(uint256 _bonus) public onlyOwner { require(now < startTime); // cant change once the sale has started bonus = _bonus; RateChanged(_bonus, 'bonus'); } function processPresaleOrEarlyContributors(address[] _beneficiaries, uint256[] _tokenAmounts) public onlyOwner { // Cant process anymore after the crowdsale has finished require(now <= endTime); for (uint i = 0; i < _beneficiaries.length; i++) { // update state tokensSold = tokensSold.add(_tokenAmounts[i]); token.mint(_beneficiaries[i], _tokenAmounts[i]); TokenPurchase(msg.sender, _beneficiaries[i], 0, _tokenAmounts[i]); } } function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { uint256 actualRate = rate; // For the first 24 hours of the crowdsale there is a bonus if (now <= startTime + 1 days) { actualRate = actualRate.add(bonus); } return weiAmount.mul(actualRate); } function finalization() internal { // transfer tokens to team token.mint(TEAM_ADDRESS, TEAM_TOKENS); // transfer tokens to the 4th pillar vault // already minted before crowdsale // token.mint(VAULT_ADDRESS, VAULT_TOKENS); // transfer advisors and contributors tokens token.mint(ADVISORS_AND_CONTRIBUTORS_ADDRESS, ADVISORS_AND_CONTRIBUTORS_TOKENS); // transfer bounty tokens // already minted before crowdsale //token.mint(BOUNTY_ADDRESS, BOUNTY_TOKENS); // transfer all unsold tokens to the unsold address for the airdrop uint256 unsold_tokens = TOKEN_SALE_CAP - tokensSold; token.mint(UNSOLD_ADDRESS, unsold_tokens); // finish minting token.finishMinting(); // release ownership back to owner token.transferOwnership(owner); // finalize super.finalization(); } // @dev Recover any mistakenly sent ERC20 tokens to the Crowdsale address function recoverERC20Tokens(address _erc20, uint256 _amount) public onlyOwner { ERC20Interface(_erc20).transfer(msg.sender, _amount); } function releaseTokenOwnership() public onlyOwner { token.transferOwnership(owner); } }
Validates the signature/
function isValidSignature(address _signer, bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (bool) { return _signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", _hash), _v, _r, _s ); }
6,349,397
./full_match/1/0x6208410d391deb5A042632865833C56326C83CBa/sources/contracts/v4/extensions/AccessControl.sol
Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role./
function grantRole(bytes32 role, address account) public onlyAdmin { _grantRole(role, account); }
17,184,615
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title Token Distributor Contract /// @author /// @notice distributes donations or tips contract TokenDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Emitted when a token share has been distributed event tokenShareCompleted( address token, uint256 indexed amount, address indexed from, bytes32 indexed room ); /// @notice Emitted when an ETH share has been distributed event ethShareCompleted( uint256 indexed amount, address indexed from, bytes32 indexed room ); modifier hasValidUsers(address[] memory users) { require(users.length > 0 && users.length < 256, "Invalid users array"); _; } modifier hasEnoughBalance(uint256 balance, uint256 amount) { require(balance >= amount, "Not enough token balance"); _; } /// @notice Splits ETH that is 'Tipped' /// @param users an ordered list of users addresses function splitEth(address[] memory users, string memory _room) public payable hasValidUsers(users) { bytes32 room = keccak256(abi.encodePacked(_room)); _handleDistribution(users, msg.value, address(this), address(0), false); emit ethShareCompleted(msg.value, msg.sender, room); } /// @notice Splits token from user /// @param users an ordered list of users addresses /// @param amount the total amount to be split /// @param token the token to be split function splitTokenFromUser( address[] memory users, uint256 amount, IERC20 token, string memory _room ) public hasValidUsers(users) hasEnoughBalance(token.balanceOf(msg.sender), amount) { bytes32 room = keccak256(abi.encodePacked(_room)); _handleDistribution(users, amount, msg.sender, address(token), true); emit tokenShareCompleted(address(token), amount, msg.sender, room); } /// @notice Handles the distribution /// @dev called internally by contract function /// @return share of the distribution function _handleDistribution( address[] memory users, uint256 amount, address from, address token, bool isToken ) private returns (uint256 share) { uint256 totalMembers = users.length; share = amount.div(totalMembers); for (uint256 i = 0; i < users.length; i++) { // if split token is requested, split from specified user if (isToken) { if (from == address(this)) { IERC20(token).safeTransfer(users[i], share); } else { IERC20(token).safeTransferFrom(from, users[i], share); } } else { (bool sent, bytes memory data) = users[i].call{value: share}( "" ); require(sent, "Failed to send Ether"); } } } }
Handles the distribution called internally by contract function return share of the distribution if split token is requested, split from specified user
function _handleDistribution( address[] memory users, uint256 amount, address from, address token, bool isToken ) private returns (uint256 share) { uint256 totalMembers = users.length; share = amount.div(totalMembers); for (uint256 i = 0; i < users.length; i++) { if (isToken) { if (from == address(this)) { IERC20(token).safeTransfer(users[i], share); IERC20(token).safeTransferFrom(from, users[i], share); } "" ); require(sent, "Failed to send Ether"); } } }
1,041,308
./full_match/3/0x8cbA3Ef8211B92E086Ea8B131DE8eF152D162e5e/sources/browser/ERC721.sol
Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings./ Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll( address owner, address operator ) public override view returns (bool) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); }
8,236,819
//Address: 0xe0c72452740414d861606a44ccd5ea7f96488278 //Contract name: EncryptoTelToken //Balance: 0 Ether //Verification Date: 6/6/2017 //Transacion Count: 6610 // CODE STARTS HERE pragma solidity ^0.4.10; // ---------------------------------------------------------------------------- // The EncryptoTel smart contract - provided by Incent - join us on slack; // http://incentinvites.herokuapp.com/ // // A collaboration between Incent, Bok and EncryptoTel :) // // Enjoy. (c) Incent Loyalty Pty Ltd and Bok Consulting Pty Ltd 2017. // The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Contract configuration // ---------------------------------------------------------------------------- contract TokenConfig { string public constant symbol = "ETT"; string public constant name = "EncryptoTel Token"; uint8 public constant decimals = 8; // 8 decimals, same as tokens on Waves uint256 public constant TOTALSUPPLY = 7766398700000000; } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract ERC20Interface { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender != newOwner) throw; OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ---------------------------------------------------------------------------- // WavesEthereumSwap functionality // ---------------------------------------------------------------------------- contract WavesEthereumSwap is Owned, ERC20Interface { event WavesTransfer(address indexed _from, string wavesAddress, uint256 amount); function moveToWaves(string wavesAddress, uint256 amount) { if (!transfer(owner, amount)) throw; WavesTransfer(msg.sender, wavesAddress, amount); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract EncryptoTelToken is TokenConfig, WavesEthereumSwap { // ------------------------------------------------------------------------ // Balances for each account // ------------------------------------------------------------------------ mapping(address => uint256) balances; // ------------------------------------------------------------------------ // Owner of account approves the transfer of an amount to another account // ------------------------------------------------------------------------ mapping(address => mapping (address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function EncryptoTelToken() Owned() TokenConfig() { totalSupply = TOTALSUPPLY; balances[owner] = TOTALSUPPLY; } // ------------------------------------------------------------------------ // Get the account balance of another account with address _owner // ------------------------------------------------------------------------ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner's account to another account // ------------------------------------------------------------------------ function transfer( address _to, uint256 _amount ) returns (bool success) { if (balances[msg.sender] >= _amount // User has balance && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the // current allowance with _value. // ------------------------------------------------------------------------ function approve( address _spender, uint256 _amount ) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner's // balance to another account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount // From a/c has balance && allowed[_from][msg.sender] >= _amount // Transfer approved && _amount > 0 // Non-zero transfer && balances[_to] + _amount > balances[_to] // Overflow check ) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance( address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------------------------------ // Transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token( address tokenAddress, uint256 amount ) onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } // ------------------------------------------------------------------------ // Don't accept ethers // ------------------------------------------------------------------------ function () { throw; } }
------------------------------------------------------------------------ Returns the amount of tokens approved by the owner that can be transferred to the spender's account ------------------------------------------------------------------------
function allowance( address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
1,046,227
./full_match/1/0x9b20bAd4B7759ECa269a4B2607A2999f39820698/sources/contracts/LSDai.sol
Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance(address owner, address spender, uint256 amount) internal { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } }
2,904,956
pragma solidity ^0.4.19; contract ADM312 { address public COO; address public CTO; address public CFO; address private coreAddress; address public logicAddress; address public superAddress; modifier onlyAdmin() { require(msg.sender == COO || msg.sender == CTO || msg.sender == CFO); _; } modifier onlyContract() { require(msg.sender == coreAddress || msg.sender == logicAddress || msg.sender == superAddress); _; } modifier onlyContractAdmin() { require(msg.sender == coreAddress || msg.sender == logicAddress || msg.sender == superAddress || msg.sender == COO || msg.sender == CTO || msg.sender == CFO); _; } function transferAdmin(address _newAdminAddress1, address _newAdminAddress2) public onlyAdmin { if(msg.sender == COO) { CTO = _newAdminAddress1; CFO = _newAdminAddress2; } if(msg.sender == CTO) { COO = _newAdminAddress1; CFO = _newAdminAddress2; } if(msg.sender == CFO) { COO = _newAdminAddress1; CTO = _newAdminAddress2; } } function transferContract(address _newCoreAddress, address _newLogicAddress, address _newSuperAddress) external onlyAdmin { coreAddress = _newCoreAddress; logicAddress = _newLogicAddress; superAddress = _newSuperAddress; SetCoreInterface(_newLogicAddress).setCoreContract(_newCoreAddress); SetCoreInterface(_newSuperAddress).setCoreContract(_newCoreAddress); } } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } contract SetCoreInterface { function setCoreContract(address _neWCoreAddress) external; } contract CaData is ADM312, ERC721 { function CaData() public { COO = msg.sender; CTO = msg.sender; CFO = msg.sender; createCustomAtom(0,0,4,0,0,0,0); } function kill() external { require(msg.sender == COO); selfdestruct(msg.sender); } function() public payable{} uint public randNonce = 0; struct Atom { uint64 dna; uint8 gen; uint8 lev; uint8 cool; uint32 sons; uint64 fath; uint64 moth; uint128 isRent; uint128 isBuy; uint32 isReady; } Atom[] public atoms; mapping (uint64 => bool) public dnaExist; mapping (address => bool) public bonusReceived; mapping (address => uint) public ownerAtomsCount; mapping (uint => address) public atomOwner; event NewWithdraw(address sender, uint balance); function createCustomAtom(uint64 _dna, uint8 _gen, uint8 _lev, uint8 _cool, uint128 _isRent, uint128 _isBuy, uint32 _isReady) public onlyAdmin { require(dnaExist[_dna]==false && _cool+_lev>=4); Atom memory newAtom = Atom(_dna, _gen, _lev, _cool, 0, 2**50, 2**50, _isRent, _isBuy, _isReady); uint id = atoms.push(newAtom) - 1; atomOwner[id] = msg.sender; ownerAtomsCount[msg.sender]++; dnaExist[_dna] = true; } function withdrawBalance() public payable onlyAdmin { NewWithdraw(msg.sender, address(this).balance); CFO.transfer(address(this).balance); } function incRandNonce() external onlyContract { randNonce++; } function setDnaExist(uint64 _dna, bool _newDnaLocking) external onlyContractAdmin { dnaExist[_dna] = _newDnaLocking; } function setBonusReceived(address _add, bool _newBonusLocking) external onlyContractAdmin { bonusReceived[_add] = _newBonusLocking; } function setOwnerAtomsCount(address _owner, uint _newCount) external onlyContract { ownerAtomsCount[_owner] = _newCount; } function setAtomOwner(uint _atomId, address _owner) external onlyContract { atomOwner[_atomId] = _owner; } function pushAtom(uint64 _dna, uint8 _gen, uint8 _lev, uint8 _cool, uint32 _sons, uint64 _fathId, uint64 _mothId, uint128 _isRent, uint128 _isBuy, uint32 _isReady) external onlyContract returns (uint id) { Atom memory newAtom = Atom(_dna, _gen, _lev, _cool, _sons, _fathId, _mothId, _isRent, _isBuy, _isReady); id = atoms.push(newAtom) -1; } function setAtomDna(uint _atomId, uint64 _dna) external onlyAdmin { atoms[_atomId].dna = _dna; } function setAtomGen(uint _atomId, uint8 _gen) external onlyAdmin { atoms[_atomId].gen = _gen; } function setAtomLev(uint _atomId, uint8 _lev) external onlyContract { atoms[_atomId].lev = _lev; } function setAtomCool(uint _atomId, uint8 _cool) external onlyContract { atoms[_atomId].cool = _cool; } function setAtomSons(uint _atomId, uint32 _sons) external onlyContract { atoms[_atomId].sons = _sons; } function setAtomFath(uint _atomId, uint64 _fath) external onlyContract { atoms[_atomId].fath = _fath; } function setAtomMoth(uint _atomId, uint64 _moth) external onlyContract { atoms[_atomId].moth = _moth; } function setAtomIsRent(uint _atomId, uint128 _isRent) external onlyContract { atoms[_atomId].isRent = _isRent; } function setAtomIsBuy(uint _atomId, uint128 _isBuy) external onlyContract { atoms[_atomId].isBuy = _isBuy; } function setAtomIsReady(uint _atomId, uint32 _isReady) external onlyContractAdmin { atoms[_atomId].isReady = _isReady; } //ERC721 mapping (uint => address) tokenApprovals; function totalSupply() public view returns (uint256 total){ return atoms.length; } function balanceOf(address _owner) public view returns (uint256 balance) { return ownerAtomsCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner) { return atomOwner[_tokenId]; } function _transfer(address _from, address _to, uint256 _tokenId) private { atoms[_tokenId].isBuy = 0; atoms[_tokenId].isRent = 0; ownerAtomsCount[_to]++; ownerAtomsCount[_from]--; atomOwner[_tokenId] = _to; Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public { require(msg.sender == atomOwner[_tokenId]); _transfer(msg.sender, _to, _tokenId); } function approve(address _to, uint256 _tokenId) public { require(msg.sender == atomOwner[_tokenId]); tokenApprovals[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function takeOwnership(uint256 _tokenId) public { require(tokenApprovals[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } interface ERC721TokenReceiver { function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } interface ERC721Metadata { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } interface ERC721Enumerable { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } contract CryptoAtomsToken is Ownable { address public CaDataAddress = 0x9b3554E6FC4F81531F6D43b611258bd1058ef6D5; CaData public CaDataContract = CaData(CaDataAddress); function kill() external { require(msg.sender == CaDataContract.COO()); selfdestruct(msg.sender); } function() public payable{} function withdrawBalance() public payable { require(msg.sender == CaDataContract.COO() || msg.sender == CaDataContract.CTO() || msg.sender == CaDataContract.CFO()); CaDataContract.CFO().transfer(address(this).balance); } mapping (address => bool) transferEmittables; function setTransferEmittables(address _addr, bool _bool) external { require(msg.sender == CaDataContract.COO() || msg.sender == CaDataContract.CTO() || msg.sender == CaDataContract.CFO()); transferEmittables[_addr] = _bool; } function emitTransfer(address _from, address _to, uint256 _tokenId) external{ require(transferEmittables[msg.sender]); Transfer(_from, _to, _tokenId); } //ERC721 event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); mapping (uint => address) tokenApprovals; mapping (uint => address) tokenOperators; mapping (address => mapping (address => bool)) ownerOperators; function _transfer(address _from, address _to, uint256 _tokenId) private { CaDataContract.setAtomIsBuy(_tokenId,0); CaDataContract.setAtomIsRent(_tokenId,0); CaDataContract.setOwnerAtomsCount(_to,CaDataContract.ownerAtomsCount(_to)+1); CaDataContract.setOwnerAtomsCount(_from,CaDataContract.ownerAtomsCount(_from)-1); CaDataContract.setAtomOwner(_tokenId,_to); Transfer(_from, _to, _tokenId); } function _isContract(address _addr) private returns (bool check) { uint size; assembly { size := extcodesize(_addr) } return size > 0; } function balanceOf(address _owner) external view returns (uint256 balance) { return CaDataContract.balanceOf(_owner); } function ownerOf(uint256 _tokenId) external view returns (address owner) { return CaDataContract.ownerOf(_tokenId); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external payable{ require(msg.sender == CaDataContract.ownerOf(_tokenId) || ownerOperators[CaDataContract.atomOwner(_tokenId)][msg.sender] == true || msg.sender == tokenApprovals[_tokenId]); require(_from == CaDataContract.ownerOf(_tokenId) && _to != 0x0); require(_tokenId < totalSupply()); _transfer(_from, _to, _tokenId); if(_isContract(_to)) { require(ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data) == ERC721_RECEIVED); } } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable{ require(msg.sender == CaDataContract.ownerOf(_tokenId) || ownerOperators[CaDataContract.atomOwner(_tokenId)][msg.sender] == true || msg.sender == tokenApprovals[_tokenId]); require(_from == CaDataContract.ownerOf(_tokenId) && _to != 0x0); require(_tokenId < totalSupply()); _transfer(_from, _to, _tokenId); if(_isContract(_to)) { require(ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "") == ERC721_RECEIVED); } } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable{ require(msg.sender == CaDataContract.ownerOf(_tokenId) || ownerOperators[CaDataContract.atomOwner(_tokenId)][msg.sender] == true || msg.sender == tokenApprovals[_tokenId]); require(_from == CaDataContract.ownerOf(_tokenId) && _to != 0x0); require(_tokenId < totalSupply()); _transfer(_from, _to, _tokenId); } /// @notice Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable { require(msg.sender == CaDataContract.atomOwner(_tokenId) || ownerOperators[CaDataContract.atomOwner(_tokenId)][msg.sender]); tokenApprovals[_tokenId] = _approved; Approval(CaDataContract.atomOwner(_tokenId), _approved, _tokenId); } /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets. /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external { ownerOperators[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address) { return tokenApprovals[_tokenId]; } /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return ownerOperators[_owner][_operator]; } //ERC165 bytes4 constant Sign_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant Sign_ERC721 = bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('setApprovalForAll(address,bool)')) ^ bytes4(keccak256('getApproved(uint256)')) ^ bytes4(keccak256('isApprovedForAll(address,address)')); function supportsInterface(bytes4 interfaceID) external view returns (bool) { return ((interfaceID == Sign_ERC165) || (interfaceID == Sign_ERC721)); } //ERC721TokenReceiver /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the /// recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return /// of other than the magic value MUST result in the transaction being reverted. /// @notice The contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing bytes4 constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4){ return ERC721_RECEIVED; } //ERC721MetaData string baseUri = "https://www.cryptoatoms.org/cres/uri/"; function name() external view returns (string _name) { return "Atom"; } function symbol() external view returns (string _symbol){ return "ATH"; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string){ require(_tokenId < totalSupply()); uint256 uid; bytes32 bid; uid = _tokenId; if (uid == 0) { bid = '0'; } else { while (uid > 0) { bid = bytes32(uint(bid) / (2 ** 8)); bid |= bytes32(((uid % 10) + 48) * 2 ** (8 * 31)); uid /= 10; } } return string(abi.encodePacked(baseUri, bid)); } function setBaseUri (string _newBaseUri) external { require(msg.sender == CaDataContract.COO() || msg.sender == CaDataContract.CTO() || msg.sender == CaDataContract.CFO()); baseUri = _newBaseUri; } //ERC721Enumerable function totalSupply() public view returns (uint256 total){ return CaDataContract.totalSupply(); } /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256){ require(_index < totalSupply()); return _index; } /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256){ require(_index < CaDataContract.balanceOf(_owner)); uint64 counter = 0; for (uint64 i = 0; i < CaDataContract.totalSupply(); i++) { if (CaDataContract.atomOwner(i) == _owner) { if(counter == _index) { uint256 result = i; i = uint64(CaDataContract.totalSupply()); } else { counter++; } } } return result; } //ERC20 function decimals() external view returns (uint8 _decimals){ return 0; } function implementsERC721() public pure returns (bool){ return true; } }
Transfers the ownership of an NFT from one address to another address This works identically to the other function with an extra data parameter, except this function just sets data to "" _from The current owner of the NFT _to The new owner _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable{ require(msg.sender == CaDataContract.ownerOf(_tokenId) || ownerOperators[CaDataContract.atomOwner(_tokenId)][msg.sender] == true || msg.sender == tokenApprovals[_tokenId]); require(_from == CaDataContract.ownerOf(_tokenId) && _to != 0x0); require(_tokenId < totalSupply()); _transfer(_from, _to, _tokenId); if(_isContract(_to)) { require(ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "") == ERC721_RECEIVED); } }
5,503,474
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: IFund interface IFund { function underlying() external view returns (address); function fundManager() external view returns (address); function relayer() external view returns (address); function deposit(uint256 amountWei) external; function depositFor(uint256 amountWei, address holder) external; function withdraw(uint256 numberOfShares) external; function getPricePerShare() external view returns (uint256); function totalValueLocked() external view returns (uint256); function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256); } // Part: IGovernable interface IGovernable { function governance() external view returns (address); } // Part: IStrategy interface IStrategy { function name() external pure returns (string memory); function version() external pure returns (string memory); function underlying() external view returns (address); function fund() external view returns (address); function creator() external view returns (address); function withdrawAllToFund() external; function withdrawToFund(uint256 amount) external; function investedUnderlyingBalance() external view returns (uint256); function doHardWork() external; } // Part: IStrategyUnderOptimizer interface IStrategyUnderOptimizer { function aprAfterDeposit(uint256 depositAmount) external view returns (uint256); function apr() external view returns (uint256); } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: OptimizerStrategyBase.sol /** * This strategy takes an asset, and invests into the best strategy */ /** * @title This is an optimizer strategy that rotates capital to various strategies. * @author Mesh Finance * @notice This strategy takes an asset, and invests into the strategy with highest APR */ contract OptimizerStrategyBase is IStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event StrategyAddedOptimizer(address indexed strategy); event StrategyRemovedOptimizer(address indexed strategy); event ActiveStrategyChangedOptimizer(address indexed strategy); address internal constant ZERO_ADDRESS = address(0); string public constant override name = "OptimizerStrategyBase"; string public constant override version = "V1"; address public immutable override underlying; address public immutable override fund; address public immutable deployer; // these tokens cannot be claimed by the governance mapping(address => bool) public canNotSweep; address[] public strategies; address public activeStrategy; bool public investActivated; constructor(address _fund) public { require(_fund != address(0), "Fund cannot be empty"); fund = _fund; address _underlying = IFund(_fund).underlying(); underlying = _underlying; deployer = msg.sender; // restricted tokens, can not be swept canNotSweep[_underlying] = true; investActivated = true; } function _governance() internal view returns (address) { return IGovernable(fund).governance(); } function governance() external view returns (address) { return _governance(); } function _fundManager() internal view returns (address) { return IFund(fund).fundManager(); } function fundManager() external view returns (address) { return _fundManager(); } function _relayer() internal view returns (address) { return IFund(fund).relayer(); } function relayer() external view returns (address) { return _relayer(); } function creator() external view override returns (address) { if (activeStrategy != ZERO_ADDRESS) { return IStrategy(activeStrategy).creator(); } return deployer; } modifier onlyFund() { require(msg.sender == fund, "The sender has to be the fund"); _; } modifier onlyFundManager() { require( msg.sender == _fundManager(), "The sender has to be the fund manager" ); _; } modifier onlyFundOrGovernance() { require( msg.sender == fund || msg.sender == _governance(), "The sender has to be the governance or fund" ); _; } modifier onlyFundManagerOrGovernance() { require( msg.sender == _fundManager() || msg.sender == _governance(), "The sender has to be the governance or fund manager" ); _; } modifier onlyFundManagerOrRelayer() { require( msg.sender == _fundManager() || msg.sender == _relayer(), "The sender has to be the relayer or fund manager" ); _; } /** * @notice Allows Governance/Fund Manager to stop/start investing from this strategy to active strategies * @dev Used for emergencies * @param _investActivated Set investment to True/False */ function setInvestActivated(bool _investActivated) external onlyFundManagerOrGovernance { investActivated = _investActivated; } /** * @notice Withdraws an underlying asset from the strategy to the fund in the specified amount. * It tries to withdraw from this optimizer contract if this has enough balance. * Otherwise, we withdraw from the active strategy. * @param underlyingAmount Underlying amount to withdraw to fund */ function withdrawToFund(uint256 underlyingAmount) external override onlyFund { uint256 underlyingBalanceBefore = IERC20(underlying).balanceOf(address(this)); if (underlyingBalanceBefore >= underlyingAmount) { IERC20(underlying).safeTransfer(fund, underlyingAmount); return; } if (activeStrategy != ZERO_ADDRESS) { IStrategy(activeStrategy).withdrawToFund( underlyingAmount.sub(underlyingBalanceBefore) ); } // we can transfer the asset to the fund uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { if (underlyingAmount < underlyingBalance) { IERC20(underlying).safeTransfer(fund, underlyingAmount); _investAllUnderlying(); } else { IERC20(underlying).safeTransfer(fund, underlyingBalance); } } } /** * @notice Withdraws all assets from the active strategy and transfers all underlying to fund. */ function withdrawAllToFund() external override onlyFund { if (activeStrategy != ZERO_ADDRESS) { IStrategy(activeStrategy).withdrawAllToFund(); } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (underlyingBalance > 0) { IERC20(underlying).safeTransfer(fund, underlyingBalance); } } /** * @notice This selects new active strategy based on APR * @dev If active strategy is changed, funds are withdrawn from current active strategy */ function _selectActiveStrategy() internal { if (strategies.length > 0) { uint256 highestApr = 0; address highestAprStrategy; uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); for (uint256 i = 0; i < strategies.length; i++) { uint256 apr; apr = IStrategyUnderOptimizer(strategies[i]).aprAfterDeposit( underlyingBalance ); if (apr > highestApr) { highestApr = apr; highestAprStrategy = strategies[i]; } } if (highestAprStrategy != activeStrategy) { if (activeStrategy != ZERO_ADDRESS) { IStrategy(activeStrategy).withdrawAllToFund(); } activeStrategy = highestAprStrategy; emit ActiveStrategyChangedOptimizer(activeStrategy); } } else { if (activeStrategy != ZERO_ADDRESS) { activeStrategy = ZERO_ADDRESS; emit ActiveStrategyChangedOptimizer(activeStrategy); } } } /** * @notice Invests all underlying assets into active strategy */ function _investAllUnderlying() internal { if (!investActivated) { return; } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (activeStrategy != ZERO_ADDRESS) { if (underlyingBalance > 0) { // deposits the entire balance to active strategy IERC20(underlying).safeTransfer( activeStrategy, underlyingBalance ); } IStrategy(activeStrategy).doHardWork(); } } /** * @notice This selects new active strategy based on APR and invests all the underlying there. * @dev If active strategy is changed, funds are first withdrawn from current active strategy */ function doHardWork() external override onlyFund { _selectActiveStrategy(); _investAllUnderlying(); } /** * @notice Adds a new strategy to select active strategy from. * @param newStrategy Strategy to add */ function addStrategy(address newStrategy) external onlyFundManager { require(newStrategy != ZERO_ADDRESS, "newStrategy cannot be empty"); // The strategies added in optimizer treat optimizer as fund. require( IStrategy(newStrategy).fund() == address(this), "The strategy does not belong to this optimizer" ); for (uint256 i = 0; i < strategies.length; i++) { require( newStrategy != strategies[i], "The strategy is already added in this optimizer" ); } strategies.push(newStrategy); emit StrategyAddedOptimizer(newStrategy); } /** * @notice Removes the strategy from the optimizer. * If it is an active strategy, funds are withdrawn from it, and reinvested in the newly selected active strategy. * @param strategy Strategy to remove */ function removeStrategy(address strategy) external onlyFundManagerOrGovernance { require(strategy != ZERO_ADDRESS, "strategy cannot be empty"); for (uint256 i = 0; i < strategies.length; i++) { if (strategy == strategies[i]) { IStrategy(strategy).withdrawAllToFund(); if (i != strategies.length - 1) { strategies[i] = strategies[strategies.length - 1]; } strategies.pop(); if (strategy == activeStrategy) { activeStrategy = ZERO_ADDRESS; _selectActiveStrategy(); } _investAllUnderlying(); emit StrategyRemovedOptimizer(strategy); return; } } require(false, "This strategy is not part of this optimizer"); } //we could make this more gas efficient but it is only used by a view function struct Strategy { string name; address strategy; uint256 investedUnderlyingBalance; uint256 apr; } /** * @notice Returns the details of all the strategies in the optimiser * @return Array of Strategy struct */ function getStrategies() public view returns (Strategy[] memory) { Strategy[] memory _strategies = new Strategy[](strategies.length); for (uint256 i = 0; i < strategies.length; i++) { Strategy memory s; s.name = IStrategy(strategies[i]).name(); s.strategy = strategies[i]; s.investedUnderlyingBalance = IStrategy(strategies[i]) .investedUnderlyingBalance(); s.apr = IStrategyUnderOptimizer(strategies[i]).apr(); _strategies[i] = s; } return _strategies; } /** * @notice No tokens apart from underlying asset should ever be stored on this contract. * Any tokens that are sent here by mistake are recoverable by owner. * @dev Not applicable for ETH, different function needs to be written * @param _token Token address that needs to be recovered * @param _sweepTo Address to which tokens are sent */ function sweep(address _token, address _sweepTo) external { require(_governance() == msg.sender, "Not governance"); require(!canNotSweep[_token], "Token is restricted"); require(_sweepTo != address(0), "Can not sweep to zero address"); IERC20(_token).safeTransfer( _sweepTo, IERC20(_token).balanceOf(address(this)) ); } /** * @notice Returns the underlying invested balance. This is the underlying amount based on active strategy, * plus the current balance of the underlying asset. * @return Total balance invested in the strategy */ function investedUnderlyingBalance() external view override returns (uint256) { uint256 underlyingBalanceinActiveStrategy; if (activeStrategy != ZERO_ADDRESS) { underlyingBalanceinActiveStrategy = IStrategy(activeStrategy) .investedUnderlyingBalance(); } return underlyingBalanceinActiveStrategy.add( IERC20(underlying).balanceOf(address(this)) ); } }
Invests all underlying assets into active strategy/ deposits the entire balance to active strategy
function _investAllUnderlying() internal { if (!investActivated) { return; } uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); if (activeStrategy != ZERO_ADDRESS) { if (underlyingBalance > 0) { IERC20(underlying).safeTransfer( activeStrategy, underlyingBalance ); } IStrategy(activeStrategy).doHardWork(); } }
1,142,318
./full_match/4/0x926B5bFB2990208A9F57884aA0De0b728d5b54bC/sources/contracts/ERC721.sol
Returns the value associated with `key`. O(1). Requirements: - `key` must be in the map./
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); }
13,338,179
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@bancor/token-governance/contracts/ITokenGovernance.sol"; import "../converter/interfaces/IConverterRegistry.sol"; import "../converter/interfaces/IConverter.sol"; import "../utility/ContractRegistryClient.sol"; import "../utility/Owned.sol"; import "../utility/Utils.sol"; import "../utility/interfaces/ITokenHolder.sol"; import "../token/ReserveToken.sol"; import "../INetworkSettings.sol"; import "../IBancorNetwork.sol"; /** * @dev This contract provides any user to trigger a network fee burning event */ contract VortexBurner is Owned, Utils, ReentrancyGuard, ContractRegistryClient { using SafeMath for uint256; using Math for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; struct Strategy { address[][] paths; uint256[] amounts; address[] govPath; } // the mechanism is only designed to work with 50/50 standard pool converters uint32 private constant STANDARD_POOL_RESERVE_WEIGHT = PPM_RESOLUTION / 2; // the type of the standard pool converter uint16 private constant STANDARD_POOL_CONVERTER_TYPE = 3; // the address of the network token IERC20 private immutable _networkToken; // the address of the governance token IERC20 private immutable _govToken; // the address of the governance token security module ITokenGovernance private immutable _govTokenGovernance; // the percentage of the converted network tokens to be sent to the caller of the burning event (in units of PPM) uint32 private _burnReward; // the maximum burn reward to be sent to the caller of the burning event uint256 private _maxBurnRewardAmount; // stores the total amount of the burned governance tokens uint256 private _totalBurnedAmount; /** * @dev triggered when the burn reward has been changed */ event BurnRewardUpdated( uint32 prevBurnReward, uint32 newBurnReward, uint256 prevMaxBurnRewardAmount, uint256 newMaxBurnRewardAmount ); /** * @dev triggered during conversion of a single token during the burning event */ event Converted(IReserveToken reserveToken, uint256 sourceAmount, uint256 targetAmount); /** * @dev triggered after a completed burning event */ event Burned(IReserveToken[] reserveTokens, uint256 sourceAmount, uint256 burnedAmount); /** * @dev initializes a new VortexBurner contract */ constructor( IERC20 networkToken, ITokenGovernance govTokenGovernance, IContractRegistry registry ) public ContractRegistryClient(registry) validAddress(address(networkToken)) validAddress(address(govTokenGovernance)) { _networkToken = networkToken; _govTokenGovernance = govTokenGovernance; _govToken = govTokenGovernance.token(); } /** * @dev ETH receive callback */ receive() external payable {} /** * @dev returns the burn reward percentage and its maximum amount */ function burnReward() external view returns (uint32, uint256) { return (_burnReward, _maxBurnRewardAmount); } /** * @dev allows the owner to set the burn reward percentage and its maximum amount * * Requirements: * * - the caller must be the owner of the contract */ function setBurnReward(uint32 newBurnReward, uint256 newMaxBurnRewardAmount) external ownerOnly validFee(newBurnReward) { emit BurnRewardUpdated(_burnReward, newBurnReward, _maxBurnRewardAmount, newMaxBurnRewardAmount); _burnReward = newBurnReward; _maxBurnRewardAmount = newMaxBurnRewardAmount; } /** * @dev returns the total amount of the burned governance tokens */ function totalBurnedAmount() external view returns (uint256) { return _totalBurnedAmount; } /** * @dev converts the provided tokens to governance tokens and burns them */ function burn(IReserveToken[] calldata reserveTokens) external nonReentrant { ITokenHolder feeWallet = _networkFeeWallet(); // retrieve the burning strategy Strategy memory strategy = _burnStrategy(reserveTokens, feeWallet); // withdraw all token/ETH amounts to the contract feeWallet.withdrawTokensMultiple(reserveTokens, address(this), strategy.amounts); // convert all amounts to the network token and record conversion amounts IBancorNetwork network = _bancorNetwork(); for (uint256 i = 0; i < strategy.paths.length; ++i) { // avoid empty conversions uint256 amount = strategy.amounts[i]; if (amount == 0) { continue; } address[] memory path = strategy.paths[i]; IReserveToken reserveToken = IReserveToken(path[0]); uint256 value = 0; if (address(reserveToken) == address(_networkToken) || address(reserveToken) == address(_govToken)) { // if the source token is the network or the governance token, we won't try to convert it, but rather // include its amount in either the total amount of tokens to convert or burn. continue; } if (reserveToken.isNativeToken()) { // if the source token is actually an ETH reserve, make sure to pass its value to the network value = amount; } else { // if the source token is a regular token, approve the network to withdraw the token amount reserveToken.ensureApprove(address(network), amount); } // perform the actual conversion and optionally send ETH to the network uint256 targetAmount = network.convertByPath{ value: value }(path, amount, 1, address(this), address(0), 0); emit Converted(reserveToken, amount, targetAmount); } // calculate the burn reward and reduce it from the total amount to convert (uint256 sourceAmount, uint256 burnRewardAmount) = _netNetworkConversionAmounts(); // in case there are network tokens to burn, convert them to the governance token if (sourceAmount > 0) { // approve the network to withdraw the network token amount _networkToken.ensureApprove(address(network), sourceAmount); // convert the entire network token amount to the governance token network.convertByPath(strategy.govPath, sourceAmount, 1, address(this), address(0), 0); } // get the governance token balance uint256 govTokenBalance = _govToken.balanceOf(address(this)); require(govTokenBalance > 0, "ERR_ZERO_BURN_AMOUNT"); // update the stats of the burning event _totalBurnedAmount = _totalBurnedAmount.add(govTokenBalance); // burn the entire governance token balance _govTokenGovernance.burn(govTokenBalance); // if there is a burn reward, transfer it to the caller if (burnRewardAmount > 0) { _networkToken.transfer(msg.sender, burnRewardAmount); } emit Burned(reserveTokens, sourceAmount + burnRewardAmount, govTokenBalance); } /** * @dev transfers the ownership of the network fee wallet * * Requirements: * * - the caller must be the owner of the contract */ function transferNetworkFeeWalletOwnership(address newOwner) external ownerOnly { _networkFeeWallet().transferOwnership(newOwner); } /** * @dev accepts the ownership of he network fee wallet */ function acceptNetworkFeeOwnership() external ownerOnly { _networkFeeWallet().acceptOwnership(); } /** * @dev returns the burning strategy for the specified tokens */ function _burnStrategy(IReserveToken[] calldata reserveTokens, ITokenHolder feeWallet) private view returns (Strategy memory) { IConverterRegistry registry = _converterRegistry(); Strategy memory strategy = Strategy({ paths: new address[][](reserveTokens.length), amounts: new uint256[](reserveTokens.length), govPath: new address[](3) }); for (uint256 i = 0; i < reserveTokens.length; ++i) { IReserveToken reserveToken = reserveTokens[i]; address[] memory path = new address[](3); path[0] = address(reserveToken); // don't look up for a converter for either the network or the governance token, since they are going to be // handled in a special way during the burn itself if (address(reserveToken) != address(_networkToken) && address(reserveToken) != address(_govToken)) { path[1] = address(_networkTokenConverterAnchor(reserveToken, registry)); path[2] = address(_networkToken); } strategy.paths[i] = path; // make sure to retrieve the balance of either an ERC20 or an ETH reserve strategy.amounts[i] = reserveToken.balanceOf(address(feeWallet)); } // get the governance token converter path strategy.govPath[0] = address(_networkToken); strategy.govPath[1] = address(_networkTokenConverterAnchor(IReserveToken(address(_govToken)), registry)); strategy.govPath[2] = address(_govToken); return strategy; } /** * @dev applies the burn reward on the whole balance and returns the net amount and the reward */ function _netNetworkConversionAmounts() private view returns (uint256, uint256) { uint256 amount = _networkToken.balanceOf(address(this)); uint256 burnRewardAmount = Math.min(amount.mul(_burnReward) / PPM_RESOLUTION, _maxBurnRewardAmount); return (amount - burnRewardAmount, burnRewardAmount); } /** * @dev finds the converter anchor of the 50/50 standard pool converter between the specified token and the network token */ function _networkTokenConverterAnchor(IReserveToken reserveToken, IConverterRegistry converterRegistry) private view returns (IConverterAnchor) { // initialize both the source and the target tokens IReserveToken[] memory reserveTokens = new IReserveToken[](2); reserveTokens[0] = IReserveToken(address(_networkToken)); reserveTokens[1] = reserveToken; // make sure to only look up for 50/50 converters uint32[] memory standardReserveWeights = new uint32[](2); standardReserveWeights[0] = STANDARD_POOL_RESERVE_WEIGHT; standardReserveWeights[1] = STANDARD_POOL_RESERVE_WEIGHT; // find the standard pool converter between the specified token and the network token IConverterAnchor anchor = converterRegistry.getLiquidityPoolByConfig( STANDARD_POOL_CONVERTER_TYPE, reserveTokens, standardReserveWeights ); require(address(anchor) != address(0), "ERR_INVALID_RESERVE_TOKEN"); return anchor; } /** * @dev returns the converter registry */ function _converterRegistry() private view returns (IConverterRegistry) { return IConverterRegistry(_addressOf(CONVERTER_REGISTRY)); } /** * @dev returns the network contract */ function _bancorNetwork() private view returns (IBancorNetwork) { return IBancorNetwork(payable(_addressOf(BANCOR_NETWORK))); } /** * @dev returns the network settings contract */ function _networkSetting() private view returns (INetworkSettings) { return INetworkSettings(_addressOf(NETWORK_SETTINGS)); } /** * @dev returns the network fee wallet */ function _networkFeeWallet() private view returns (ITokenHolder) { return ITokenHolder(_networkSetting().networkFeeWallet()); } }
converts the provided tokens to governance tokens and burns them/ retrieve the burning strategy withdraw all token/ETH amounts to the contract convert all amounts to the network token and record conversion amounts avoid empty conversions if the source token is the network or the governance token, we won't try to convert it, but rather include its amount in either the total amount of tokens to convert or burn. if the source token is actually an ETH reserve, make sure to pass its value to the network if the source token is a regular token, approve the network to withdraw the token amount in case there are network tokens to burn, convert them to the governance token approve the network to withdraw the network token amount convert the entire network token amount to the governance token if there is a burn reward, transfer it to the caller
function burn(IReserveToken[] calldata reserveTokens) external nonReentrant { ITokenHolder feeWallet = _networkFeeWallet(); Strategy memory strategy = _burnStrategy(reserveTokens, feeWallet); feeWallet.withdrawTokensMultiple(reserveTokens, address(this), strategy.amounts); IBancorNetwork network = _bancorNetwork(); for (uint256 i = 0; i < strategy.paths.length; ++i) { uint256 amount = strategy.amounts[i]; if (amount == 0) { continue; } address[] memory path = strategy.paths[i]; IReserveToken reserveToken = IReserveToken(path[0]); uint256 value = 0; if (address(reserveToken) == address(_networkToken) || address(reserveToken) == address(_govToken)) { continue; } if (reserveToken.isNativeToken()) { value = amount; reserveToken.ensureApprove(address(network), amount); } emit Converted(reserveToken, amount, targetAmount); } if (sourceAmount > 0) { _networkToken.ensureApprove(address(network), sourceAmount); network.convertByPath(strategy.govPath, sourceAmount, 1, address(this), address(0), 0); } require(govTokenBalance > 0, "ERR_ZERO_BURN_AMOUNT"); if (burnRewardAmount > 0) { _networkToken.transfer(msg.sender, burnRewardAmount); } emit Burned(reserveTokens, sourceAmount + burnRewardAmount, govTokenBalance); }
6,424,368
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // Added public isInitialized() view of private initialized bool. // SPDX-License-Identifier: MIT pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } /** * @dev Return true if and only if the contract has been initialized * @return whether the contract has been initialized */ function isInitialized() public view returns (bool) { return initialized; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Context} from "Context.sol"; import {Initializable} from "Initializable.sol"; /** * @title UpgradeableClaimable * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. Since * this contract combines Claimable and UpgradableOwnable contracts, ownership * can be later change via 2 step method {transferOwnership} and {claimOwnership} * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract UpgradeableClaimable is Initializable, Context { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting a custom initial owner of choice. * @param __owner Initial owner of contract to be set. */ function initialize(address __owner) internal initializer { _owner = __owner; emit OwnershipTransferred(address(0), __owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view returns (address) { return _pendingOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner"); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; _pendingOwner = address(0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "IERC20.sol"; import "SafeMath.sol"; import "Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {Address} from "Address.sol"; import {Context} from "Context.sol"; import {IERC20} from "IERC20.sol"; import {SafeMath} from "SafeMath.sol"; import {Initializable} from "Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero") ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ITrueLender2 { // @dev calculate overall value of the pools function value(ITrueFiPool2 pool) external view returns (uint256); // @dev distribute a basket of tokens for exiting user function distribute( address recipient, uint256 numerator, uint256 denominator ) external; function transferAllLoanTokens(ILoanToken2 loan, address recipient) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IERC20WithDecimals is IERC20 { function decimals() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20WithDecimals} from "IERC20WithDecimals.sol"; /** * @dev Oracle that converts any token to and from TRU * Used for liquidations and valuing of liquidated TRU in the pool */ interface ITrueFiPoolOracle { // token address function token() external view returns (IERC20WithDecimals); // amount of tokens 1 TRU is worth function truToToken(uint256 truAmount) external view returns (uint256); // amount of TRU 1 token is worth function tokenToTru(uint256 tokenAmount) external view returns (uint256); // USD price of token with 18 decimals function tokenToUsd(uint256 tokenAmount) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface I1Inch3 { struct SwapDescription { address srcToken; address dstToken; address srcReceiver; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; } function swap( address caller, SwapDescription calldata desc, bytes calldata data ) external returns ( uint256 returnAmount, uint256 gasLeft, uint256 chiSpent ); function unoswap( address srcToken, uint256 amount, uint256 minReturn, bytes32[] calldata /* pools */ ) external payable returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface IDeficiencyToken is IERC20 { function loan() external view returns (ILoanToken2); function burnFrom(address account, uint256 amount) external; function version() external pure returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IDeficiencyToken} from "IDeficiencyToken.sol"; import {ILoanToken2} from "ILoanToken2.sol"; interface ISAFU { function poolDeficit(address pool) external view returns (uint256); function deficiencyToken(ILoanToken2 loan) external view returns (IDeficiencyToken); function reclaim(ILoanToken2 loan, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ERC20, IERC20} from "UpgradeableERC20.sol"; import {ITrueLender2, ILoanToken2} from "ITrueLender2.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {I1Inch3} from "I1Inch3.sol"; import {ISAFU} from "ISAFU.sol"; interface ITrueFiPool2 is IERC20 { function initialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner ) external; function singleBorrowerInitialize( ERC20 _token, ITrueLender2 _lender, ISAFU safu, address __owner, string memory borrowerName, string memory borrowerSymbol ) external; function token() external view returns (ERC20); function oracle() external view returns (ITrueFiPoolOracle); function poolValue() external view returns (uint256); /** * @dev Ratio of liquid assets in the pool after lending * @param afterAmountLent Amount of asset being lent */ function liquidRatio(uint256 afterAmountLent) external view returns (uint256); /** * @dev Join the pool by depositing tokens * @param amount amount of tokens to deposit */ function join(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount) external; /** * @dev pay borrowed money back to pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 currencyAmount) external; /** * @dev SAFU buys LoanTokens from the pool */ function liquidate(ILoanToken2 loan) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; import {ERC20} from "UpgradeableERC20.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanToken2 is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function pool() external view returns (ITrueFiPool2); function profit() external view returns (uint256); function status() external view returns (Status); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function settle() external; function enterDefault() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function repayInFull(address _sender) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function isRepaid() external view returns (bool); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function token() external view returns (ERC20); function version() external pure returns (uint8); } //interface IContractWithPool { // function pool() external view returns (ITrueFiPool2); //} // //// Had to be split because of multiple inheritance problem //interface ILoanToken2 is ILoanToken, IContractWithPool { // //} // SPDX-License-Identifier: MIT pragma solidity 0.6.10; interface IPoolFactory { function isPool(address pool) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {IERC20} from "IERC20.sol"; interface IStakingPool is IERC20 { function stakeSupply() external view returns (uint256); function withdraw(uint256 amount) external; function payFee(uint256 amount, uint256 endTime) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {ITrueFiPool2} from "ITrueFiPool2.sol"; interface ILoanFactory2 { function createLoanToken( ITrueFiPool2 _pool, uint256 _amount, uint256 _term ) external; function isLoanToken(address) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.10; import {UpgradeableClaimable} from "UpgradeableClaimable.sol"; import {IERC20} from "IERC20.sol"; import {SafeERC20} from "SafeERC20.sol"; import {ILoanToken2} from "ILoanToken2.sol"; import {IPoolFactory} from "IPoolFactory.sol"; import {ITrueFiPool2} from "ITrueFiPool2.sol"; import {IStakingPool} from "IStakingPool.sol"; import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol"; import {ILoanFactory2} from "ILoanFactory2.sol"; import {SafeMath} from "SafeMath.sol"; /** * @title Liquidator2 * @notice Liquidate LoanTokens with this Contract * @dev When a Loan becomes defaulted, Liquidator allows to * compensate pool participants, by transferring some of TRU to the pool */ contract Liquidator2 is UpgradeableClaimable { using SafeMath for uint256; using SafeERC20 for IERC20; // basis point for ratio uint256 private constant BASIS_RATIO = 10000; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IStakingPool public stkTru; IERC20 public tru; ILoanFactory2 public loanFactory; mapping(address => bool) public approvedTokens; // max share of tru to be taken from staking pool during liquidation // 1000 -> 10% uint256 public fetchMaxShare; // Address of SAFU fund, to which slashed tru is transferred after liquidation address public SAFU; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted fetch max share is changed * @param newShare New share set */ event FetchMaxShareChanged(uint256 newShare); /** * @dev Emitted when whitelist status for a token changes * @param token Address of token * @param status New whitelist status */ event WhitelistStatusChanged(address token, bool status); /** * @dev Emitted when a loan gets liquidated * @param loan Loan that has been liquidated * @param defaultedValue Remaining loan debt to repay * @param withdrawnTru Amount of TRU transferred to compensate defaulted loan */ event Liquidated(ILoanToken2 loan, uint256 defaultedValue, uint256 withdrawnTru); /** * @dev Emitted when SAFU is changed * @param SAFU New SAFU address */ event AssuranceChanged(address SAFU); /** * @dev Initialize this contract */ function initialize( IStakingPool _stkTru, IERC20 _tru, ILoanFactory2 _loanFactory, address _SAFU ) public initializer { UpgradeableClaimable.initialize(msg.sender); stkTru = _stkTru; tru = _tru; loanFactory = _loanFactory; SAFU = _SAFU; fetchMaxShare = 1000; } /** * @dev Set a new SAFU address * @param _SAFU Address to be set as SAFU */ function setAssurance(address _SAFU) external onlyOwner { SAFU = _SAFU; emit AssuranceChanged(_SAFU); } /** * @dev Set new max fetch share * @param newShare New share to be set */ function setFetchMaxShare(uint256 newShare) external onlyOwner { require(newShare > 0, "Liquidator: Share cannot be set to 0"); require(newShare <= BASIS_RATIO, "Liquidator: Share cannot be larger than 10000"); fetchMaxShare = newShare; emit FetchMaxShareChanged(newShare); } /** * @dev Change whitelist status of a token for liquidations * @param token Address of token to change whitelist status * @param status New whitelist status for token */ function setTokenApproval(address token, bool status) external onlyOwner { approvedTokens[token] = status; emit WhitelistStatusChanged(token, status); } /** * @dev Liquidates a defaulted Loan, withdraws a portion of tru from staking pool * then transfers tru to TrueFiPool as compensation * @param loan Loan to be liquidated */ function liquidate(ILoanToken2 loan) external { require(msg.sender == SAFU, "Liquidator: Only SAFU contract can liquidate a loan"); require(loanFactory.isLoanToken(address(loan)), "Liquidator: Unknown loan"); require(loan.status() == ILoanToken2.Status.Defaulted, "Liquidator: Loan must be defaulted"); ITrueFiPool2 pool = ITrueFiPool2(loan.pool()); require(approvedTokens[address(pool.token())], "Liquidator: Token not approved for default protection"); uint256 defaultedValue = loan.debt().sub(loan.repaid()); uint256 withdrawnTru = getAmountToWithdraw(defaultedValue, ITrueFiPoolOracle(pool.oracle())); stkTru.withdraw(withdrawnTru); loan.liquidate(); tru.safeTransfer(SAFU, withdrawnTru); emit Liquidated(loan, defaultedValue, withdrawnTru); } /** * @dev Calculate amount of tru to be withdrawn from staking pool (not more than preset share) * @param deficit Amount of tusd lost on defaulted loan * @return amount of TRU to be withdrawn on liquidation */ function getAmountToWithdraw(uint256 deficit, ITrueFiPoolOracle oracle) internal view returns (uint256) { uint256 stakingPoolSupply = stkTru.stakeSupply(); uint256 maxWithdrawValue = stakingPoolSupply.mul(fetchMaxShare).div(BASIS_RATIO); uint256 deficitInTru = oracle.tokenToTru(deficit); return maxWithdrawValue > deficitInTru ? deficitInTru : maxWithdrawValue; } }
Set a new SAFU address _SAFU Address to be set as SAFU/
function setAssurance(address _SAFU) external onlyOwner { SAFU = _SAFU; emit AssuranceChanged(_SAFU); }
6,228,206
/** *Submitted for verification at Etherscan.io on 2021-02-24 */ pragma solidity ^0.5.0; /* ____________________________________________________________________ 1. Notify Reward and send to staking : 90% of this reward deposits 2. Total Rewards : 90% of this contract balance 3. Notifier Rewards : 10 % of this contract balance ____________________________________________________________________ -Codezeros Developers -https://www.codezeros.com/ ____________________________________________________________________ */ library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function average(uint256 a, uint256 b) internal pure returns (uint256) { return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Context { constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { // function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } interface Staking { function notifyRewardAmount() external returns (bool); } contract RewardCollector is Ownable, Staking { using SafeMath for uint256; using SafeERC20 for IERC20; Staking stakingInstance; uint256 notifierFee; uint256 notifyAmount; IERC20 public APE ; constructor(address _presale, address _staking) public { APE = IERC20(_presale); stakingInstance = Staking(_staking); } function rewardDeposits() public view returns (uint256) { return APE.balanceOf(address(this)); } function balanceOf(address account) public view returns (uint256) { return APE.balanceOf(account); } function calculateTenPercent(uint256 amount) public pure returns (uint256) { return amount.mul(100).div(1000); } function calculateNinetyPercent(uint256 amount) public pure returns (uint256) { return amount.mul(900).div(1000); } function notifyRewardAmount() public returns (bool) { return stakingInstance.notifyRewardAmount(); } function notifyExternal() public returns (bool) { notifyRewardAmount(); notifierFee = calculateTenPercent(rewardDeposits()); //-----| Notifier Reward |------------ notifyAmount = calculateNinetyPercent(rewardDeposits()); //-----| For Notify Purpose |--------- APE.safeTransfer(msg.sender, notifierFee); //-----| Send notifier reward |------- APE.safeTransfer(address(stakingInstance), notifyAmount); //-----| Send to staking contract|----- return true; } }
function totalSupply() external view returns (uint256);
interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); }
2,304,305
./full_match/1/0xFD9E52A73d92E08903BFe6f42aeDEB82a86EFF35/sources/contracts/NAGOMIMinterHalfYear.sol
フリーミント用MerkleRootのsetter
function setFreeMintMerkleRoot(bytes32 _merkleRoot) public onlyOwner { freeMintMerkleRoot = _merkleRoot; }
3,024,512
./partial_match/42220/0x56E44A9f86C2e3a53e816335cBE6deaE440b0856/sources/WitnetPriceFeedBypass.sol
Read and consume the next 32 bytes from the buffer as an `uint256`. buffer An instance of `Buffer`. return value The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
function readUint256(Buffer memory buffer) internal pure withinRange(buffer.cursor + 32, buffer.data.length) returns (uint256 value) { bytes memory data = buffer.data; uint offset = buffer.cursor; assembly { value := mload(add(add(data, 32), offset)) } buffer.cursor += 32; }
3,498,221
./partial_match/1/0x5A7434f0579354fB51EaB6f848cbdA4EAA53756f/sources/TokenVesting.sol
return The amount of vesting token/
function amount(address account) external view returns (uint256) { return _vestingBeneficiaries[account].amount; }
2,699,994
//Address: 0xd5527579226e4ebc8864906e49d05d4458ccf47f //Contract name: Kubera //Balance: 0 Ether //Verification Date: 10/30/2017 //Transacion Count: 4643 // CODE STARTS HERE pragma solidity ^0.4.11; contract SafeMath { //internals function safeMul(uint a, uint b) internal returns(uint) { uint c = a * b; Assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns(uint) { Assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns(uint) { uint c = a + b; Assert(c >= a && c >= b); return c; } function Assert(bool assertion) internal { if (!assertion) { revert(); } } } contract Kubera is SafeMath { /* Public variables of the token */ string public standard = 'ERC20'; string public name = 'Kubera token'; string public symbol = 'KBR'; uint8 public decimals = 0; uint256 public totalSupply; address public owner; uint public tokensSoldToInvestors = 0; uint public maxGoalInICO = 2100000000; /* From this time on tokens may be transfered (after ICO 23h59 10/11/2017)*/ uint256 public startTime = 1510325999; /* Tells if tokens have been burned already */ bool burned; bool hasICOStarted; /* This wallet will hold tokens after ICO*/ address tokensHolder = 0x94B4776F8331DF237E087Ed548A3c8b4932D131B; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event TransferToReferral(address indexed referralAddress, uint256 value); event Approval(address indexed Owner, address indexed spender, uint256 value); event Burned(uint amount); /* Initializes contract with initial supply tokens to the creator of the contract */ function Kubera() { owner = 0x084bf76c9ba9106d6114305fae9810fbbdb157d9; // Give the owner all initial tokens balanceOf[owner] = 2205000000; // Update total supply totalSupply = 2205000000; } /* Send some of your tokens to a given address */ function transfer(address _to, uint256 _value) returns(bool success) { //check if the crowdsale is already over if (now < startTime) { revert(); } //prevent owner transfer all tokens immediately after ICO ended if (msg.sender == owner && !burned) { burn(); return; } // Subtract from the sender balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Add the same to the recipient balanceOf[_to] = safeAdd(balanceOf[_to], _value); // Notify anyone listening that this transfer took place Transfer(msg.sender, _to, _value); return true; } /* Allow another contract or person to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns(bool success) { if( now < startTime && hasICOStarted) { // during ICO only allow execute this function one time revert(); } hasICOStarted = true; allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /* A contract or person attempts to get the tokens of somebody else. * This is only allowed if the token holder approved. */ function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (now < startTime && _from != owner) revert(); //check if the crowdsale is already over //prevent the owner of spending his share of tokens so that owner has to burn the token left after ICO if (_from == owner && now >= startTime && !burned) { burn(); return; } if (now < startTime){ if(_value < maxGoalInICO ) { tokensSoldToInvestors = safeAdd(tokensSoldToInvestors, _value); } else { _value = safeSub(_value, maxGoalInICO); } } var _allowance = allowance[_from][msg.sender]; // Subtract from the sender balanceOf[_from] = safeSub(balanceOf[_from], _value); // Add the same to the recipient balanceOf[_to] = safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function burn(){ // if tokens have not been burned already and the ICO ended or Tokens have been sold out before ICO end. if(!burned && ( now > startTime || tokensSoldToInvestors >= maxGoalInICO) ) { // checked for overflow above totalSupply = safeSub(totalSupply, balanceOf[owner]) + 900000000; uint tokensLeft = balanceOf[owner]; balanceOf[owner] = 0; balanceOf[tokensHolder] = 900000000; startTime = now; burned = true; Burned(tokensLeft); } } }
Public variables of the token / From this time on tokens may be transfered (after ICO 23h59 10/11/2017)/ Tells if tokens have been burned already / This wallet will hold tokens after ICO/ This creates an array with all balances / This generates a public event on the blockchain that will notify clients / Initializes contract with initial supply tokens to the creator of the contract / Give the owner all initial tokens Update total supply
function Kubera() { owner = 0x084bf76c9ba9106d6114305fae9810fbbdb157d9; balanceOf[owner] = 2205000000; totalSupply = 2205000000; }
12,996,351
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./ERC20/ERC20Custom.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IDiamond.sol"; import "./Operator.sol"; contract Diamond is ERC20Custom, Operator, IDiamond { using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // ERC20 - Token string public symbol; string public name; uint8 public constant decimals = 18; // CONTRACTS address public treasury; // FLAGS bool public initialized; // DISTRIBUTION uint256 public constant COMMUNITY_ALLOCATION = 7000 ether; // 7K uint256 public constant TREASURY_ALLOCATION = 2000 ether; // 2K uint256 public constant IRON_ALLOCATION = 1000 ether; // 2K uint256 public constant VESTING_DURATION = 730 days; // 24 months uint256 public startTime; // Start time of vesting duration uint256 public endTime; // End of vesting duration address public treasuryFund; uint256 public treasuryFundLastClaimed; uint256 public constant treasuryFundEmissionRate = TREASURY_ALLOCATION / VESTING_DURATION; address public ironFund; uint256 public ironFundLastClaimed; uint256 public constant ironFundEmissionRate = IRON_ALLOCATION / VESTING_DURATION; address public communityFundController; // Holding SHARE tokens to distribute into Liquiditiy Mining Pools uint256 public communityFundClaimed; /* ========== MODIFIERS ========== */ modifier onlyPools() { require(ITreasury(treasury).isPool(msg.sender), "!pools"); _; } modifier checkInitialized() { require(initialized, "not initialized"); _; } /* ========== CONSTRUCTOR ========== */ constructor( string memory _name, string memory _symbol, address _treasury ) { name = _name; symbol = _symbol; treasury = _treasury; } function initialize( address _treasuryFund, address _ironFund, address _communityFundController, uint256 _startTime ) external onlyOperator { require(!initialized, "alreadyInitialized"); require(_treasuryFund != address(0), "invalid_address"); require(_ironFund != address(0), "invalid_address"); require(_communityFundController != address(0), "invalid_address"); initialized = true; communityFundController = _communityFundController; startTime = _startTime; endTime = _startTime + VESTING_DURATION; treasuryFund = _treasuryFund; treasuryFundLastClaimed = _startTime; ironFund = _ironFund; ironFundLastClaimed = _startTime; } /* ========== VIEWS FUNCTIONS =============== */ function unclaimedTreasuryFund() public view returns (uint256 _pending) { uint256 _now = block.timestamp; if (_now > endTime) _now = endTime; if (treasuryFundLastClaimed >= _now) return 0; _pending = _now.sub(treasuryFundLastClaimed).mul(treasuryFundEmissionRate); } function unclaimedIronFund() public view returns (uint256 _pending) { uint256 _now = block.timestamp; if (_now > endTime) _now = endTime; if (ironFundLastClaimed >= _now) return 0; _pending = _now.sub(ironFundLastClaimed).mul(ironFundEmissionRate); } /* ========== RESTRICTED FUNCTIONS ========== */ function setTreasury(address _treasury) external onlyOperator { treasury = _treasury; emit TreasuryChanged(treasury); } function setTreasuryFund(address _treasuryFund) external { require(msg.sender == treasuryFund, "!treasuryFund"); require(_treasuryFund != address(0), "zero"); treasuryFund = _treasuryFund; emit TreasuryFundChanged(treasuryFund); } function setIronFund(address _ironFund) external { require(msg.sender == ironFund, "!ironFund"); require(_ironFund != address(0), "zero"); ironFund = _ironFund; emit IronFundChanged(ironFund); } function setCommunityFundController(address _communityFundController) external { require(msg.sender == communityFundController, "!communityFundController"); require(_communityFundController != address(0), "zero"); communityFundController = _communityFundController; emit CommunityFundControllerChanged(communityFundController); } function claimCommunityFund(uint256 amount) external onlyOperator checkInitialized { require(amount > 0, "invalidAmount"); require(initialized, "!initialized"); require(communityFundController != address(0), "!communityFundController"); uint256 _remainingFund = COMMUNITY_ALLOCATION.sub(communityFundClaimed); require(amount <= _remainingFund, "exceeded_community_fund"); communityFundClaimed = communityFundClaimed.add(amount); _mint(communityFundController, amount); } function claimTreasuryFund() external checkInitialized { require(msg.sender == treasuryFund, "!treasuryFund"); uint256 _pending = unclaimedTreasuryFund(); if (_pending > 0 && treasuryFund != address(0)) { _mint(treasuryFund, _pending); treasuryFundLastClaimed = block.timestamp; } } function claimIronFund() external checkInitialized { require(msg.sender == ironFund, "!ironFund"); uint256 _pending = unclaimedIronFund(); if (_pending > 0 && ironFund != address(0)) { _mint(ironFund, _pending); ironFundLastClaimed = block.timestamp; } } /* ========== POOL FUNCTIONS ================== */ // This function is what other Pools will call to mint new SHARE function poolMint(address m_address, uint256 m_amount) external override onlyPools { super._mint(m_address, m_amount); emit DiamondMinted(address(this), m_address, m_amount); } // This function is what other pools will call to burn SHARE function poolBurnFrom(address b_address, uint256 b_amount) external override onlyPools { super._burnFrom(b_address, b_amount); emit DiamondBurned(b_address, address(this), b_amount); } /* ========== EVENTS ========== */ event DiamondMinted(address indexed from, address indexed to, uint256 amount); event DiamondBurned(address indexed from, address indexed to, uint256 amount); event TreasuryChanged(address indexed newTreasury); event TreasuryFundChanged(address indexed newTreasuryFund); event IronFundChanged(address indexed newIronFund); event CommunityFundControllerChanged(address indexed newCommunityFundController); }
This function is what other pools will call to burn SHARE
function poolBurnFrom(address b_address, uint256 b_amount) external override onlyPools { super._burnFrom(b_address, b_amount); emit DiamondBurned(b_address, address(this), b_amount); } event DiamondMinted(address indexed from, address indexed to, uint256 amount); event DiamondBurned(address indexed from, address indexed to, uint256 amount); event TreasuryChanged(address indexed newTreasury); event TreasuryFundChanged(address indexed newTreasuryFund); event IronFundChanged(address indexed newIronFund); event CommunityFundControllerChanged(address indexed newCommunityFundController);
12,851,748
//SPDX-License-Identifier: MIT pragma solidity ^0.7.6; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () public { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract Ownable { address public owner; constructor () public { owner = msg.sender; } modifier onlyOwner() { if (msg.sender == owner) _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) owner = newOwner; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) internal _balances; mapping (address => mapping (address => uint)) internal _allowances; uint internal _totalSupply; function totalSupply() public view override returns (uint) { return _totalSupply; } function balanceOf(address account) public view override returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) public { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } } contract ERC20Detailed is ERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public{ _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } contract PriceConsumerV3 { AggregatorV3Interface internal priceFeed; constructor() public { // Mainnet address : 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46 //Kovan test netwoek: 0x0bF499444525a23E7Bb61997539725cA2e928138 priceFeed = AggregatorV3Interface(0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } } contract GoldT is ERC20, ERC20Detailed, PriceConsumerV3{ using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public ownership; constructor () ERC20Detailed("GoldToken", "GoldT", 18) PriceConsumerV3() public{ ownership = msg.sender; _totalSupply = 10000000000 * (10**uint256(18)) ; _balances[ownership] = _totalSupply; } } contract tokenSale is Ownable, PriceConsumerV3{ using SafeMath for uint256; // The token being sold ERC20 public token; address public _owner = msg.sender; address payable wallet = msg.sender; address[] tokenHolders; constructor(ERC20 _token) public { require(address(_token) != address(0)); wallet = msg.sender; token = _token; } fallback () payable external{ buy(msg.sender); } receive() payable external { buy(msg.sender); } uint256 public weiUSD; uint256 public amountOfTokens; function _forwardFunds(uint256 _weiUSD) internal { wallet.transfer(_weiUSD); } function buy(address beneficiary) payable public { require(msg.value > 0 ether," No value transfered"); weiUSD = (uint256)(getLatestPrice()); require(weiUSD != 0, " No exchange value returned. Try again"); uint256 unitPrice = msg.value.div(weiUSD); amountOfTokens = unitPrice * uint256(10**18); //1 GoldT token * USD amount of Value _forwardFunds(weiUSD); uint256 twoPercent = calculateTwoPercent(amountOfTokens); token.transfer(beneficiary, (amountOfTokens + twoPercent)); } function calculateTwoPercent(uint256 _amountOfTokens) internal returns (uint256) { uint256 _twoPercent = 2 * amountOfTokens / 100 ; return _twoPercent; } address burnAddress = 0x000000000000000000000000000000000000dEaD; function getGoldCoin(address _beneficiary) public returns(string memory) { require(_beneficiary != address(0), "It should be real address" ); if(token.balanceOf(_beneficiary) >= 1050 * (10**18)) { token._transfer(_beneficiary, wallet, 50*(10**18)); token._transfer(_beneficiary, burnAddress, 1000 * (10**18)); tokenHolders.push(_beneficiary); return "Hurrah !! You can claim your Gold Coin."; } else { return "Alert !! You should have 1000 GoldT tokens to claim a real Gold Coin."; } } function claimCoin(address claimer) public returns (bytes memory) { require(claimer != address(0),"It should be a real address"); for(uint256 a= 0 ; a<= tokenHolders.length; a++) { if(tokenHolders[a] == claimer) { return 'Congratulations!! You will be rewarded with a physical gold coin. Please connect with us to get your reward.'; break; } } } function getHolders() public onlyOwner returns(address[] memory) { return tokenHolders; } }
Returns the latest price/
function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; }
21,626
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Base Server Address for Token MetaData URI string internal tokenURIBase; /** * @dev Returns an URI for a given token ID. Only returns the based location, you will have to appending a token ID to this * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIBase; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _uri string URI to assign */ function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256(&#39;totalSupply()&#39;)) ^ bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256(&#39;name()&#39;)) ^ bytes4(keccak256(&#39;symbol()&#39;)) ^ bytes4(keccak256(&#39;tokenURI(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256(&#39;exists(uint256)&#39;)); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } contract CCNFTFactory is ERC721Token, OperationalControl { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new asset comes into existence. event AssetCreated(address owner, uint256 assetId, uint256 assetType, uint256 sequenceId, uint256 creationTime); event DetachRequest(address owner, uint256 assetId, uint256 timestamp); event NFTDetached(address requester, uint256 assetId); event NFTAttached(address requester, uint256 assetId); // Mapping from assetId to uint encoded data for NFT mapping(uint256 => uint256) internal nftDataA; mapping(uint256 => uint128) internal nftDataB; // Mapping from Asset Types to count of that type in exsistance mapping(uint32 => uint64) internal assetTypeTotalCount; mapping(uint32 => uint64) internal assetTypeBurnedCount; // Mapping from index of a Asset Type to get AssetID mapping(uint256 => mapping(uint32 => uint64) ) internal sequenceIDToTypeForID; // Mapping from Asset Type to string name of type mapping(uint256 => string) internal assetTypeName; // Mapping from assetType to creation limit mapping(uint256 => uint32) internal assetTypeCreationLimit; // Indicates if attached system is Active (Transfers will be blocked if attached and active) bool public attachedSystemActive; // Is Asset Burning Active bool public canBurn; // Time LS Oracle has to respond to detach requests uint32 public detachmentTime = 300; /** * @dev Constructor function */ constructor() public { require(msg.sender != address(0)); paused = true; error = false; canBurn = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "CCNFTFactory"; symbol_ = "CCNFT"; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); if(isAttached == 2) { //One-Time Auth for Physical Card Transfers require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 1); } else if(attachedSystemActive == true && isAttached >= 1) { require(msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require(isApprovedOrOwner(msg.sender, _tokenId)); } _; } /** Public Functions */ // Returns the AssetID for the Nth assetID for a specific type function getAssetIDForTypeSequenceID(uint256 _seqId, uint256 _type) public view returns (uint256 _assetID) { return sequenceIDToTypeForID[_seqId][uint32(_type)]; } function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ) { require(exists(_assetId)); uint256 nftData = nftDataA[_assetId]; uint256 nftDataBLocal = nftDataB[_assetId]; assetId = _assetId; ownersIndex = ownedTokensIndex[_assetId]; createdTimestamp = uint256(uint48(nftData>>160)); assetType = uint256(uint32(nftData>>208)); assetTypeSeqId = uint256(uint64(nftDataBLocal)); isAttached = uint256(uint48(nftDataBLocal>>64)); creator = address(nftData); owner = ownerOf(_assetId); } function totalSupplyOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)] - assetTypeBurnedCount[uint32(_type)]; } function totalCreatedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeTotalCount[uint32(_type)]; } function totalBurnedOfType(uint256 _type) public view returns (uint256 _totalOfType) { return assetTypeBurnedCount[uint32(_type)]; } function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ) { require(exists(_assetId)); dataA = nftDataA[_assetId]; dataB = nftDataB[_assetId]; } function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; assetType = uint256(uint32(dataA>>208)); } function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ) { require(exists(_assetId)); uint256 dataB = nftDataB[_assetId]; assetTypeSequenceId = uint256(uint64(dataB)); } function getIsNFTAttached( uint256 _assetId) public view returns( uint256 isAttached ) { uint256 nftData = nftDataB[_assetId]; isAttached = uint256(uint48(nftData>>64)); } function getAssetIdCreator(uint256 _assetId) public view returns( address creator ) { require(exists(_assetId)); uint256 dataA = nftDataA[_assetId]; creator = address(dataA); } function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ) { return isApprovedOrOwner(requesterAddress, _assetId); } function getAssetIdOwner(uint256 _assetId) public view returns( address owner ) { require(exists(_assetId)); owner = ownerOf(_assetId); } function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ) { require(exists(_assetId)); ownerIndex = ownedTokensIndex[_assetId]; } /// @param _owner The owner whose ships tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire NFT owners array looking for NFT belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; // We count on the fact that all Asset have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _itemIndex; for (_itemIndex = 0; _itemIndex < tokenCount; _itemIndex++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_itemIndex); resultIndex++; } return result; } } // Get the name of the Asset type function getTypeName (uint32 _type) public returns(string) { return assetTypeName[_type]; } /** * @dev Transfers the ownership of a given token ID to another address, modified to prevent transfer if attached and system is active */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function multiBatchTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function batchTransferFrom(uint256[] _assetIds, address _from, address _to) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; require(isApprovedOrOwner(msg.sender, _id)); require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _id); removeTokenFrom(_from, _id); addTokenTo(_to, _id); emit Transfer(_from, _to, _id); } } function multiBatchSafeTransferFrom( uint256[] _assetIds, address[] _fromB, address[] _toB ) public { uint256 _id; address _to; address _from; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } function batchSafeTransferFrom( uint256[] _assetIds, address _from, address _to ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; safeTransferFrom(_from, _to, _id); } } function batchApprove( uint256[] _assetIds, address _spender ) public { uint256 _id; for (uint256 i = 0; i < _assetIds.length; ++i) { _id = _assetIds[i]; approve(_spender, _id); } } function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require(isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached >= 1); if(attachedSystemActive == true) { //Checks to see if request was made and if time elapsed if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { //Fail if time is already set for attachment require(isAttached == 1); } else { //Is attached, set detachment time and make request to detach emit DetachRequest(msg.sender, _tokenId, block.timestamp); isAttached = block.timestamp; } } else { isAttached = 0; } if(isAttached == 0) { emit NFTDetached(msg.sender, _tokenId); } updateIsAttached(_tokenId, isAttached); } function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = getIsNFTAttached(_tokenId); require(isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit NFTAttached(msg.sender, _tokenId); } function batchAttachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { attachAsset(_ids[i]); } } function batchDetachAssets(uint256[] _ids) public { for(uint i = 0; i < _ids.length; i++) { requestDetachment(_ids[i]); } } function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { //Request can only be made by owner or approved address require(isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } function batchBurnAssets(uint256[] _assetIDs) public { uint256 _id; for(uint i = 0; i < _assetIDs.length; i++) { _id = _assetIDs[i]; burnAsset(_id); } } function burnAsset(uint256 _assetID) public { // Is Burn Enabled require(canBurn == true); // Deny Action if Attached require(getIsNFTAttached(_assetID) == 0); require(isApprovedOrOwner(msg.sender, _assetID) == true); //Updates Type Total Count uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(msg.sender, _assetID); } /** Dev Functions */ function setTokenURIBase (string _tokenURI) public onlyManager { _setTokenURIBase(_tokenURI); } function setPermanentLimitForType (uint32 _type, uint256 _limit) public onlyManager { //Only allows Limit to be set once require(assetTypeCreationLimit[_type] == 0); assetTypeCreationLimit[_type] = uint32(_limit); } function setTypeName (uint32 _type, string _name) public anyOperator { assetTypeName[_type] = _name; } // Minting Function function batchSpawnAsset(address _to, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAsset(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256 _isAttached) public anyOperator { address _to; uint256 _id; uint256 _assetType; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _createAsset(_to, _assetType, _id, _isAttached, address(0)); } } function batchSpawnAssetWithCreator(address[] _toB, uint256[] _assetTypes, uint256[] _assetIds, uint256[] _isAttacheds, address[] _creators) public anyOperator { address _to; address _creator; uint256 _id; uint256 _assetType; uint256 _isAttached; for(uint i = 0; i < _assetIds.length; i++) { _to = _toB[i]; _id = _assetIds[i]; _assetType = _assetTypes[i]; _creator = _creators[i]; _isAttached = _isAttacheds[i]; _createAsset(_to, _assetType, _id, _isAttached, _creator); } } function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, address(0)); } function spawnAssetWithCreator(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached, address _creator) public anyOperator { _createAsset(_to, _assetType, _assetID, _isAttached, _creator); } /// @dev Remove all Ether from the contract, shouldn&#39;t have any but just incase. function withdrawBalance() public onlyBanker { // We are using this boolean method to make sure that even if one fails it will still work bankManager.transfer(address(this).balance); } // Burn Functions function setCanBurn(bool _state) public onlyManager { canBurn = _state; } function burnAssetOperator(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); //Updates Type Total Count uint256 _assetType = getAssetIdItemType(_assetID); assetTypeBurnedCount[uint32(_assetType)] += 1; _burn(ownerOf(_assetID), _assetID); } function toggleAttachedEnforement (bool _state) public onlyManager { attachedSystemActive = _state; } function setDetachmentTime (uint256 _time) public onlyManager { //Detactment Time can not be set greater than 2 weeks. require(_time <= 1209600); detachmentTime = uint32(_time); } function setNFTDetached(uint256 _assetID) public anyOperator { require(getIsNFTAttached(_assetID) > 0); updateIsAttached(_assetID, 0); emit NFTDetached(msg.sender, _assetID); } function setBatchDetachCollectibles(uint256[] _assetIds) public anyOperator { uint256 _id; for(uint i = 0; i < _assetIds.length; i++) { _id = _assetIds[i]; setNFTDetached(_id); } } /** Internal Functions */ // @dev For creating NFT Collectible function _createAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _attachState, address _creator) internal returns(uint256) { uint256 _sequenceId = uint256(assetTypeTotalCount[uint32(_assetType)]) + 1; //Will not allow creation if over limit require(assetTypeCreationLimit[uint32(_assetType)] == 0 || assetTypeCreationLimit[uint32(_assetType)] > _sequenceId); // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. require(_sequenceId == uint256(uint64(_sequenceId))); //Creates NFT _mint(_to, _assetID); uint256 nftData = uint256(_creator); // 160 bit address of creator nftData |= now<<160; // 48 bit creation timestamp nftData |= _assetType<<208; // 32 bit item type uint256 nftDataContinued = uint256(_sequenceId); // 64 bit sequence id of item nftDataContinued |= _attachState<<64; // 48 bit state and/or timestamp for detachment nftDataA[_assetID] = nftData; nftDataB[_assetID] = uint128(nftDataContinued); assetTypeTotalCount[uint32(_assetType)] += 1; sequenceIDToTypeForID[_sequenceId][uint32(_assetType)] = uint64(_assetID); // emit Created event emit AssetCreated(_to, _assetID, _assetType, _sequenceId, now); return _assetID; } function updateIsAttached(uint256 _assetID, uint256 _isAttached) internal { uint256 nftData = nftDataB[_assetID]; uint256 assetTypeSeqId = uint256(uint64(nftData)); uint256 nftDataContinued = uint256(assetTypeSeqId); // 64 bit sequence id of item nftDataContinued |= _isAttached<<64; // 48 bit state and/or timestamp for detachment nftDataB[_assetID] = uint128(nftDataContinued); } }
Internal function to invoke `onERC721Received` on a target address The call is not executed if the target address is not a contract _from address representing the previous owner of the given token ID _to target address that will receive the tokens _tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return whether the call correctly returned the expected magic value/
function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); }
2,379,338
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import {SafeMath} from "../../lib/SafeMath.sol"; import {Ownable} from "../../lib/Ownable.sol"; import {FixedPoint} from "../../lib/FixedPoint.sol"; import {IKeep3rV1} from "./IKeep3rV1.sol"; import {UniswapV2OracleLibrary} from "./UniswapV2OracleLibrary.sol"; import {UniswapV2Library} from "./UniswapV2Library.sol"; /** * @notice A Time-weighted average prices oracle and Keeper job for any uniswap pair */ contract ArcUniswapV2Oracle is Ownable { /* ========== Libraries ========== */ using SafeMath for uint; /* ========== Storage ========== */ IKeep3rV1 public KP3R; address public uniV2Factory; uint public periodWindow = 1 hours; // mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; address[] internal _pairs; mapping(address => bool) internal _known; /* ========== Types ========== */ struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } /* ========== Events ========== */ event WorkDone(address keeper); event UpdatedAll(address caller); event PairUpdated(address pair); event PairAdded(address pair); event PairRemoved(address pair); event Keep3rV1AddressSet(address kp3r); event PeriodWindowSet(uint newPeriodWindow); event UniV2FactorySet(address newUniV2Factory); /* ========== Modifiers ========== */ modifier keeper() { require( KP3R.isKeeper(msg.sender), "isKeeper(): keeper is not registered" ); _; } /* ========== Constructor ========== */ constructor( address _kp3r, address _uniV2Factory ) public { require( _kp3r != address(0) && _uniV2Factory != address(0), "ArcUniswapV2Oracle: Keeper and univ2Factory address must not be null" ); KP3R = IKeep3rV1(_kp3r); uniV2Factory = _uniV2Factory; } /* ========== Keeper Functions ========== */ /** * @notice Updates all pairs. The function to be called by the keeper to be rewarded. */ function work() external keeper { bool worked = _updateAll(); require( worked, "ArcUniswapV2Oracle:work: the work was not completed!" ); KP3R.worked(msg.sender); emit WorkDone(msg.sender); } /* ========== External Functions ========== */ /** * @notice Updates the pair if it is known * @return `true` if the pair was successfully updated */ function updateTokensPair( address _token0, address _token1 ) external returns (bool) { address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1); return updatePair(pair); } /** * @notice Updates the given pair * @param _pair The pair to be updated */ function updatePair(address _pair) public returns (bool) { require( _known[_pair], "ArcUniswapV2Oracle:updatePair(): The pair is not known" ); bool updated = _update(_pair); if (updated) { emit PairUpdated(_pair); } return updated; } /** * @notice Updates all pairs */ function updateAll() external returns (bool) { bool worked = _updateAll(); if (worked) { emit UpdatedAll(msg.sender); } return worked; } /* ========== Public Getters ========== */ function getPairObservations(address _pair) external view returns (Observation[] memory) { return pairObservations[_pair]; } function getPairs() external view returns (address[] memory) { return _pairs; } /** * @notice Returns the last recorded observation for the pair * @param _pair The pair we want the last observation for */ function lastObservation(address _pair) public view returns (Observation memory) { require( _known[_pair], "ArcUniswapV2Oracle:lastObservation(): The pair is not known" ); Observation[] memory foundPairObservations = pairObservations[_pair]; return pairObservations[_pair][foundPairObservations.length - 1]; } /** * @notice returns the last observation for the token pair */ function lastObservationTokens( address _token0, address _token1 ) external view returns (Observation memory) { address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1); require( _known[pair], "ArcUniswapV2Oracle:lastObservationTokens(): The pair is not known" ); Observation[] memory foundPairObservations = pairObservations[pair]; return pairObservations[pair][foundPairObservations.length - 1]; } /** * @notice Returns true if pair is updatable given the period window. Therefore calling work() will yield a reward * @param _pair The pair to make the check for */ function workablePair(address _pair) public view returns (bool) { require( _known[_pair], "ArcUniswapV2Oracle:workablePair(): pair is not known" ); Observation memory observation = lastObservation(_pair); uint timeElapsed = block.timestamp.sub(observation.timestamp); return timeElapsed > periodWindow; } /** * @notice Returns true if pair is updatable given the period window. Therefore calling work() will yield a reward */ function workableTokens( address _token0, address _token1 ) external view returns (bool) { address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1); require( _known[pair], "ArcUniswapV2Oracle:workableTokens(): pair is not known" ); Observation memory observation = lastObservation(pair); uint timeElapsed = block.timestamp.sub(observation.timestamp); return timeElapsed > periodWindow; } /** * @notice Iterates over all known pairs and checks wether there is at least one pair that is updatable */ function workable() external view returns (bool) { for (uint i = 0; i < _pairs.length; i++) { if (workablePair(_pairs[i])) { return true; } } return false; } /** * @notice Returns the pair address of the two tokens */ function pairFor(address _token0, address _token1) external view returns (address) { return UniswapV2Library.pairFor(uniV2Factory, _token0, _token1); } /** * @notice Computes and returns how much of `_tokenOut` you would get if you give `_amountIn` of `_tokenIn` * * @param _tokenIn the address of the token in * @param _amountIn the amount in terms of `_tokenIn` * @param _tokenOut the address of the token out */ function current( address _tokenIn, uint _amountIn, address _tokenOut ) external view returns (uint) { address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenIn, _tokenOut); require( _valid(pair, periodWindow.mul(2)), "ArcUniswapV2Oracle:current(): stale prices" ); (address token0, ) = UniswapV2Library.sortTokens(_tokenIn, _tokenOut); Observation memory observation = lastObservation(pair); (uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); if (block.timestamp == observation.timestamp) { Observation[] memory observationsForPair = pairObservations[pair]; observation = pairObservations[pair][observationsForPair.length.sub(2)]; } uint timeElapsed = block.timestamp.sub(observation.timestamp); timeElapsed = timeElapsed == 0 ? 1 : timeElapsed; if (token0 == _tokenIn) { // prettier-ignore return _computeAmountOut( observation.price0Cumulative, price0Cumulative, timeElapsed, _amountIn ); } else { // prettier-ignore return _computeAmountOut( observation.price1Cumulative, price1Cumulative, timeElapsed, _amountIn ); } } /** * @notice Gives a price quote based on the granularity * @param _tokenIn the token that `_amountIn` is denominated in * @param _amountIn the amount to get the quote for * @param _tokenOut the token that the result is denominated in * @param _granularity the granularity of the quote in terms of time. * Ex. if `_granularity` = 2, the quote will be return a * price based on the `periodWindow` * 2 */ function quote( address _tokenIn, uint _amountIn, address _tokenOut, uint _granularity ) external view returns (uint) { address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenIn, _tokenOut); require( _valid(pair, periodWindow.mul(_granularity)), "ArcUniswapV2Oracle:quote(): stale prices" ); (address token0, ) = UniswapV2Library.sortTokens(_tokenIn, _tokenOut); uint priceAverageCumulative = 0; uint length = pairObservations[pair].length - 1; uint i = length.sub(_granularity); uint nextIndex = 0; if (token0 == _tokenIn) { for (; i < length; i++) { nextIndex = i + 1; priceAverageCumulative += _computeAmountOut( pairObservations[pair][i].price0Cumulative, pairObservations[pair][nextIndex].price0Cumulative, pairObservations[pair][nextIndex].timestamp.sub(pairObservations[pair][i].timestamp), _amountIn ); } } else { for (; i < length; i++) { nextIndex = i + 1; priceAverageCumulative += _computeAmountOut( pairObservations[pair][i].price1Cumulative, pairObservations[pair][nextIndex].price1Cumulative, pairObservations[pair][nextIndex].timestamp.sub(pairObservations[pair][i].timestamp), _amountIn ); } } return priceAverageCumulative.div(_granularity); } /* ========== Owner functions ========== */ /** * @notice Sets the period window */ function setPeriodWindow(uint _periodWindow) external onlyOwner { require( _periodWindow != 0, "ArcUniswapV2Oracle:setPeriodWindow(): period window cannot be 0!" ); periodWindow = _periodWindow; emit PeriodWindowSet(_periodWindow); } /** * @notice Sets the Keep3rV1 address */ function setKeep3rAddress(address _kp3r) external onlyOwner { require( _kp3r != address(0), "ArcUniswapV2Oracle:setKeep3rAddress(): _kp3r must not be null" ); KP3R = IKeep3rV1(_kp3r); emit Keep3rV1AddressSet(_kp3r); } /** * @notice Adds the pair to the known pairs. Will start updating the given pair * @dev the order doesn't matter because they are be sorted later down the road * @param _token0 first token of the pair * @param _token1 second token of the pair */ function addPair( address _token0, address _token1 ) external onlyOwner { address pair = UniswapV2Library.pairFor(uniV2Factory, _token0, _token1); require(!_known[pair], "ArcUniswapV2Oracle:addPair(): already known"); _known[pair] = true; _pairs.push(pair); // Add an observation (uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(pair); pairObservations[pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); emit PairAdded(pair); emit PairUpdated(pair); } /** * @notice Removes a pair */ function removePair( address _tokenA, address _tokenB ) external onlyOwner { address pair = UniswapV2Library.pairFor(uniV2Factory, _tokenA, _tokenB); require( _known[pair], "ArcUniswapV2Oracle:removePair(): pair not added" ); // Remove the pair from the pairs array for (uint i = 0; i < _pairs.length; i++) { if (_pairs[i] == pair) { delete _pairs[i]; _pairs[i] = _pairs[_pairs.length - 1]; _pairs.length--; break; } } delete _known[pair]; delete pairObservations[pair]; emit PairRemoved(pair); } /** * @notice sets the univ2 factory address */ function setUniV2FactoryAddress(address _uniV2Factory) external onlyOwner { require( _uniV2Factory != address(0), "ArcUniswapV2Oracle:setUniV2FactoryAddress(): _uniV2Factory cannot be 0" ); uniV2Factory = _uniV2Factory; emit UniV2FactorySet(_uniV2Factory); } /* ========== Internal Functions ========== */ /** * @dev Updates the pair if within the time window * @param _pair The pair to update */ function _update(address _pair) internal returns (bool) { // we only want to commit updates once per period (i.e. windowSize / granularity) uint timeElapsed = block.timestamp - lastObservation(_pair).timestamp; if (timeElapsed > periodWindow) { (uint price0Cumulative, uint price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(_pair); pairObservations[_pair].push(Observation(block.timestamp, price0Cumulative, price1Cumulative)); return true; } return false; } /** * @dev Loops over all registered pairs and updates them */ function _updateAll() internal returns (bool updated) { for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } /** * @dev Checks wether the pair was updated within `age` time */ function _valid( address _pair, uint _age ) internal view returns (bool) { return block.timestamp.sub(lastObservation(_pair).timestamp) <= _age; } function _computeAmountOut( uint _priceCumulativeStart, uint _priceCumulativeEnd, uint _timeElapsed, uint _amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((_priceCumulativeEnd - _priceCumulativeStart) / _timeElapsed)); FixedPoint.uq144x112 memory priceAverageMultiplied = FixedPoint.mul(priceAverage, _amountIn); return FixedPoint.decode144(priceAverageMultiplied); } }
sets the univ2 factory address/
function setUniV2FactoryAddress(address _uniV2Factory) external onlyOwner { require( _uniV2Factory != address(0), "ArcUniswapV2Oracle:setUniV2FactoryAddress(): _uniV2Factory cannot be 0" ); uniV2Factory = _uniV2Factory; emit UniV2FactorySet(_uniV2Factory); }
1,825,340
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; interface IUniswapZapIn { // zapIn address: 0xE83554B397BdA8ECAE7FEE5aeE532e83Ee9eB29D function ZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount, uint256 _minPoolTokens ) external payable returns (uint256); function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) external pure returns (uint256); } interface IUniswapZapOut { // zapOut: 0x79B6C6F8634ea477ED725eC23b7b6Fcb41F00E58 function ZapOut2PairToken(address _FromUniPoolAddress, uint256 _IncomingLP) external returns (uint256 amountA, uint256 amountB); function ZapOut( address _ToTokenContractAddress, address _FromUniPoolAddress, uint256 _IncomingLP, uint256 _minTokensRec ) external payable returns (uint256); } interface IBalancerZapOut { function EasyZapOut( address _ToTokenContractAddress, address _FromBalancerPoolAddress, uint256 _IncomingBPT, uint256 _minTokensRec ) external payable returns (uint256); } interface IUniswapPipe { // zapPipe address: 0xBdcd4Dcc79bA2C4088323ca94F443a05A23cA372 function PipeUniV2( address payable _toWhomToIssue, address _incomingUniV2Exchange, uint256 _IncomingLPT, address _toUniV2Exchange, uint256 _minPoolTokens ) external returns (uint256 lptReceived); function PipeUniV2WithPermit( address payable _toWhomToIssue, address _incomingUniV2Exchange, uint256 _IncomingLPT, address _toUniV2Exchange, uint256 _minPoolTokens, uint256 _approvalAmount, uint256 _deadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256); }
zapIn address: 0xE83554B397BdA8ECAE7FEE5aeE532e83Ee9eB29D
interface IUniswapZapIn { function ZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount, uint256 _minPoolTokens ) external payable returns (uint256); function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) external pure returns (uint256); pragma solidity >=0.6.0 <0.8.0; }
15,859,985
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "./SongNFTfactory.sol"; import "./TheDropERC20.sol"; /** PlaylistToken is a erc721 factory that creates "playlist" NFTs, empty container-items that keep track of a Leaderboard of songNFTs, voted by a erc20 community. */ contract PlaylistToken is ERC721, ERC721Burnable, ERC721URIStorage, Ownable { //the playlist can be transferred, sold using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; DropRepToken public repTokenAddress; // the erc20 token we shall consider for voting ERC721 songNFTAddress; // the songNFT collection we restrict the playlist to struct Playlist { // we need a Playlist struct for new playlists string name; uint256 playlistID; string playlistMetadata; Song[] songs; mapping(address => uint256) voters; // keep track of the voters so the vote can be discarded. uint256 topScore; } struct Song { address tokenAddress; uint tokenId; uint score; } mapping (uint => Playlist) public playlists; modifier hasRepToken { require(repTokenAddress.balanceOf(msg.sender) >= 1*10**17, "you need 0.1 Reputation Token at least"); _; } constructor(address _songNFTAddr) ERC721("PlayListToken", "PlayList") { repTokenAddress = new DropRepToken(address(this)); songNFTAddress = ERC721(_songNFTAddr); } function safeMint(address to, string memory _nameOfPLaylist, string memory _playlistMetadata) public onlyOwner { uint256 tokenId = _tokenIdCounter.current(); playlists[tokenId].name = _nameOfPLaylist; playlists[tokenId].playlistID = tokenId; playlists[tokenId].playlistMetadata = _playlistMetadata; _tokenIdCounter.increment(); _safeMint(to, tokenId); } function mint(address to, uint256 amount) public onlyOwner { repTokenAddress.mint(to, amount); } // The following functions are overrides required by Solidity. function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } // create a new Song struct out of a songNFT function addSong(uint256 _playlistID, ERC721 _NFTcontract, uint256 _tokenId) external onlyOwner { require(songNFTAddress == _NFTcontract, "Invalid NFT contract address"); // make sure the songNFT belongs to the collection we declared Playlist storage playlist = playlists[_playlistID]; Song memory newsong; newsong.tokenAddress = address(_NFTcontract); newsong.tokenId = _tokenId; newsong.score = 0; playlist.songs.push(newsong); } function upvoteSong (uint256 _playlistID, uint256 index) external /*hasRepToken*/ { Playlist storage playlist = playlists[_playlistID]; Song storage currentSong = playlist.songs[index]; currentSong.score++; // keep track of the voter so he/she can discard the vote. playlist.voters[msg.sender] = index + 1; // 0 means, it's not a voter // upvoting requests msg.sender to burn 0.1 repToken. Alternatively can transfer these erc20 to the Playlist treasury address owner = ERC721(currentSong.tokenAddress).ownerOf(currentSong.tokenId); repTokenAddress.transferFrom(msg.sender, owner, 1*10**17); if (currentSong.score > playlist.topScore) { // update TopScore if it is the highest playlist.topScore = currentSong.score; } } /* function discardVote (uint256 _playlistID) external { // get the playlist. Playlist storage playlist = playlists[_playlistID]; // sender should already have voted in this leaderboard require(playlist.voters[msg.sender] > 0, "sender should be a voter"); // get the song the sender has voted for. uint songId = playlist.voters[msg.sender] - 1; // reinitialize msg.sender as non-voter and continue. playlist.voters[msg.sender] = 0; // get the song. Song storage currentSong = playlist.songsMetadata[songId]; currentSong.score--; playlist.songScore[currentSong.tokenId] -= 1; } */ function getPlaylistSongs(uint _playlistID) public view returns(Song[] memory) { Playlist storage playlist = playlists[_playlistID]; return playlist.songs; } }
keep track of the voter so he/she can discard the vote. upvoting requests msg.sender to burn 0.1 repToken. Alternatively can transfer these erc20 to the Playlist treasury
function upvoteSong (uint256 _playlistID, uint256 index) external /*hasRepToken*/ { Playlist storage playlist = playlists[_playlistID]; Song storage currentSong = playlist.songs[index]; currentSong.score++; address owner = ERC721(currentSong.tokenAddress).ownerOf(currentSong.tokenId); repTokenAddress.transferFrom(msg.sender, owner, 1*10**17); playlist.topScore = currentSong.score; }
12,994,456
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity >=0.6.2 <0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Nuggs.sol pragma solidity 0.7.0; /** * @title Nuggs contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract Nuggs is ERC721, Ownable { using SafeMath for uint256; uint256 private NuggsPrice = 0.0420 ether; uint public constant maxNuggsPurchase = 20; uint256 public MAX_Nuggs = 8400; bool public saleIsActive = false; uint256 public startingIndexBlock; uint256 public startingIndex; address nw = 0x6D03aec79B611a904Dc12262720D82ec6E860c88; address dw = 0x92bD5583A20853A1C88521C27e8CcB8Bd9e7cC3B; address dv = 0xd7DBe51f9EBf734A5fd55C18002a063c6881d8b4; constructor() ERC721("Nuggs.wtf", "NUGG") { } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(nw).transfer((balance*45)/100); payable(dw).transfer((balance*10)/100); payable(dv).transfer((balance*45)/100); payable(msg.sender).transfer(address(this).balance); } function reserveNuggs() public onlyOwner { uint supply= totalSupply(); uint i; for (i = 1; i < 101; i++) { _safeMint(msg.sender, supply + i); } } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function getPrice() public view returns (uint256){ return NuggsPrice; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } /** * Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_Nuggs; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_Nuggs; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function SetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner() { NuggsPrice = _newPrice; } function mintNuggs(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint Nuggs"); require(numberOfTokens <= maxNuggsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_Nuggs, "Purchase would exceed max supply of Nuggs"); require(NuggsPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply() + 1; if (totalSupply() < MAX_Nuggs) { _safeMint(msg.sender, mintIndex); } } } }
Set the starting index for the collection/ Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) Prevent default sequence
function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_Nuggs; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_Nuggs; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } }
1,437,499
pragma solidity ^0.4.24; /* Big Thanks from the Document crew to chuckbergeron for providing this template and Andrew Parker for creating the tutorial on building NFT's. Also, thanks to the ethereum team for providing the ERC721 standard. Code is Law! */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SupportsInterfaceWithLookup * @author Matt Condon (@shrugs) * @dev Implements ERC165 using a lookup table. */ contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ /** * @dev a mapping of interface id to whether or not it's supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } contract Document is ERC721Token, Ownable { /*** EVENTS ***/ /// The event emitted (useable by web3) when a token is purchased event BoughtToken(address indexed buyer, uint256 tokenId); /*** CONSTANTS ***/ uint8 constant TITLE_MIN_LENGTH = 1; uint8 constant TITLE_MAX_LENGTH = 64; uint256 constant DESCRIPTION_MIN_LENGTH = 1; uint256 constant DESCRIPTION_MAX_LENGTH = 10000; /*** DATA TYPES ***/ /// Price set by contract owner for each token in Wei. /// @dev If you'd like a different price for each token type, you will /// need to use a mapping like: `mapping(uint256 => uint256) tokenTypePrices;` uint256 currentPrice = 0; /// The token type (1 for idea, 2 for belonging, etc) mapping(uint256 => uint256) tokenTypes; /// The title of the token mapping(uint256 => string) tokenTitles; /// The description of the token mapping(uint256 => string) tokenDescription; constructor() ERC721Token("Document", "DQMT") public { // any init code when you deploy the contract would run here } /// Requires the amount of Ether be at least or more of the currentPrice /// @dev Creates an instance of an token and mints it to the purchaser /// @param _type The token type as an integer /// @param _title The short title of the token /// @param _description Description of the token function buyToken ( uint256 _type, string _title, string _description ) external payable { bytes memory _titleBytes = bytes(_title); require(_titleBytes.length >= TITLE_MIN_LENGTH, "Title is too short"); require(_titleBytes.length <= TITLE_MAX_LENGTH, "Title is too long"); bytes memory _descriptionBytes = bytes(_description); require(_descriptionBytes.length >= DESCRIPTION_MIN_LENGTH, "Description is too short"); require(_descriptionBytes.length <= DESCRIPTION_MAX_LENGTH, "Description is too long"); require(msg.value >= currentPrice, "Amount of Ether sent too small"); uint256 index = allTokens.length + 1; _mint(msg.sender, index); tokenTypes[index] = _type; tokenTitles[index] = _title; tokenDescription[index] = _description; emit BoughtToken(msg.sender, index); } /** * @dev Returns all of the tokens that the user owns * @return An array of token indices */ function myTokens() external view returns ( uint256[] ) { return ownedTokens[msg.sender]; } /// @notice Returns all the relevant information about a specific token /// @param _tokenId The ID of the token of interest function viewToken(uint256 _tokenId) external view returns ( uint256 tokenType_, string tokenTitle_, string tokenDescription_ ) { tokenType_ = tokenTypes[_tokenId]; tokenTitle_ = tokenTitles[_tokenId]; tokenDescription_ = tokenDescription[_tokenId]; } /// @notice Allows the owner of this contract to set the currentPrice for each token function setCurrentPrice(uint256 newPrice) public onlyOwner { currentPrice = newPrice; } /// @notice Returns the currentPrice for each token function getCurrentPrice() external view returns ( uint256 price ) { price = currentPrice; } /// @notice allows the owner of this contract to destroy the contract function kill() public { if(msg.sender == owner) selfdestruct(owner); } }
Internal function to mint a new token Reverts if the given token ID already exists _to The address that will own the minted token _tokenId uint256 ID of the token to be minted by the msg.sender/
function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); }
7,013,786
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./openzeppelin/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "./openzeppelin/access/OwnableUpgradeable.sol"; import "./openzeppelin/security/PausableUpgradeable.sol"; import "./abstract/Generator.sol"; import "./abstract/Whitelist.sol"; import "./interface/ISerum.sol"; import "./interface/IMetadata.sol"; import "./interface/IBlueprint.sol"; error NotWhitelisted(address _account); error InvalidMintAmount(uint256 _amount); error LimitExceeded(address _account); error SoldOut(); error GenerationLimit(uint256 _generation); error NotEnoughEther(uint256 _given, uint256 _expected); error InvalidBurnLength(uint256 _given, uint256 _expected); error BurnNotOwned(address _sender, uint256 _tokenId); error InvalidBurnGeneration(uint256 _given, uint256 _expected); error BlueprintNotReady(); error EarlyMintIsEnabled(); error EarlyMintNotEnabled(); // LabGame V2.0 contract LabGame is ERC721EnumerableUpgradeable, OwnableUpgradeable, PausableUpgradeable, Generator, Whitelist { uint256 constant GEN0_PRICE = 0 ether; // @since V2.0 Free mint uint256 constant GEN1_PRICE = 5_000 ether; uint256 constant GEN2_PRICE = 12_500 ether; uint256 constant GEN3_PRICE = 45_000 ether; uint256 constant GEN0_MAX = 1_111; uint256 constant GEN1_MAX = 2_222; uint256 constant GEN2_MAX = 3_333; uint256 constant GEN3_MAX = 4_444; uint256 constant WHITELIST_MINT_LIMIT = 2; uint256 constant PUBLIC_MINT_LIMIT = 5; uint256 constant EXTRA_MINT_LIMIT = 20; uint256 constant MAX_TRAITS = 16; uint256 constant TYPE_OFFSET = 9; mapping(uint256 => uint256) tokens; mapping(address => uint256) whitelistMints; mapping(address => uint256) publicMints; uint256 tokenOffset; ISerum public serum; IMetadata public metadata; IBlueprint public blueprint; uint8[][MAX_TRAITS] rarities; uint8[][MAX_TRAITS] aliases; bool public earlyMintEnabled; // @since V2.0 mapping(address => bool) public extraMintAccounts; /** * LabGame constructor * @param _name ERC721 name * @param _symbol ERC721 symbol * @param _serum Serum contract address * @param _metadata Metadata contract address * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function initialize( string memory _name, string memory _symbol, address _serum, address _metadata, address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); __Pausable_init(); __Generator_init(_vrfCoordinator, _keyHash, _subscriptionId, _callbackGasLimit); __Whitelist_init(); serum = ISerum(_serum); metadata = IMetadata(_metadata); // Setup rarity and alias tables for token traits rarities[0] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[0] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[1] = [89, 236, 255, 44, 179, 249, 134]; aliases[1] = [2, 2, 0, 1, 5, 2, 5]; rarities[2] = [50, 73, 96, 119, 142, 164, 187, 210, 233, 255, 28]; aliases[2] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0]; rarities[3] = [255, 128, 255, 192, 128, 192, 255, 255, 255, 64, 255, 255, 64, 255, 128, 255, 128, 128, 255, 128, 255, 255, 128, 255, 255]; aliases[3] = [0, 6, 0, 24, 7, 24, 0, 0, 0, 3, 0, 0, 5, 0, 8, 0, 11, 15, 0, 18, 0, 0, 20, 0, 0]; rarities[4] = [199, 209, 133, 255, 209, 209, 255, 133, 255, 133, 199, 255, 199, 66, 66, 199, 255, 133, 255, 255, 66, 255, 255, 66, 250, 240]; aliases[4] = [22, 24, 8, 0, 24, 25, 0, 11, 0, 16, 24, 0, 25, 25, 1, 22, 0, 19, 0, 0, 4, 0, 0, 5, 8, 22]; rarities[5] = [255, 204, 255, 204, 40, 235, 204, 204, 235, 204, 204, 40, 204, 204, 204, 204]; aliases[5] = [0, 5, 0, 8, 0, 0, 5, 8, 2, 5, 8, 2, 5, 8, 5, 8]; rarities[6] = [158, 254, 220, 220, 158, 158, 220, 220, 220, 220, 158, 158, 238, 79, 158, 238, 79, 220, 220, 238, 158, 220, 245, 245, 245, 253, 158, 255, 253, 158, 253]; aliases[6] = [2, 27, 22, 23, 3, 6, 24, 25, 28, 30, 7, 8, 25, 1, 9, 28, 27, 22, 23, 30, 17, 24, 25, 28, 30, 1, 18, 0, 27, 21, 1]; rarities[7] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]; aliases[7] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; rarities[8] = [112, 112, 160, 160, 208, 64, 64, 208, 255, 255]; aliases[8] = [2, 3, 4, 7, 8, 0, 1, 9, 0, 0]; rarities[9] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[9] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[10] = [235, 250, 46, 30, 255, 76]; aliases[10] = [4, 4, 1, 0, 0, 4]; rarities[11] = [153, 204, 255, 102]; aliases[11] = [1, 2, 0, 0]; rarities[12] = [81, 138, 133, 30, 184, 189, 189, 138, 235, 240, 240, 255]; aliases[12] = [2, 5, 4, 0, 8, 9, 10, 6, 11, 11, 11, 0]; rarities[13] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[13] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[14] = [76, 192, 255]; aliases[14] = [2, 2, 0]; rarities[15] = [236, 236, 224, 224, 249, 249, 255]; aliases[15] = [4, 5, 0, 1, 6, 6, 0]; } // -- EXTERNAL -- // @since V2.0 - Whitelist mint no longer needed /** * Mint scientists & mutants * @param _amount Number of tokens to mint * @param _burnIds Token Ids to burn as payment (for gen 1 & 2) */ function mint(uint256 _amount, uint256[] calldata _burnIds) external payable whenNotPaused { if (earlyMintEnabled) revert EarlyMintIsEnabled(); uint256 publicMintCount = publicMints[_msgSender()]; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > PUBLIC_MINT_LIMIT) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); if (id >= GEN3_MAX) revert SoldOut(); uint256 max = id + _amount; uint256 generation; // Generation 0 if (id < GEN0_MAX) { if (max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); uint256 whitelistMintCount = whitelistMints[_msgSender()]; if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > PUBLIC_MINT_LIMIT) || (publicMintCount + _amount > PUBLIC_MINT_LIMIT) ) revert LimitExceeded(_msgSender()); // Generation 1 } else if (id < GEN1_MAX) { if (max > GEN1_MAX) revert GenerationLimit(1); serum.burn(_msgSender(), _amount * GEN1_PRICE); generation = 1; // Generation 2 } else if (id < GEN2_MAX) { if (max > GEN2_MAX) revert GenerationLimit(2); serum.burn(_msgSender(), _amount * GEN2_PRICE); generation = 2; // Generation 3 } else if (id < GEN3_MAX) { if (address(blueprint) == address(0)) revert BlueprintNotReady(); if (max > GEN3_MAX) revert GenerationLimit(3); serum.burn(_msgSender(), _amount * GEN3_PRICE); generation = 3; } // Burn tokens to mint gen 1, 2, and 3 uint256 burnLength = _burnIds.length; if (generation != 0) { if (burnLength != _amount) revert InvalidBurnLength(burnLength, _amount); for (uint256 i; i < burnLength; i++) { // Verify token to be burned if (_msgSender() != ownerOf(_burnIds[i])) revert BurnNotOwned(_msgSender(), _burnIds[i]); if (tokens[_burnIds[i]] & 3 != generation - 1) revert InvalidBurnGeneration(tokens[_burnIds[i]] & 3, generation - 1); _burn(_burnIds[i]); } // Add burned tokens to id offset tokenOffset += burnLength; // Generation 0 no burn needed } else { if (burnLength != 0) revert InvalidBurnLength(burnLength, 0); } publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { uint256 seed = _random(i); _revealToken(i, seed); } } function earlyMint(uint256 _amount) external whenNotPaused { if (!earlyMintEnabled) revert EarlyMintNotEnabled(); // Only when early mint enabled uint256 whitelistMintCount = whitelistMints[_msgSender()]; uint256 publicMintCount = publicMints[_msgSender()]; bool hasExtraMints = extraMintAccounts[_msgSender()]; if (whitelistMintCount == 0 && publicMintCount == 0 && hasExtraMints == false) revert EarlyMintIsEnabled(); uint256 limit = hasExtraMints ? EXTRA_MINT_LIMIT : PUBLIC_MINT_LIMIT; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > limit) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); uint256 max = id + _amount; if (id >= GEN0_MAX || max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > limit) || (publicMintCount + _amount > limit) ) revert LimitExceeded(_msgSender()); publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { _revealToken(i, _random(i)); } } /** * Reveal pending mints */ function reveal() external whenNotPaused { (, uint256 count) = pendingOf(_msgSender()); _reveal(_msgSender()); // Tokens minted, update offset tokenOffset -= count; } /** * Get the metadata uri for a token * @param _tokenId Token ID to query * @return Token metadata json URI */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return metadata.tokenURI(_tokenId); } /** * Get the total number of minted tokens * @return Total number of minted tokens */ function totalMinted() public view returns (uint256) { return totalSupply() + tokenOffset; } /** * Get the data of a token * @param _tokenId Token ID to query * @return Token structure */ function getToken(uint256 _tokenId) external view returns (uint256) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return tokens[_tokenId]; } // -- INTERNAL -- function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override { super._beforeTokenTransfer(_from, _to, _tokenId); // Update serum claim on transfer and burn if (_from != address(0)) serum.updateClaim(_from, _tokenId); } /** * Generate and mint pending token using random seed * @param _tokenId Token ID to reveal * @param _seed Random seed */ function _revealToken(uint256 _tokenId, uint256 _seed) internal override { // Calculate generation of token uint256 token; if (_tokenId <= GEN0_MAX) {} else if (_tokenId <= GEN1_MAX) token = 1; else if (_tokenId <= GEN2_MAX) token = 2; else if (_tokenId <= GEN3_MAX) token = 3; // Select scientist or mutant // @since V2.0 Mint mutants at 2% token |= (((_seed & 0xFFFF) % 100) < 2) ? 128 : 0; // Loop over tokens traits (9 scientist, 8 mutant) (uint256 start, uint256 count) = (token & 128 != 0) ? (TYPE_OFFSET, MAX_TRAITS - TYPE_OFFSET) : (0, TYPE_OFFSET); for (uint256 i; i < count; i++) { _seed >>= 16; token |= _selectTrait(_seed, start + i) << (8 * i + 8); } // Save traits tokens[_tokenId] = token; // Mint token _safeMint(_msgSender(), _tokenId); // Setup serum claim for token serum.initializeClaim(_tokenId); // Mint blueprint to gen3 tokens if (token & 3 == 3) blueprint.mint(_msgSender(), _seed >> 16); } /** * Select a trait from the alias tables using a random seed (16 bit) * @param _seed Random seed * @param _trait Trait to select * @return Index of the selected trait */ function _selectTrait(uint256 _seed, uint256 _trait) internal view returns (uint256) { uint256 i = (_seed & 0xFF) % rarities[_trait].length; return (((_seed >> 8) & 0xFF) < rarities[_trait][i]) ? i : aliases[_trait][i]; } /** * Generate a psuedo-random number * @param _seed Seed for the RNG * @return Random 256 bit number */ function _random(uint256 _seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, _seed ))); } // -- OWNER -- /** * Enable/disable holder only early mint */ function setEarlyMintEnabled(bool _earlyMintEnabled) external onlyOwner { earlyMintEnabled = _earlyMintEnabled; } /** * Add account to the early mint * @param _accounts Account to add */ function addEarlyMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) whitelistMints[_accounts[i]]++; } /** * Add account to the extra mint list * @param _accounts Account to add */ function addExtraMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) extraMintAccounts[_accounts[i]] = true; } /** * Pause the contract */ function pause() external onlyOwner { _pause(); } /** * Unpause the contract */ function unpause() external onlyOwner { _unpause(); } /** * Set blueprint contract * @param _blueprint Address of the blueprint contract */ function setBlueprint(address _blueprint) external onlyOwner { blueprint = IBlueprint(_blueprint); } /** * Withdraw funds to owner */ function withdraw() external onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ error ERC721Enumerable_IndexOutOfBounds(uint256 index, uint256 max); abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { if (index >= ERC721Upgradeable.balanceOf(owner)) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721Upgradeable.balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { if (index >= ERC721EnumerableUpgradeable.totalSupply()) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721EnumerableUpgradeable.totalSupply()); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ error Ownable_CallerNotOwner(address caller, address owner); error Ownable_NewOwnerZeroAddress(); abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (owner() != _msgSender()) revert Ownable_CallerNotOwner(_msgSender(), owner()); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ error Pausable_Paused(); error Pausable_NotPaused(); abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { if (paused()) revert Pausable_Paused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { if (!paused()) revert Pausable_NotPaused(); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./VRFConsumerBaseV2Upgradable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error AccountHasPendingMint(address _account); error AcountHasNoPendingMint(address _account); error InvalidAccount(); error InvalidRequestBase(); error InvalidRequestCount(); error RevealNotReady(); abstract contract Generator is VRFConsumerBaseV2Upgradable { VRFCoordinatorV2Interface internal vrfCoordinator; bytes32 internal keyHash; uint64 internal subscriptionId; uint32 internal callbackGasLimit; struct Mint { uint64 base; uint32 count; uint256[] random; } mapping(uint256 => address) internal mintRequests; mapping(address => Mint) internal pendingMints; event Requested(address indexed _account, uint256 _baseId, uint256 _count); event Pending(address indexed _account, uint256 _baseId, uint256 _count); event Revealed(address indexed _account, uint256 _tokenId); /** * Constructor to initialize VRF * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function __Generator_init( address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) internal onlyInitializing { __VRFConsumerBaseV2_init(_vrfCoordinator); vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator); keyHash = _keyHash; subscriptionId = _subscriptionId; callbackGasLimit = _callbackGasLimit; } // -- PUBLIC -- modifier zeroPending(address _account) { if (pendingMints[_account].base != 0) revert AccountHasPendingMint(_account); _; } /** * Get the current pending mints of a user account * @param _account Address of account to query * @return Pending token base ID, amount of pending tokens */ function pendingOf(address _account) public view returns (uint256, uint256) { return (pendingMints[_account].base, pendingMints[_account].random.length); } // -- INTERNAL -- /** * Update pending mint with response from VRF * @param _requestId Request ID that was fulfilled * @param _randomWords Received random numbers */ function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal virtual override { // Pop request address account = mintRequests[_requestId]; delete mintRequests[_requestId]; // Update pending mints with received random numbers pendingMints[account].random = _randomWords; // Ready to reveal emit Pending(account, pendingMints[account].base, _randomWords.length); } /** * Setup a pending mint and request numbers from VRF * @param _account Account to request for * @param _base Base token ID * @param _count Number of tokens */ function _request(address _account, uint256 _base, uint256 _count) internal zeroPending(_account) { if (_account == address(0)) revert InvalidAccount(); if (_base == 0) revert InvalidRequestBase(); if (_count == 0) revert InvalidRequestCount(); // Request random numbers for tokens, save request id to account uint256 requestId = vrfCoordinator.requestRandomWords( keyHash, subscriptionId, 3, callbackGasLimit, uint32(_count) ); mintRequests[requestId] = _account; // Initialize mint request with id and count pendingMints[_account].base = uint64(_base); pendingMints[_account].count = uint32(_count); // Mint requested emit Requested(_account, _base, _count); } /** * Reveal pending tokens with received random numbers * @param _account Account to reveal for */ function _reveal(address _account) internal { if (_account == address(0)) revert InvalidAccount(); Mint memory mint = pendingMints[_account]; if (mint.base == 0) revert AcountHasNoPendingMint(_account); if (mint.random.length == 0) revert RevealNotReady(); delete pendingMints[_account]; // Generate all tokens for (uint256 i; i < mint.count; i++) { _revealToken(mint.base + i, mint.random[i]); emit Revealed(_account, mint.base + i); } } /** * Abstract function called on each token when revealing * @param _tokenId Token ID to reveal * @param _seed Random number from VRF for the token */ function _revealToken(uint256 _tokenId, uint256 _seed) internal virtual; /** * Set the VRF key hash * @param _keyHash New keyHash */ function _setKeyHash(bytes32 _keyHash) internal { keyHash = _keyHash; } /** * Set the VRF subscription ID * @param _subscriptionId New subscriptionId */ function _setSubscriptionId(uint64 _subscriptionId) internal { subscriptionId = _subscriptionId; } /** * Set the VRF callback gas limit * @param _callbackGasLimit New callbackGasLimit */ function _setCallbackGasLimit(uint32 _callbackGasLimit) internal { callbackGasLimit = _callbackGasLimit; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error WhitelistIsEnabled(); error WhitelistNotEnabled(); abstract contract Whitelist is Initializable { bytes32 internal merkleRoot; event WhitelistEnabled(); event WhitelistDisabled(); /** Whitelist contstructor (empty) */ function __Whitelist_init() internal onlyInitializing {} function whitelisted() public view returns (bool) { return merkleRoot != bytes32(0); } modifier whenWhitelisted { if (!whitelisted()) revert WhitelistNotEnabled(); _; } modifier whenNotWhitelisted { if (whitelisted()) revert WhitelistIsEnabled(); _; } /** * Checks if an account is whitelisted using the given proof * @param _account Account to verify * @param _merkleProof Proof to verify the account is in the merkle tree */ function _whitelisted(address _account, bytes32[] calldata _merkleProof) internal view returns (bool) { return MerkleProofUpgradeable.verify(_merkleProof, merkleRoot, keccak256(abi.encodePacked(_account))); } /** * Enable the whitelist and set the merkle tree root * @param _merkleRoot Whitelist merkle tree root hash */ function _enableWhitelist(bytes32 _merkleRoot) internal { if (whitelisted()) revert WhitelistIsEnabled(); merkleRoot = _merkleRoot; emit WhitelistEnabled(); } /** * Disable the whitelist and clear the root hash */ function _disableWhitelist() internal { if (!whitelisted()) revert WhitelistNotEnabled(); delete merkleRoot; emit WhitelistDisabled(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./IClaimable.sol"; interface ISerum is IClaimable { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IMetadata { function tokenURI(uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IBlueprint { function mint(address _account, uint256 _seed) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ error ERC721_QueryOnZeroAddress(); error ERC721_QueryForNonexistentToken(uint256 tokenId); error ERC721Metadata_QueryForNonexistentToken(uint256 tokenId); error ERC721_ApprovalToCurrentOwner(address owner); error ERC721_CallerNotOwnerOrApproved(address caller); error ERC721_TransferToNonReceiverImplementer(address to, uint256 tokenId); error ERC721_MintToZeroAddress(uint256 tokenId); error ERC721_TokenAlreadyMinted(uint256 tokenId); error ERC721_TransferFromIncorrectOwner(address from, address expected); error ERC721_TransferToZeroAddress(uint256 tokenId); error ERC721_ApprovalToCaller(address caller); contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert ERC721_QueryOnZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; if (owner == address(0)) revert ERC721_QueryForNonexistentToken(tokenId); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert ERC721Metadata_QueryForNonexistentToken(tokenId); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); if (to == owner) revert ERC721_ApprovalToCurrentOwner(to); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { if (to == address(0)) revert ERC721_MintToZeroAddress(tokenId); if (_exists(tokenId)) revert ERC721_TokenAlreadyMinted(tokenId); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { if (ERC721Upgradeable.ownerOf(tokenId) != from) revert ERC721_TransferFromIncorrectOwner(from, ERC721Upgradeable.ownerOf(tokenId)); if (to == address(0)) revert ERC721_TransferToZeroAddress(tokenId); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { if (owner == operator) revert ERC721_ApprovalToCaller(owner); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ error Initializable_AlreadyInitialized(); error Initializable_NotInitializing(); abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized(); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { if (!_initializing) revert Initializable_NotInitializing(); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; /** * @dev Collection of functions related to the address type */ error Address_InsufficientBalance(uint256 balance, uint256 amount); error Address_UnableToSendValue(address recipient, uint256 amount); error Address_CallToNonContract(address target); error Address_StaticCallToNonContract(address target); library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount); (bool success, ) = recipient.call{value: amount}(""); if (!success) revert Address_UnableToSendValue(recipient, amount); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value); if (!isContract(target)) revert Address_CallToNonContract(target); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { if (!isContract(target)) revert Address_StaticCallToNonContract(target); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "../openzeppelin/proxy/utils/Initializable.sol"; // Modified to use OpenZeppelin upgradeables /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously. * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2Upgradable is Initializable { error OnlyCoordinatorCanFulfill(address have, address want); address private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ function __VRFConsumerBaseV2_init(address _vrfCoordinator) internal onlyInitializing { vrfCoordinator = _vrfCoordinator; } /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Get configuration relevant for making requests * @return minimumRequestConfirmations global min for request confirmations * @return maxGasLimit global max for request gas limit * @return s_provingKeyHashes list of registered key hashes */ function getRequestConfig() external view returns ( uint16, uint32, bytes32[] memory ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with the minimum subscription balance required for the selected keyHash. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [0, maxGasLimit] * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns (uint256 requestId); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns (uint64 subId); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return reqCount - number of requests for this subscription, determines fee tier. * @return owner - owner of the subscription. * @return consumers - list of consumer address which are able to use this subscription. */ function getSubscription(uint64 subId) external view returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer(uint64 subId) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer(uint64 subId, address consumer) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer(uint64 subId, address consumer) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription(uint64 subId, address to) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProofUpgradeable { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; error NoClaimAvailable(address _account); interface IClaimable { function claim() external; function pendingClaim(address _account) external view returns (uint256); function initializeClaim(uint256 _tokenId) external; function updateClaim(address _account, uint256 _tokenId) external; event Claimed(address indexed _account, uint256 _amount); event Updated(address indexed _account, uint256 indexed _tokenId); }
Reveal pending tokens with received random numbers _account Account to reveal for/ Generate all tokens
function _reveal(address _account) internal { if (_account == address(0)) revert InvalidAccount(); Mint memory mint = pendingMints[_account]; if (mint.base == 0) revert AcountHasNoPendingMint(_account); if (mint.random.length == 0) revert RevealNotReady(); delete pendingMints[_account]; for (uint256 i; i < mint.count; i++) { _revealToken(mint.base + i, mint.random[i]); emit Revealed(_account, mint.base + i); } }
6,147,345
./full_match/1/0x2fC246149B4B8d7bcEF6188A10AF1791380227f1/sources/src/StarterPack/StarterPackV1.sol
Get current StarterPack prices return prices Array of prices
function getStarterPackPrices() external view returns (uint256[] memory prices) { return _starterPackPrices; }
8,434,663
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; interface Decimals { function decimals() external view returns (uint8); } // import "contracts/interfaces/IUniswapV2Factory.sol"; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // import "contracts/interfaces/IUniswapV2Router01.sol"; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // import "contracts/interfaces/IIronSwap.sol"; interface IIronSwap { /// EVENTS event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event TokenExchange( address indexed buyer, uint256 soldId, uint256 tokensSold, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 tokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 tokenIndex, uint256 tokenAmount, uint256 coinAmount ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 A, uint256 timestamp); event NewFee(uint256 fee, uint256 adminFee, uint256 withdrawFee); event CollectProtocolFee(address token, uint256 amount); event FeeControllerChanged(address newController); event FeeDistributorChanged(address newController); // pool data view functions function getLpToken() external view returns (IERC20 lpToken); function getA() external view returns (uint256); function getAPrecise() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokens() external view returns (IERC20[] memory); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getTokenBalances() external view returns (uint256[] memory); function getNumberOfTokens() external view returns (uint256); function getVirtualPrice() external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); function getAdminBalances() external view returns (uint256[] memory adminBalances); function getAdminBalance(uint8 index) external view returns (uint256); function calculateCurrentWithdrawFee(address account) external view returns (uint256); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; function withdrawAdminFee() external; } // import "contracts/interfaces/IIronRoute.sol"; interface IIronRoute { function calculateSwapFromBase( IIronSwap pool, IIronSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapToBase( IIronSwap pool, IIronSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function swapFromBase( IIronSwap pool, IIronSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapToBase( IIronSwap pool, IIronSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); } // import "contracts/interfaces/IIron3usdFarm.sol"; interface IIron3usdFarm { event Deposit( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, address indexed lpToken, address indexed rewarder ); event LogRewardPerSecond(uint256 rewardPerSecond); event LogSetPool( uint256 indexed pid, uint256 allocPoint, address indexed rewarder, bool overwrite ); event LogUpdatePool( uint256 indexed pid, uint256 lastRewardTime, uint256 lpSupply, uint256 accRewardPerShare ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event PoolFundChanged(address indexed fund); event Withdraw( address indexed user, uint256 indexed pid, uint256 amount, address indexed to ); function add( uint256 allocPoint, address _lpToken, address _rewarder ) external; function deposit( uint256 pid, uint256 amount, address to ) external; function emergencyWithdraw(uint256 pid, address to) external; function fund() external view returns (address); function harvest(uint256 pid, address to) external; function harvestAllRewards(address to) external; function lpToken(uint256) external view returns (address); function massUpdatePools(uint256[] memory pids) external; function owner() external view returns (address); function pendingReward(uint256 _pid, address _user) external view returns (uint256 pending); function poolInfo(uint256) external view returns ( uint256 accRewardPerShare, uint256 lastRewardTime, uint256 allocPoint ); function poolLength() external view returns (uint256 pools); function renounceOwnership() external; function reward() external view returns (address); function rewardPerSecond() external view returns (uint256); function rewarder(uint256) external view returns (address); function set( uint256 _pid, uint256 _allocPoint, address _rewarder, bool overwrite ) external; function setFund(address _fund) external; function setRewardPerSecond(uint256 _rewardPerSecond) external; function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 pid) external returns (IronChef.PoolInfo memory pool); function userInfo(uint256, address) external view returns (uint256 amount, int256 rewardDebt); function withdraw( uint256 pid, uint256 amount, address to ) external; function withdrawAndHarvest( uint256 pid, uint256 amount, address to ) external; } interface IronChef { struct PoolInfo { uint256 accRewardPerShare; uint256 lastRewardTime; uint256 allocPoint; } } // import "contracts/interfaces/IFirebirdRoute.sol"; interface IFirebirdRoute { function acceptContractDepositor() external view returns (bool); function deposit( address _vault, uint256 _amount, uint256 _min_mint_amount ) external; function exit(address _vault, uint256 _min_output_amount) external; function governance() external view returns (address); function governanceRecoverUnsupported( address _token, uint256 amount, address to ) external; function harvestAllStrategies(address _vault) external; function harvestStrategy(address _vault, address _strategy) external; function initialize(address _vaultMaster) external; function setAcceptContractDepositor(bool _acceptContractDepositor) external; function setGovernance(address _governance) external; function setStrategist(address _strategist) external; function setVaultMaster(address _vaultMaster) external; function strategist() external view returns (address); function unwhitelistContract(address _contract) external; function vaultMaster() external view returns (address); function whitelistContract(address _contract) external; function whitelistedContract(address) external view returns (bool); function withdraw( address _vault, uint256 _shares, uint256 _min_output_amount ) external; } // import "contracts/interfaces/IFirebirdStakingPool.sol"; interface IFirebirdStakingPool { event Commission( address indexed user, address indexed referrer, uint256 amount ); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition( uint256 indexed pid, uint256 allocPoint, address indexed lpToken, address indexed rewarder ); event LogRewardPerSecond(uint256 rewardPerSecond); event LogSetPool( uint256 indexed pid, uint256 allocPoint, address indexed rewarder ); event LogUpdatePool( uint256 indexed pid, uint256 lastRewardTime, uint256 lpSupply, uint256 accHopePerShare ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event WithdrawFee( address indexed user, uint256 indexed pid, uint256 amount, uint256 fee ); function add( uint256 _allocPoint, address _lpToken, address _rewarder, uint256 _lastRewardTime ) external; function commissionPercent() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function depositWithRef( uint256 _pid, uint256 _amount, address _referrer ) external; function devFund() external view returns (address); function devPercent() external view returns (uint256); function emergencyWithdraw(uint256 _pid) external; function enterStaking(uint256 _amount) external; function enterStakingWithRef(uint256 _amount, address _referrer) external; function governanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external; function halvingChecked() external view returns (bool); function harvestAllRewards() external; function harvestAndRestake() external; function hope() external view returns (address); function initialize( address _hope, uint256 _totalRewardPerSecond, uint256 _startTime ) external; function leaveStaking(uint256 _amount) external; function massUpdatePools() external; function nextHalvingTime() external view returns (uint256); function owner() external view returns (address); function pendingReward(uint256 _pid, address _user) external view returns (uint256); function poolEarlyWithdrawFee(uint256) external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardTime, uint256 accHopePerShare, bool isStarted, uint256 startTime ); function poolLength() external view returns (uint256); function poolLockedTime(uint256) external view returns (uint256); function renounceOwnership() external; function reserveFund() external view returns (address); function reservePercent() external view returns (uint256); function resetStartTime(uint256 _startTime) external; function rewardHalvingRate() external view returns (uint256); function rewardPerSecond() external view returns (uint256); function rewardReferral() external view returns (address); function rewarder(uint256) external view returns (address); function set( uint256 _pid, uint256 _allocPoint, address _rewarder ) external; function setCommissionPercent(uint256 _commissionPercent) external; function setDevFund(address _devFund) external; function setDevPercent(uint256 _devPercent) external; function setHalvingChecked(bool _halvingChecked) external; function setPoolLockedTimeAndFee( uint256 _pid, uint256 _lockedTime, uint256 _earlyWithdrawFee ) external; function setReserveFund(address _reserveFund) external; function setReservePercent(uint256 _reservePercent) external; function setRewardHalvingRate(uint256 _rewardHalvingRate) external; function setRewardReferral(address _rewardReferral) external; function setTotalRewardPerSecond(uint256 _totalRewardPerSecond) external; function startTime() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function totalRewardPerSecond() external view returns (uint256); function transferOwnership(address newOwner) external; function unfrozenDepositTime(uint256 _pid, address _account) external view returns (uint256); function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function userLastDepositTime(uint256, address) external view returns (uint256); function withdraw(uint256 _pid, uint256 _amount) external; function withdrawAll(uint256 _pid) external; } interface IFirebird3usdToken { function withdraw(uint256 _shares, uint256 _min_output_amount) external returns (uint256); } interface IDfynSwap { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline ) external; } contract IronCompound is Ownable { using SafeERC20 for IERC20; using Address for address; address internal constant iron3usdToken = 0xb4d09ff3dA7f9e9A2BA029cb0A81A989fd7B8f17; address internal constant iceToken = 0x4A81f8796e0c6Ad4877A51C86693B0dE8093F2ef; address internal constant iron3usdPool = 0x837503e8A8753ae17fB8C8151B8e6f586defCb57; address internal constant iron3usdFarm = 0x1fD1259Fa8CdC60c6E8C86cfA592CA1b8403DFaD; address internal constant firebirdRoute = 0x8294B42C8acFF8e819064e8755a55D038060731E; address internal constant firebird3usdToken = 0x32B7d3A9Ab9Ef0412e055C8C6538E9F929f58b38; address internal constant firebirdStakingPool = 0xE9a8b6ea3e7431E6BefCa51258CB472Df2Dd21d4; address internal constant firebirdSwapRoute = 0x7973b6961C8C5ca8026B9FB82332626e715ff8c7; address internal constant wMaticToken = 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270; address internal constant hopeToken = 0xd78C475133731CD54daDCb430F7aAE4F03C1E660; address internal constant USDC = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; address internal constant WETH = 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619; address internal constant dfynSwap = 0xA102072A4C07F06EC3B4900FDC4C7B80b6c57429; address internal constant dfynWethToken = 0x4c28f48448720e9000907BC2611F73022fdcE1fA; address internal constant quickswap = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff; mapping(address => uint256) internal _userAlloc; uint256 internal _totalAlloc; uint256 internal _total3Usd; uint256 internal _allocRatio; mapping(address => bool) internal _isInWhiteList; constructor() { _allocRatio = getTokenUnit(iron3usdToken); addWhitelist(msg.sender); } function addWhitelist(address user) public onlyOwner { _isInWhiteList[user] = true; } modifier inWhiteList() { require(_isInWhiteList[msg.sender], "Not in whitelist"); _; } function getTokenUnit(address token) public view returns (uint256) { return 10**Decimals(token).decimals(); } function getInfo() public view returns ( uint256 totalAlloc, uint256 total3Usd, uint256 allocRatio ) { totalAlloc = _totalAlloc; total3Usd = _total3Usd; allocRatio = _allocRatio; } function userInfo(address user) public view returns ( uint256 alloc, uint256 amount, bool isInWhiteList ) { alloc = _userAlloc[user]; amount = _totalAlloc == 0 ? 0 : (alloc * _total3Usd) / _totalAlloc; isInWhiteList = _isInWhiteList[user]; } function deposite(uint256 amount) public inWhiteList returns (uint256) { require(amount > 0, "Fail: zero amount"); compound(); // updateAllocRatio(); address sender = msg.sender; IERC20(iron3usdToken).safeTransferFrom(sender, address(this), amount); // calculate alloc of current user uint256 depositingAlloc = (amount * getTokenUnit(iron3usdToken)) / _allocRatio; // set deposited amount _total3Usd += amount; _userAlloc[sender] += depositingAlloc; _totalAlloc += depositingAlloc; IERC20(iron3usdToken).approve(iron3usdFarm, amount); // deposit to farm. pid: 0, the 3usd pool IIron3usdFarm(iron3usdFarm).deposit(0, amount, address(this)); return depositingAlloc; } function withdraw(uint256 amount) public inWhiteList returns (uint256) { require(amount > 0, "Fail: zero amount"); compound(); // updateAllocRatio(); address sender = msg.sender; uint256 share = (_userAlloc[sender] * _total3Usd) / _totalAlloc; require(amount <= share, "Fail: withdraw amount too much"); (uint256 amountInFarm, ) = IIron3usdFarm(iron3usdFarm).userInfo( 0, address(this) ); uint256 amountToWithdraw; { amountToWithdraw = amount < amountInFarm ? amount : amountInFarm; } // pid: 0, the 3usd pool IIron3usdFarm(iron3usdFarm).withdrawAndHarvest( 0, amountToWithdraw, address(this) ); IERC20(iron3usdToken).safeTransfer(sender, amountToWithdraw); // calculate alloc { uint256 withdrawingAlloc = (amountToWithdraw * getTokenUnit(iron3usdToken)) / _allocRatio; _total3Usd -= amountToWithdraw; _userAlloc[sender] -= withdrawingAlloc; _totalAlloc -= withdrawingAlloc; } return amountToWithdraw; } function emergencyWithdraw() public { address sender = msg.sender; uint256 amount = (_userAlloc[sender] * _total3Usd) / _totalAlloc; require(amount > 0, "Fail: zero amount"); (uint256 amountInFarm, ) = IIron3usdFarm(iron3usdFarm).userInfo( 0, address(this) ); uint256 amountToWithdraw; { amountToWithdraw = amount < amountInFarm ? amount : amountInFarm; } // pid: 0, the 3usd pool IIron3usdFarm(iron3usdFarm).withdrawAndHarvest( 0, amountToWithdraw, address(this) ); IERC20(iron3usdToken).safeTransfer(sender, amountToWithdraw); // calculate alloc { uint256 withdrawingAlloc = (amountToWithdraw * getTokenUnit(iron3usdToken)) / _allocRatio; _total3Usd -= amountToWithdraw; _userAlloc[sender] = 0; _totalAlloc -= withdrawingAlloc; } } function updateAllocRatio() internal returns (uint256) { // pid: 0, the 3usd pool (uint256 amountInFarm, ) = IIron3usdFarm(iron3usdFarm).userInfo( 0, address(this) ); uint256 current3usd = IERC20(iron3usdToken).balanceOf(address(this)); _total3Usd = amountInFarm + current3usd; _allocRatio = (_total3Usd * getTokenUnit(iron3usdToken)) / _totalAlloc; return _allocRatio; } function compound() public returns (uint256) { if (_total3Usd == 0) { return 0; } uint256 current3usd = withdrawAndHarvest(); uint256 currentFirebird3usd = depositToFirebird(current3usd); compoundFirebirdAndWithdraw(currentFirebird3usd); uint256 final3usd = swapRewardsAndAddLiquidity(); require(final3usd > current3usd, "WTF: less 3usd"); // update allocRatio _total3Usd = final3usd; _allocRatio = (final3usd * getTokenUnit(iron3usdToken)) / _totalAlloc; IERC20(iron3usdToken).approve(iron3usdFarm, final3usd); // deposit to farm. pid: 0, the 3usd pool IIron3usdFarm(iron3usdFarm).deposit(0, final3usd, address(this)); return final3usd; } function withdrawAndHarvest() internal returns (uint256) { // pid: 0, the 3usd pool (uint256 amount, ) = IIron3usdFarm(iron3usdFarm).userInfo( 0, address(this) ); // pid: 0, the 3usd pool IIron3usdFarm(iron3usdFarm).withdrawAndHarvest( 0, amount, address(this) ); uint256 current3usd = IERC20(iron3usdToken).balanceOf(address(this)); require(current3usd >= _total3Usd, "WTF: less 3usd amount"); if (current3usd > _total3Usd) { _total3Usd = current3usd; } return current3usd; } function depositToFirebird(uint256 amount) internal returns (uint256) { // deposit to firebird and mint firebird3usd IERC20(iron3usdToken).approve(firebirdRoute, amount); IFirebirdRoute(firebirdRoute).deposit(firebird3usdToken, amount, 1); uint256 currentFirebird3usd = IERC20(firebird3usdToken).balanceOf( address(this) ); // deposit to staking pool IERC20(firebird3usdToken).approve( firebirdStakingPool, currentFirebird3usd ); // pid: 37, iron 3usd pool IFirebirdStakingPool(firebirdStakingPool).deposit( 37, currentFirebird3usd ); return currentFirebird3usd; } function compoundFirebirdAndWithdraw(uint256 amount) internal { // compound IFirebirdRoute(firebirdRoute).harvestAllStrategies(firebird3usdToken); // withdraw from staking pool. pid: 37, iron 3usd pool IFirebirdStakingPool(firebirdStakingPool).withdraw(37, amount); // withdraw from firebird // IFirebird3usdToken(firebird3usdToken).withdraw(amount, 0); IFirebirdRoute(firebirdRoute).withdraw(firebird3usdToken, amount, 1); } function swapRewardsAndAddLiquidity() internal returns (uint256) { address[] memory path = new address[](2); uint256 deadline = block.timestamp + 100; // swap hope to wMatic { uint256 hopeBalance = IERC20(hopeToken).balanceOf(address(this)); // at least one gwei if (hopeBalance > 1_000_000_000) { IERC20(hopeToken).approve(firebirdSwapRoute, hopeBalance); path[0] = hopeToken; path[1] = wMaticToken; IUniswapV2Router01(firebirdSwapRoute).swapExactTokensForTokens( hopeBalance, 1, path, address(this), deadline ); } } // swap wMatic to usdc { uint256 wMaticBalance = IERC20(wMaticToken).balanceOf( address(this) ); // at least one gwei if (wMaticBalance > 1_000_000_000) { IERC20(wMaticToken).approve(quickswap, wMaticBalance); path[0] = wMaticToken; path[1] = USDC; IUniswapV2Router01(quickswap).swapExactTokensForTokens( wMaticBalance, 1, path, address(this), deadline ); } } // swap ice to usdc { uint256 iceBalance = IERC20(iceToken).balanceOf(address(this)); // at least one gwei if (iceBalance > 1_000_000_000) { IERC20(wMaticToken).approve(quickswap, iceBalance); // path = new address[](3); path[0] = iceToken; path[1] = USDC; IDfynSwap(dfynSwap) .swapExactTokensForETHSupportingFeeOnTransferTokens( iceBalance, 1, path, address(this), deadline ); } } { uint256 usdcBalance = IERC20(USDC).balanceOf(address(this)); // at least one gwei if (usdcBalance > 1_000_000_000) { IERC20(USDC).approve(iron3usdPool, usdcBalance); // 0: USDC | 1: USDT | 2: DAI uint256[] memory minAmounts = new uint256[](3); // uint256[3] calldata minAmounts; minAmounts[0] = usdcBalance; minAmounts[1] = 0; minAmounts[2] = 0; IIronSwap(iron3usdPool).addLiquidity( minAmounts, 1, block.timestamp + 100 ); } } uint256 current3usd = IERC20(iron3usdToken).balanceOf(address(this)); return current3usd; } }
pool data view functions state modifying functions
interface IIronSwap { event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event TokenExchange( address indexed buyer, uint256 soldId, uint256 tokensSold, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 tokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 tokenIndex, uint256 tokenAmount, uint256 coinAmount ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 A, uint256 timestamp); event NewFee(uint256 fee, uint256 adminFee, uint256 withdrawFee); event CollectProtocolFee(address token, uint256 amount); event FeeControllerChanged(address newController); event FeeDistributorChanged(address newController); function getLpToken() external view returns (IERC20 lpToken); function getA() external view returns (uint256); function getAPrecise() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokens() external view returns (IERC20[] memory); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getTokenBalances() external view returns (uint256[] memory); function getNumberOfTokens() external view returns (uint256); function getVirtualPrice() external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); function getAdminBalances() external view returns (uint256[] memory adminBalances); function getAdminBalance(uint8 index) external view returns (uint256); function calculateCurrentWithdrawFee(address account) external view returns (uint256); function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; function withdrawAdminFee() external; }
13,069,901
//Address: 0xc99f359f73626e475ee86caab459a4b34ae93fea //Contract name: DungeonTokenAuction //Balance: 0 Ether //Verification Date: 3/10/2018 //Transacion Count: 9 // CODE STARTS HERE pragma solidity ^0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title JointOwnable * @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses * to manage some functions of the contract, using the eitherOwner modifier. * Note that onlyOwner modifier would still be accessible only for the original owner. */ contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner1; address public anotherOwner2; /** * @dev Throws if called by any account other than the owner or anotherOwner. */ modifier eitherOwner() { require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2); _; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner1(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner1 = _anotherOwner; } /** * @dev Allows the current owner to assign another owner. * @param _anotherOwner The address to another owner. */ function assignAnotherOwner2(address _anotherOwner) onlyOwner public { require(_anotherOwner != 0); AnotherOwnerAssigned(_anotherOwner); anotherOwner2 = _anotherOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens. */ contract ERC721 { // Events event Transfer(address indexed from, address indexed to, uint indexed tokenId); event Approval(address indexed owner, address indexed approved, uint indexed tokenId); // ERC20 compatible functions. // function name() public constant returns (string); // function symbol() public constant returns (string); function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint); // Functions that define ownership. function ownerOf(uint _tokenId) external view returns (address); function transfer(address _to, uint _tokenId) external; // Approval related functions, mainly used in auction contracts. function approve(address _to, uint _tokenId) external; function approvedFor(uint _tokenId) external view returns (address); function transferFrom(address _from, address _to, uint _tokenId) external; /** * @dev Each non-fungible token owner can own more than one token at one time. * Because each token is referenced by its unique ID, however, * it can get difficult to keep track of the individual tokens that a user may own. * To do this, the contract keeps a record of the IDs of each token that each user owns. */ mapping(address => uint[]) public ownerTokens; } /** * @title The ERC-721 compliance token contract. */ contract ERC721Token is ERC721, Pausable { /* ======== STATE VARIABLES ======== */ /** * @dev A mapping from token IDs to the address that owns them. */ mapping(uint => address) tokenIdToOwner; /** * @dev A mapping from token ids to an address that has been approved to call * transferFrom(). Each token can only have one approved address for transfer * at any time. A zero value means no approval is outstanding. */ mapping (uint => address) tokenIdToApproved; /** * @dev A mapping from token ID to index of the ownerTokens' tokens list. */ mapping(uint => uint) tokenIdToOwnerTokensIndex; /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Returns the number of tokens owned by a specific address. * @param _owner The owner address to check. */ function balanceOf(address _owner) public view returns (uint) { return ownerTokens[_owner].length; } /** * @dev Returns the address currently assigned ownership of a given token. */ function ownerOf(uint _tokenId) external view returns (address) { require(tokenIdToOwner[_tokenId] != address(0)); return tokenIdToOwner[_tokenId]; } /** * @dev Returns the approved address of a given token. */ function approvedFor(uint _tokenId) external view returns (address) { return tokenIdToApproved[_tokenId]; } /** * @dev Get an array of IDs of each token that an user owns. */ function getOwnerTokens(address _owner) external view returns(uint[]) { return ownerTokens[_owner]; } /** * @dev External function to transfers a token to another address. * @param _to The address of the recipient, can be a user or contract. * @param _tokenId The ID of the token to transfer. */ function transfer(address _to, uint _tokenId) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); // You can only send your own token. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /** * @dev Grant another address the right to transfer a specific Kitty via * transferFrom(). This is the preferred flow for transfering NFTs to contracts. * @param _to The address to be granted transfer approval. Pass address(0) to * clear all approvals. * @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. */ function approve(address _to, uint _tokenId) whenNotPaused external { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /** * @dev Transfer a Kitty owned by another address, for which the calling address * has previously been granted transfer approval by the owner. * @param _from The address that owns the Kitty to be transfered. * @param _to The address that should take ownership of the Kitty. Can be any address, * including the caller. * @param _tokenId The ID of the Kitty to be transferred. */ function transferFrom(address _from, address _to, uint _tokenId) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Check for approval and valid ownership require(tokenIdToApproved[_tokenId] == msg.sender); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev Assigns ownership of a specific token to an address. */ function _transfer(address _from, address _to, uint _tokenId) internal { // Step 1: Remove token from _form address. // When creating new token, _from is 0x0. if (_from != address(0)) { uint[] storage fromTokens = ownerTokens[_from]; uint tokenIndex = tokenIdToOwnerTokensIndex[_tokenId]; // Put the last token to the transferred token index and update its index in ownerTokensIndexes. uint lastTokenId = fromTokens[fromTokens.length - 1]; // Do nothing if the transferring token is the last item. if (_tokenId != lastTokenId) { fromTokens[tokenIndex] = lastTokenId; tokenIdToOwnerTokensIndex[lastTokenId] = tokenIndex; } fromTokens.length--; } // Step 2: Add token to _to address. // Transfer ownership. tokenIdToOwner[_tokenId] = _to; // Add the _tokenId to ownerTokens[_to] and remember the index in ownerTokensIndexes. tokenIdToOwnerTokensIndex[_tokenId] = ownerTokens[_to].length; ownerTokens[_to].push(_tokenId); // Emit the Transfer event. Transfer(_from, _to, _tokenId); } /** * @dev Marks an address as being approved for transferFrom(), overwriting any previous * approval. Setting _approved to address(0) clears all transfer approval. */ function _approve(uint _tokenId, address _approved) internal { tokenIdToApproved[_tokenId] = _approved; } /* ======== MODIFIERS ======== */ /** * @dev Throws if _dungeonId is not created yet. */ modifier tokenExists(uint _tokenId) { require(_tokenId < totalSupply()); _; } /** * @dev Checks if a given address is the current owner of a particular token. * @param _claimant The address we are validating against. * @param _tokenId Token ID */ function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIdToOwner[_tokenId] == _claimant; } } contract EDStructs { /** * @dev The main Dungeon struct. Every dungeon in the game is represented by this structure. * A dungeon is consists of an unlimited number of floors for your heroes to challenge, * the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others, * the secret formula for that is left for user to find out. * * Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat, * and some dungeons are more effective in the training, which is also a secret formula! * * When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards, * which will be rewarded to the player who successfully challenged the current floor. * * Each dungeon fits in fits into three 256-bit words. */ struct Dungeon { // Each dungeon has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint32 creationTime; // The status of the dungeon, each dungeon can have 5 status, namely: // 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive uint8 status; // The dungeon's difficulty, the higher the difficulty, // normally, the "rarer" the seedGenes, the higher the diffculty, // and the higher the contribution fee it is to challenge, train, and transport to the dungeon, // the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts. // A dungeon's difficulty never change. uint8 difficulty; // The dungeon's capacity, maximum number of players allowed to stay on this dungeon. // The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity). // Using 16-bit unsigned integers can have a maximum of 65535 in capacity. // A dungeon's capacity never change. uint16 capacity; // The current floor number, a dungeon is consists of an umlimited number of floors, // when there is heroes successfully challenged a floor, the next floor will be // automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors. uint32 floorNumber; // The timestamp of the block when the current floor is generated. uint32 floorCreationTime; // Current accumulated rewards, successful challenger will get a large proportion of it. uint128 rewards; // The seed genes of the dungeon, it is used as the base gene for first floor, // some dungeons are rarer and some are more common, the exact details are, // of course, top secret of the game! // A dungeon's seedGenes never change. uint seedGenes; // The genes for current floor, it encodes the difficulty level of the current floor. // We considered whether to store the entire array of genes for all floors, but // in order to save some precious gas we're willing to sacrifice some functionalities with that. uint floorGenes; } /** * @dev The main Hero struct. Every hero in the game is represented by this structure. */ struct Hero { // Each hero has an ID which is the index in the storage array. // The timestamp of the block when this dungeon is created. uint64 creationTime; // The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge. uint64 cooldownStartTime; // Every time a hero challenge a dungeon, its cooldown index will be incremented by one. uint32 cooldownIndex; // The seed of the hero, the gene encodes the power level of the hero. // This is another top secret of the game! Hero's gene can be upgraded via // training in a dungeon. uint genes; } } contract DungeonTokenInterface is ERC721, EDStructs { /** * @notice Limits the number of dungeons the contract owner can ever create. */ uint public constant DUNGEON_CREATION_LIMIT = 1024; /** * @dev Name of token. */ string public constant name = "Dungeon"; /** * @dev Symbol of token. */ string public constant symbol = "DUNG"; /** * @dev An array containing the Dungeon struct, which contains all the dungeons in existance. * The ID for each dungeon is the index of this array. */ Dungeon[] public dungeons; /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. */ function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) external returns (uint); /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) external; /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) external; /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) external; } /** * @title The ERC-721 compliance token contract for the Dungeon tokens. * @dev See the DungeonStructs contract to see the details of the Dungeon token data structure. */ contract DungeonToken is DungeonTokenInterface, ERC721Token, JointOwnable { /* ======== EVENTS ======== */ /** * @dev The Mint event is fired whenever a new dungeon is created. */ event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes); /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Returns the total number of tokens currently in existence. */ function totalSupply() public view returns (uint) { return dungeons.length; } /** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. * @param _difficulty The difficulty of the new dungeon. * @param _capacity The capacity of the new dungeon. * @param _floorNumber The initial floor number of the new dungeon. * @param _seedGenes The seed genes of the new dungeon. * @param _floorGenes The initial genes of the dungeon floor. * @return The dungeon ID of the new dungeon. */ function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) eitherOwner external returns (uint) { return _createDungeon(_difficulty, _capacity, _floorNumber, 0, _seedGenes, _floorGenes, _owner); } /** * @dev The external function to set dungeon status by its ID, * refer to DungeonStructs for more information about dungeon status. * Only contract owners can alter dungeon state. */ function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external { dungeons[_id].status = uint8(_newStatus); } /** * @dev The external function to add additional dungeon rewards by its ID, * only contract owners can alter dungeon state. */ function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external { dungeons[_id].rewards += uint128(_additinalRewards); } /** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. */ function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) external { Dungeon storage dungeon = dungeons[_id]; dungeon.floorNumber++; dungeon.floorCreationTime = uint32(now); dungeon.rewards = uint128(_newRewards); dungeon.floorGenes = _newFloorGenes; } /* ======== PRIVATE/INTERNAL FUNCTIONS ======== */ function _createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) private returns (uint) { // Ensure the total supply is within the fixed limit. require(totalSupply() < DUNGEON_CREATION_LIMIT); // ** STORAGE UPDATE ** // Create a new dungeon. dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), uint32(_floorNumber), uint32(now), uint128(_rewards), _seedGenes, _floorGenes)); // Token id is the index in the storage array. uint newTokenId = dungeons.length - 1; // Emit the token mint event. Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes); // This will assign ownership, and also emit the Transfer event. _transfer(0, _owner, newTokenId); return newTokenId; } /* ======== MIGRATION FUNCTIONS ======== */ /** * @dev Since the DungeonToken contract is re-deployed due to optimization. * We need to migrate all dungeons from Beta token contract to Version 1. */ function migrateDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) external { // Migration will be finished before maintenance period ends, tx.origin is used within a short period only. require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714); _createDungeon(_difficulty, _capacity, _floorNumber, _rewards, _seedGenes, _floorGenes, _owner); } } /** * @title ERC721DutchAuction * @dev Dutch auction / Decreasing clock auction for ERC721 tokens. */ contract ERC721DutchAuction is Ownable, Pausable { /* ======== STRUCTS/ENUMS ======== */ // Represents an auction of an ERC721 token. struct Auction { // Current owner of the ERC721 token. address seller; // Price (in wei) at beginning of auction. uint128 startingPrice; // Price (in wei) at end of auction. uint128 endingPrice; // Duration (in seconds) of auction. uint64 duration; // Time when auction started. // NOTE: 0 if this auction has been concluded. uint64 startedAt; } /* ======== CONTRACTS ======== */ // Reference to contract tracking ERC721 token ownership. ERC721 public nonFungibleContract; /* ======== STATE VARIABLES ======== */ // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint public ownerCut; // Map from token ID to their corresponding auction. mapping (uint => Auction) tokenIdToAuction; /* ======== EVENTS ======== */ event AuctionCreated(uint timestamp, address indexed seller, uint indexed tokenId, uint startingPrice, uint endingPrice, uint duration); event AuctionSuccessful(uint timestamp, address indexed seller, uint indexed tokenId, uint totalPrice, address winner); event AuctionCancelled(uint timestamp, address indexed seller, uint indexed tokenId); /** * @dev Constructor creates a reference to the ERC721 token ownership contract and verifies the owner cut is in the valid range. * @param _tokenAddress - address of a deployed contract implementing the Nonfungible Interface. * @param _ownerCut - percent cut the owner takes on each auction, must be between 0-10,000. */ function ERC721DutchAuction(address _tokenAddress, uint _ownerCut) public { require(_ownerCut <= 10000); nonFungibleContract = ERC721(_tokenAddress); ownerCut = _ownerCut; } /* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */ /** * @dev Bids on an open auction, completing the auction and transferring * ownership of the token if enough Ether is supplied. * @param _tokenId - ID of token to bid on. */ function bid(uint _tokenId) whenNotPaused external payable { // _bid will throw if the bid or funds transfer fails. _bid(_tokenId, msg.value); // Transfers the token owned by this contract to another address. It will throw if transfer fails. nonFungibleContract.transfer(msg.sender, _tokenId); } /** * @dev Cancels an auction that hasn't been won yet. Returns the token to original owner. * @notice This is a state-modifying function that can be called while the contract is paused. * @param _tokenId - ID of token on auction */ function cancelAuction(uint _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /** * @dev Cancels an auction when the contract is paused. * Only the owner may do this, and tokens are returned to * the seller. This should only be used in emergencies. * @param _tokenId - ID of the token on auction to cancel. */ function cancelAuctionWhenPaused(uint _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /** * @dev Remove all Ether from the contract, which is the owner's cuts * as well as any Ether sent directly to the contract address. */ function withdrawBalance() onlyOwner external { msg.sender.transfer(this.balance); } /** * @dev Returns auction info for an token on auction. * @param _tokenId - ID of token on auction. */ function getAuction(uint _tokenId) external view returns ( address seller, uint startingPrice, uint endingPrice, uint duration, uint startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /** * @dev Returns the current price of an auction. * @param _tokenId - ID of the token price we are checking. */ function getCurrentPrice(uint _tokenId) external view returns (uint) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _computeCurrentPrice(auction); } /* ======== INTERNAL/PRIVATE FUNCTIONS ======== */ /** * @dev Creates and begins a new auction. Perform all the checkings necessary. * @param _tokenId - ID of token to auction, sender must be owner. * @param _startingPrice - Price of item (in wei) at beginning of auction. * @param _endingPrice - Price of item (in wei) at end of auction. * @param _duration - Length of time to move between starting * price and ending price (in seconds). * @param _seller - Seller, if not the message sender */ function _createAuction( uint _tokenId, uint _startingPrice, uint _endingPrice, uint _duration, address _seller ) internal { // Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct. require(_startingPrice == uint(uint128(_startingPrice))); require(_endingPrice == uint(uint128(_endingPrice))); require(_duration == uint(uint64(_duration))); // If the token is already on any auction, this will throw // because it will be owned by the auction contract. require(nonFungibleContract.ownerOf(_tokenId) == msg.sender); // Throw if the _endingPrice is larger than _startingPrice. require(_startingPrice >= _endingPrice); // Require that all auctions have a duration of at least one minute. require(_duration >= 1 minutes); // Transfer the token from its owner to this contract. It will throw if transfer fails. nonFungibleContract.transferFrom(msg.sender, this, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /** * @dev Adds an auction to the list of open auctions. Also fires the * AuctionCreated event. * @param _tokenId The ID of the token to be put on auction. * @param _auction Auction to add. */ function _addAuction(uint _tokenId, Auction _auction) internal { tokenIdToAuction[_tokenId] = _auction; AuctionCreated( now, _auction.seller, _tokenId, _auction.startingPrice, _auction.endingPrice, _auction.duration ); } /** * @dev Computes the price and transfers winnings. * Does NOT transfer ownership of token. */ function _bid(uint _tokenId, uint _bidAmount) internal returns (uint) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint price = _computeCurrentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. uint auctioneerCut = price * ownerCut / 10000; uint sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(now, seller, _tokenId, price, msg.sender); return price; } /** * @dev Cancels an auction unconditionally. */ function _cancelAuction(uint _tokenId, address _seller) internal { _removeAuction(_tokenId); // Transfers the token owned by this contract to its original owner. It will throw if transfer fails. nonFungibleContract.transfer(_seller, _tokenId); AuctionCancelled(now, _seller, _tokenId); } /** * @dev Removes an auction from the list of open auctions. * @param _tokenId - ID of token on auction. */ function _removeAuction(uint _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /** * @dev Returns current price of an token on auction. Broken into two * functions (this one, that computes the duration from the auction * structure, and the other that does the price computation) so we * can easily test that the price computation works correctly. */ function _computeCurrentPrice(Auction storage _auction) internal view returns (uint) { uint secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } if (secondsPassed >= _auction.duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _auction.endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int totalPriceChange = int(_auction.endingPrice) - int(_auction.startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int currentPriceChange = totalPriceChange * int(secondsPassed) / int(_auction.duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that startingPrice. Thus, this result will always end up positive. int currentPrice = int(_auction.startingPrice) + currentPriceChange; return uint(currentPrice); } } /* ======== MODIFIERS ======== */ /** * @dev Returns true if the token is on auction. * @param _auction - Auction to check. */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } } contract DungeonTokenAuction is DungeonToken, ERC721DutchAuction { function DungeonTokenAuction(uint _ownerCut) ERC721DutchAuction(this, _ownerCut) public { } /** * @dev Creates and begins a new auction. * @param _tokenId - ID of token to auction, sender must be owner. * @param _startingPrice - Price of item (in wei) at beginning of auction. * @param _endingPrice - Price of item (in wei) at end of auction. * @param _duration - Length of time to move between starting price and ending price (in seconds). */ function createAuction( uint _tokenId, uint _startingPrice, uint _endingPrice, uint _duration ) whenNotPaused external { _approve(_tokenId, this); // This will perform all the checkings necessary. _createAuction(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender); } }
Checks if a given address is the current owner of a particular token. _claimant The address we are validating against. _tokenId Token ID/
function _owns(address _claimant, uint _tokenId) internal view returns (bool) { return tokenIdToOwner[_tokenId] == _claimant; }
1,793,787
/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.10; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol"; import "./compound/ICErc20.sol"; import "./DrawManager.sol"; import "fixidity/contracts/FixidityLib.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract Pool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; uint256 private constant ETHER_IN_WEI = 1000000000000000000; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary ) public initializer { require(_owner != address(0), "owner cannot be the null address"); require(_cToken != address(0), "money market address is zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw(nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function commit() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin unlessPaused { require(currentCommittedDrawId() == 0, "there is a committed draw"); if (currentOpenDrawId() != 0) { commit(); } open(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin unlessPaused { require(currentCommittedDrawId() != 0, "a draw has not been committed"); reward(lastSecret, _salt); commit(); open(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret and a hash of the Draw's opened block and the gross winnings. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw */ function reward(bytes32 _secret, bytes32 _salt) internal { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "secret does not match"); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // derive entropy from the revealed secret and the hash of the openedBlock and gross winnings bytes32 entropy = _secret ^ keccak256(abi.encodePacked(draw.openedBlock, grossWinnings)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the next draw drawState.deposit(winningAddress, netWinnings); // Updated the accounted total accountedBalance = underlyingBalance; } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } // Destroy the draw now that it's complete delete draws[drawId]; emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public nonReentrant unlessPaused { // Deposit the funds _deposit(_amount); emit SponsorshipDeposited(msg.sender, _amount); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw nonReentrant unlessPaused { // Update the user's eligibility drawState.deposit(msg.sender, _amount); // Deposit the funds _deposit(_amount); emit Deposited(msg.sender, _amount); } /** * @notice Transfers tokens from the sender into the Compound cToken contract and updates the accountedBalance. * @param _amount The amount of the token underlying the cToken to deposit. */ function _deposit(uint256 _amount) internal { require(_amount > 0, "deposit is not greater than zero"); // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "token transfer failed"); // Update the user's balance balances[msg.sender] = balances[msg.sender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "could not approve money market spend"); require(cToken.mint(_amount) == 0, "could not supply money market"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant { uint balance = balances[msg.sender]; require(balance > 0, "balance has already been withdrawn"); // Update the user's balance balances[msg.sender] = 0; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(balance); } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(uint256 _amount) internal { require(_amount > 0, "withdrawal is not greater than zero"); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "could not redeem from compound"); require(token().transfer(msg.sender, _amount), "could not transfer winnings"); emit Withdrawn(msg.sender, _amount); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) public view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) public view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) public view returns (uint256) { return balances[_addr]; } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply; } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction >= 0, "fee must be zero or greater"); require(_feeFraction <= ETHER_IN_WEI, "fee fraction must be 1 or less"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "beneficiary should not be 0x0"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "admin does not exist"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() internal view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } modifier onlyAdmin() { require(admins.has(msg.sender), "must be an admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "there is no open draw"); _; } modifier whenPaused() { require(paused, "contract is not paused"); _; } modifier unlessPaused() { require(!paused, "contract is paused"); _; } }
Transfers tokens from the cToken contract to the sender. Updates the accounted balance./ Update the total of this contract Withdraw from Compound and transfer
function _withdraw(uint256 _amount) internal { require(_amount > 0, "withdrawal is not greater than zero"); accountedBalance = accountedBalance.sub(_amount); require(cToken.redeemUnderlying(_amount) == 0, "could not redeem from compound"); require(token().transfer(msg.sender, _amount), "could not transfer winnings"); emit Withdrawn(msg.sender, _amount); }
930,197
./full_match/1/0x73d6B1EF5227EA7f97426a9ADE2b9006eb88eE5D/sources/contracts/token/MRANDMRSWOJAK.sol
Returns the symbol of the token, usually a shorter version of the name./
function symbol() public view returns (string memory) { return _symbol; }
2,991,236
// SPDX-License-Identifier: GPLv2 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../DigitalaxAccessControls.sol"; import "./interfaces/IERC20.sol"; import "../oracle/IDigitalaxMonaOracle.sol"; import "../EIP2771/BaseRelayRecipient.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title Digitalax Rewards * @dev Calculates the rewards for staking on the Digitalax platform * @author DIGITALAX CORE TEAM * @author Based on original staking contract by Adrian Guerrera (deepyr) */ interface DigitalaxStaking { function stakedEthTotal() external view returns (uint256); function stakedEthTotalByPool(uint256 _poolId) external view returns (uint256); function earlyStakedEthTotalByPool(uint256 _poolId) external view returns (uint256); function stakedMonaInPool(uint256 _poolId) external view returns (uint256); function monaToken() external view returns (address); function WETH() external view returns (address); } interface MONA is IERC20 { function mint(address tokenOwner, uint tokens) external returns (bool); } contract DigitalaxNFTRewardsV2 is BaseRelayRecipient, ReentrancyGuard { using SafeMath for uint256; /* ========== Variables ========== */ MONA public monaToken; /// @notice Mona to Ether Oracle IDigitalaxMonaOracle public oracle; DigitalaxAccessControls public accessControls; DigitalaxStaking public monaStaking; uint256 constant pointMultiplier = 10e18; uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_WEEK = 7 * 24 * 60 * 60; mapping (uint256 => uint256) public weeklyMonaRevenueSharingPerSecond; // Mona revenue sharing uint256 public startTime; uint256 public monaRewardsPaidTotal; /// @notice for storing information from oracle uint256 public lastOracleQuote = 1e18; // We must trust admin to pass correct weighted values, if not we could use something like // / @notice mapping of a staker to its current properties //mapping (uint256 => uint256) public weeklyTotalWeightPoints; /* @notice staking pool id to staking pool reward mapping */ StakingPoolRewards public pool; /* ========== Structs ========== */ /** @notice Struct to track the active pool @dev weeklyWeightPoints mapping the week to the weight for this pool @dev lastRewardsTime last time the overall rewards @dev rewardsPaid amount of rewards that have been paid to this pool */ struct StakingPoolRewards { uint256 lastRewardsTime; uint256 monaRewardsPaid; } /* ========== Events ========== */ event UpdateAccessControls( address indexed accessControls ); event RewardAdded(address indexed addr, uint256 reward); event RewardDistributed(address indexed addr, uint256 reward); event ReclaimedERC20(address indexed token, uint256 amount); event UpdateOracle(address indexed oracle); event DepositRevenueSharing( uint256 weeklyMonaRevenueSharingPerSecond, uint256 _week, uint256 _amount ); /* ========== Admin Functions ========== */ constructor( MONA _monaToken, DigitalaxAccessControls _accessControls, DigitalaxStaking _monaStaking, IDigitalaxMonaOracle _oracle, address _trustedForwarder, uint256 _startTime, uint256 _monaRewardsPaidTotal ) public { require( address(_monaToken) != address(0), "DigitalaxRewardsV2: Invalid Mona Address" ); require( address(_accessControls) != address(0), "DigitalaxRewardsV2: Invalid Access Controls" ); require( address(_monaStaking) != address(0), "DigitalaxRewardsV2: Invalid Mona Staking" ); require( address(_oracle) != address(0), "DigitalaxRewardsV2: Invalid Mona Oracle" ); monaToken = _monaToken; accessControls = _accessControls; monaStaking = _monaStaking; oracle = _oracle; startTime = _startTime; monaRewardsPaidTotal = _monaRewardsPaidTotal; trustedForwarder = _trustedForwarder; } receive() external payable { } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } /* * @notice Set the start time * @dev Setter functions for contract config */ function setStartTime( uint256 _startTime ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.setStartTime: Sender must be admin" ); startTime = _startTime; } /** @notice Method for updating oracle @dev Only admin @param _oracle new oracle */ function updateOracle(IDigitalaxMonaOracle _oracle) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.updateOracle: Sender must be admin" ); oracle = _oracle; emit UpdateOracle(address(_oracle)); } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract (Cannot be zero address) */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.updateAccessControls: Sender must be admin" ); require(address(_accessControls) != address(0), "DigitalaxRewardsV2.updateAccessControls: Zero Address"); accessControls = _accessControls; emit UpdateAccessControls(address(_accessControls)); } /** @notice Method for updating the address of the mona staking contract @dev Only admin @param _addr Address of the mona staking contract */ function setMonaStaking(address _addr) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.setMonaStaking: Sender must be admin" ); monaStaking = DigitalaxStaking(_addr); } /* * @notice Deposit revenue sharing rewards to be distributed during a certain week * @dev this number is the total rewards that week with 18 decimals */ function depositMonaRewards( uint256 _week, uint256 _amount ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.setRewards: Sender must be admin" ); require( _week > getCurrentWeek(), "DigitalaxRewardsV2.depositRevenueSharingRewards: The rewards generated should be set for the future weeks" ); require(IERC20(monaToken).allowance(_msgSender(), address(this)) >= _amount, "DigitalaxRewardsV2.depositRevenueSharingRewards: Failed to supply ERC20 Allowance"); // Deposit this amount of MONA here require(IERC20(monaToken).transferFrom( address(_msgSender()), address(this), _amount )); uint256 monaAmount = _amount.mul(pointMultiplier) .div(SECONDS_PER_WEEK) .div(pointMultiplier); // Increase the revenue sharing per second for the week for Mona weeklyMonaRevenueSharingPerSecond[_week] = weeklyMonaRevenueSharingPerSecond[_week].add(monaAmount); emit DepositRevenueSharing(weeklyMonaRevenueSharingPerSecond[_week], _week, _amount); } /* From BokkyPooBah's DateTime Library v1.01 * https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary */ function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } /* ========== Mutative Functions ========== */ /* @notice Calculate and update rewards * @dev */ function updateRewards(uint256 _poolId) external returns(bool) { if (_getNow() <= pool.lastRewardsTime) { return false; } /// @dev check that the staking pool has contributions, and rewards have started if (_getNow() <= startTime) { pool.lastRewardsTime = _getNow(); return false; } // @dev Update the oracle (uint256 exchangeRate, bool rateValid) = oracle.getData(); require(rateValid, "DigitalaxMarketplace.estimateMonaAmount: Oracle data is invalid"); lastOracleQuote = exchangeRate; /// @dev This sends rewards (Mona from revenue sharing) _updateMonaRewards(_poolId); /// @dev update accumulated reward pool.lastRewardsTime = _getNow(); return true; } /* * @dev Setter functions for contract config custom last rewards time for a pool */ function setLastRewardsTime( uint256[] memory _poolIds, uint256[] memory _lastRewardsTimes) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.setLastRewardsTime: Sender must be admin" ); for (uint256 i = 0; i < _poolIds.length; i++) { pool.lastRewardsTime = _lastRewardsTimes[i]; } } /* ========== View Functions ========== */ /* * @notice Gets the total rewards outstanding from last reward time */ function totalNewMonaRewards(uint256 _poolId) external view returns (uint256) { uint256 lRewards = MonaRewards(_poolId, pool.lastRewardsTime, _getNow()); return lRewards; } /* * @notice Get the last rewards time for a pool * @return last rewards time for a pool */ function lastRewardsTime(uint256 _poolId) external view returns(uint256) { return pool.lastRewardsTime; } /* @notice Return mona revenue rewards over the given _from to _to timestamp. * @dev A fraction of the start, multiples of the middle weeks, fraction of the end */ function MonaRewards(uint256 _poolId, uint256 _from, uint256 _to) public view returns (uint256 rewards) { if (_to <= startTime) { return 0; } if (_from < startTime) { _from = startTime; } uint256 fromWeek = diffDays(startTime, _from) / 7; uint256 toWeek = diffDays(startTime, _to) / 7; if (fromWeek == toWeek) { return _rewardsFromPoints(weeklyMonaRevenueSharingPerSecond[fromWeek], _to.sub(_from)); } /// @dev First count remainder of first week uint256 initialRemander = startTime.add((fromWeek+1).mul(SECONDS_PER_WEEK)).sub(_from); rewards = _rewardsFromPoints(weeklyMonaRevenueSharingPerSecond[fromWeek], initialRemander); /// @dev add multiples of the week for (uint256 i = fromWeek+1; i < toWeek; i++) { rewards = rewards.add(_rewardsFromPoints(weeklyMonaRevenueSharingPerSecond[i], SECONDS_PER_WEEK)); } /// @dev Adds any remaining time in the most recent week till _to uint256 finalRemander = _to.sub(toWeek.mul(SECONDS_PER_WEEK).add(startTime)); rewards = rewards.add(_rewardsFromPoints(weeklyMonaRevenueSharingPerSecond[toWeek], finalRemander)); return rewards; } /* ========== Internal Functions ========== */ function _updateMonaRewards(uint256 _poolId) internal returns(uint256 rewards) { rewards = MonaRewards(_poolId, pool.lastRewardsTime, _getNow()); if ( rewards > 0 ) { pool.monaRewardsPaid = pool.monaRewardsPaid.add(rewards); monaRewardsPaidTotal = monaRewardsPaidTotal.add(rewards); // Send this amount of MONA to the staking contract IERC20(monaToken).transfer( address(monaStaking), rewards ); } } function _rewardsFromPoints( uint256 rate, uint256 duration ) internal pure returns(uint256) { return rate.mul(duration); } /* ========== Reclaim ERC20 ========== */ /* * @notice allows for the recovery of incorrect ERC20 tokens sent to contract */ function reclaimERC20( address _tokenAddress, uint256 _tokenAmount ) external { // Cannot recover the staking token or the rewards token require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.reclaimERC20: Sender must be admin" ); // require( // tokenAddress != address(monaToken), // "Cannot withdraw the rewards token" // ); IERC20(_tokenAddress).transfer(_msgSender(), _tokenAmount); emit ReclaimedERC20(_tokenAddress, _tokenAmount); } /** * @notice EMERGENCY Recovers ETH, drains amount of eth sitting on the smart contract * @dev Only access controls admin can access */ function reclaimETH(uint256 _amount) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.reclaimETH: Sender must be admin" ); _msgSender().transfer(_amount); } /* ========== Getters ========== */ function getCurrentWeek() public view returns(uint256) { return diffDays(startTime, _getNow()) / 7; } function getMonaStakedEthTotal() public view returns(uint256) { return monaStaking.stakedEthTotal(); } function getMonaDailyAPY(uint256 _poolId, bool isEarlyStaker) external view returns (uint256) { uint256 stakedEth = monaStaking.stakedEthTotalByPool(_poolId); uint256 yearlyReturnInEth = 0; if ( stakedEth != 0) { uint256 rewards = MonaRewards(_poolId, _getNow() - 60, _getNow()); uint256 rewardsInEth = rewards.mul(getEthPerMona()).div(1e18); /// @dev minutes per year x 100 = 52560000 yearlyReturnInEth = rewardsInEth.mul(52560000).mul(1e18).div(stakedEth); } return yearlyReturnInEth; } // MONA amount for custom ETH amount function getMonaPerEth(uint256 _ethAmt) public view returns (uint256) { return _ethAmt.mul(1e18).div(lastOracleQuote); } // ETH amount for 1 MONA function getEthPerMona() public view returns (uint256) { return lastOracleQuote.div(1e18); } function _getNow() internal virtual view returns (uint256) { return block.timestamp; } }
allows for the recovery of incorrect ERC20 tokens sent to contract/ Cannot recover the staking token or the rewards token require( tokenAddress != address(monaToken), "Cannot withdraw the rewards token" );
function reclaimERC20( address _tokenAddress, uint256 _tokenAmount ) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxRewardsV2.reclaimERC20: Sender must be admin" ); IERC20(_tokenAddress).transfer(_msgSender(), _tokenAmount); emit ReclaimedERC20(_tokenAddress, _tokenAmount); }
5,545,726
./full_match/80001/0x75AfbEf84bF6FF8Cafe08872Db2CB77cabebF53f/sources/phopox.sol
Update burnPercent by the previous dev.
function getBurnPercent() external view returns (uint256){ return burnPercent; }
840,420
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IDetailedERC20.sol"; /// Interface for all Vault Adapter implementations. interface IVaultAdapter { /// @dev Gets the token that the adapter accepts. function token() external view returns (IDetailedERC20); /// @dev The total value of the assets deposited into the vault. function totalValue() external view returns (uint256); /// @dev Deposits funds into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(uint256 _amount) external; /// @dev Attempts to withdraw funds from the wrapped vault. /// /// The amount withdrawn to the recipient may be less than the amount requested. /// /// @param _recipient the recipient of the funds. /// @param _amount the amount of funds to withdraw. function withdraw(address _recipient, uint256 _amount) external; }
Interface for all Vault Adapter implementations.
interface IVaultAdapter { function token() external view returns (IDetailedERC20); function totalValue() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(address _recipient, uint256 _amount) external; pragma solidity ^0.6.12; }
7,269,319
./partial_match/1/0x9391B14dB2d43687Ea1f6E546390ED4b20766c46/sources/contracts/lib/Bytes32Set.sol
Check if a key exists in the Set. self A Set struct key A key to look for. return bool True if the key exists in the Set, otherwise false./
function exists(Set storage self, bytes32 key) internal view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; }
3,560,127
pragma solidity ^0.5.16; import "./CToken.sol"; import "./CTokenNoInterest.sol"; import "./ERC3156FlashLenderInterface.sol"; import "./ERC3156FlashBorrowerInterface.sol"; /** * @title Cream's CCollateralCapErc20 Contract * @notice CTokens which wrap an EIP-20 underlying with collateral cap * @author Cream */ contract CCollateralCapErc20NoInterest is CTokenNoInterest, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external returns (uint256) { (uint256 err, ) = mintInternal(mintAmount, false); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256) { return redeemInternal(redeemTokens, false); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256) { return redeemUnderlyingInternal(redeemAmount, false); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256) { return borrowInternal(borrowAmount, false); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount, false); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral, false); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint256 addAmount) external returns (uint256) { return _addReservesInternal(addAmount, false); } /** * @notice Set the given collateral cap for the market. * @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap. */ function _setCollateralCap(uint256 newCollateralCap) external { require(msg.sender == admin, "only admin can set collateral cap"); collateralCap = newCollateralCap; emit NewCollateralCap(address(this), newCollateralCap); } /** * @notice Absorb excess cash into reserves. */ function gulp() external nonReentrant { uint256 cashOnChain = getCashOnChain(); uint256 cashPrior = getCashPrior(); uint256 excessCash = sub_(cashOnChain, cashPrior); totalReserves = add_(totalReserves, excessCash); internalCash = cashOnChain; } /** * @notice Get the max flash loan amount */ function maxFlashLoan() external view returns (uint256) { uint256 amount = 0; if ( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, "") ) { amount = getCashPrior(); } return amount; } /** * @notice Get the flash loan fees * @param amount amount of token to borrow */ function flashFee(uint256 amount) external view returns (uint256) { require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), address(0), amount, ""), "flashloan is paused" ); return div_(mul_(amount, flashFeeBips), 10000); } /** * @notice Flash loan funds to a given account. * @param receiver The receiver address for the funds * @param initiator flash loan initiator * @param amount The amount of the funds to be loaned * @param data The other data * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external nonReentrant returns (bool) { require(amount > 0, "flashLoan amount should be greater than zero"); require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); require( ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed( address(this), address(receiver), amount, data ), "flashloan is paused" ); uint256 cashOnChainBefore = getCashOnChain(); uint256 cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint256 totalFee = this.flashFee(amount); // 2. transfer fund to receiver doTransferOut(address(uint160(address(receiver))), amount, false); // 3. update totalBorrows totalBorrows = add_(totalBorrows, amount); // 4. execute receiver's callback function require( receiver.onFlashLoan(initiator, underlying, amount, totalFee, data) == keccak256("ERC3156FlashBorrowerInterface.onFlashLoan"), "IERC3156: Callback failed" ); // 5. take amount + fee from receiver, then check balance uint256 repaymentAmount = add_(amount, totalFee); doTransferIn(address(receiver), repaymentAmount, false); uint256 cashOnChainAfter = getCashOnChain(); require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT"); // 6. update reserves and internal cash and totalBorrows uint256 reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); internalCash = add_(cashBefore, totalFee); totalBorrows = sub_(totalBorrows, amount); emit Flashloan(address(receiver), amount, totalFee, reservesFee); return true; } /** * @notice Register account collateral tokens if there is space. * @param account The account to register * @dev This function could only be called by comptroller. * @return The actual registered amount of collateral */ function registerCollateral(address account) external returns (uint256) { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may register collateral for user"); uint256 amount = sub_(accountTokens[account], accountCollateralTokens[account]); return increaseUserCollateralInternal(account, amount); } /** * @notice Unregister account collateral tokens if the account still has enough collateral. * @dev This function could only be called by comptroller. * @param account The account to unregister */ function unregisterCollateral(address account) external { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may unregister collateral for user"); require( comptroller.redeemAllowed(address(this), account, accountCollateralTokens[account]) == 0, "comptroller rejection" ); decreaseUserCollateralInternal(account, accountCollateralTokens[account]); } /*** Safe Token ***/ /** * @notice Gets internal balance of this contract in terms of the underlying. * It excludes balance from direct transfer. * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint256) { return internalCash; } /** * @notice Gets total balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashOnChain() internal view returns (uint256) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function * that accesses accountCollateralTokens or accountTokens. * @param account The account of accountCollateralTokens that needs to be updated */ function initializeAccountCollateralTokens(address account) internal { /** * If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet. * This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its * initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to * check every user's value when the implementation becomes active. Therefore, it must rely on every action which will * access accountTokens to call this function to check if accountCollateralTokens needed to be initialized. */ if (!isCollateralTokenInit[account]) { if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(account, CToken(address(this)))) { accountCollateralTokens[account] = accountTokens[account]; totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]); emit UserCollateralChanged(account, accountCollateralTokens[account]); } isCollateralTokenInit[account] = true; } } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256) { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); uint256 transferredIn = sub_(balanceAfter, balanceBefore); internalCash = add_(internalCash, transferredIn); return transferredIn; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); internalCash = sub_(internalCash, amount); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { // Make sure accountCollateralTokens of `src` and `dst` are initialized. initializeAccountCollateralTokens(src); initializeAccountCollateralTokens(dst); /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be transferred first. * bufferTokens = accountTokens[src] - accountCollateralTokens[src] * collateralTokens = tokens - bufferTokens */ uint256 bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]); uint256 collateralTokens = 0; if (tokens > bufferTokens) { collateralTokens = tokens - bufferTokens; } /** * Since bufferTokens are not collateralized and can be transferred freely, we only check with comptroller * whether collateralized tokens can be transferred. */ uint256 allowed = comptroller.transferAllowed(address(this), src, dst, collateralTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ accountTokens[src] = sub_(accountTokens[src], tokens); accountTokens[dst] = add_(accountTokens[dst], tokens); if (collateralTokens > 0) { accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens); accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens); emit UserCollateralChanged(src, accountCollateralTokens[src]); emit UserCollateralChanged(dst, accountCollateralTokens[dst]); } /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = sub_(startingAllowance, tokens); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @notice Get the account's cToken balances * @param account The address of the account */ function getCTokenBalanceInternal(address account) internal view returns (uint256) { if (isCollateralTokenInit[account]) { return accountCollateralTokens[account]; } else { /** * If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens. */ return accountTokens[account]; } } /** * @notice Increase user's collateral. Increase as much as we can. * @param account The address of the account * @param amount The amount of collateral user wants to increase * @return The actual increased amount of collateral */ function increaseUserCollateralInternal(address account, uint256 amount) internal returns (uint256) { uint256 totalCollateralTokensNew = add_(totalCollateralTokens, amount); if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) { // 1. If collateral cap is not set, // 2. If collateral cap is set but has enough space for this user, // give all the user needs. totalCollateralTokens = totalCollateralTokensNew; accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); return amount; } else if (collateralCap > totalCollateralTokens) { // If the collateral cap is set but the remaining cap is not enough for this user, // give the remaining parts to the user. uint256 gap = sub_(collateralCap, totalCollateralTokens); totalCollateralTokens = add_(totalCollateralTokens, gap); accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap); emit UserCollateralChanged(account, accountCollateralTokens[account]); return gap; } return 0; } /** * @notice Decrease user's collateral. Reject if the amount can't be fully decrease. * @param account The address of the account * @param amount The amount of collateral user wants to decrease */ function decreaseUserCollateralInternal(address account, uint256 amount) internal { /* * Return if amount is zero. * Put behind `redeemAllowed` for accuring potential COMP rewards. */ if (amount == 0) { return; } totalCollateralTokens = sub_(totalCollateralTokens, amount); accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); } struct MintLocalVars { uint256 exchangeRateMantissa; uint256 mintTokens; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256) { // Make sure accountCollateralTokens of `minter` is initialized. initializeAccountCollateralTokens(minter); /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* * Return if mintAmount is zero. * Put behind `mintAllowed` for accuring potential COMP rewards. */ if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupply = totalSupply + mintTokens * accountTokens[minter] = accountTokens[minter] + mintTokens */ totalSupply = add_(totalSupply, vars.mintTokens); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); /* * We only allocate collateral tokens if the minter has entered the market. */ if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(address(this)))) { increaseUserCollateralInternal(minter, vars.mintTokens); } /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } struct RedeemLocalVars { uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero. * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256) { // Make sure accountCollateralTokens of `redeemer` is initialized. initializeAccountCollateralTokens(redeemer); require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be redeemed first. * bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer] * collateralTokens = redeemTokens - bufferTokens */ uint256 bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]); uint256 collateralTokens = 0; if (vars.redeemTokens > bufferTokens) { collateralTokens = vars.redeemTokens - bufferTokens; } if (collateralTokens > 0) { require(comptroller.redeemAllowed(address(this), redeemer, collateralTokens) == 0, "comptroller rejection"); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ totalSupply = sub_(totalSupply, vars.redeemTokens); accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens); /* * We only deallocate collateral tokens if the redeemer needs to redeem them. */ decreaseUserCollateralInternal(redeemer, collateralTokens); /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount, isNative); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint256(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { // Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized. initializeAccountCollateralTokens(liquidator); initializeAccountCollateralTokens(borrower); /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* * Return if seizeTokens is zero. * Put behind `seizeAllowed` for accuring potential COMP rewards. */ if (seizeTokens == 0) { return uint256(Error.NO_ERROR); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } /* * We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow: * accountTokens[borrower] = accountTokens[borrower] - seizeTokens * accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens * accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens * accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens */ accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens); accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens); accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens); accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], seizeTokens); /* Emit a Transfer, UserCollateralChanged events */ emit Transfer(borrower, liquidator, seizeTokens); emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]); emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint256(Error.NO_ERROR); } } pragma solidity ^0.5.16; import "./CCollateralCapErc20NoInterest.sol"; /** * @title Cream's CCollateralCapErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Cream */ contract CCollateralCapErc20NoInterestDelegate is CCollateralCapErc20NoInterest { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); // Set internal cash when becoming implementation internalCash = getCashOnChain(); // Set CToken version in comptroller ComptrollerInterfaceExtension(address(comptroller)).updateCTokenVersion( address(this), ComptrollerV1Storage.Version.COLLATERALCAP ); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* * Return if borrowAmount is zero. * Put behind `borrowAllowed` for accuring potential COMP rewards. */ if (borrowAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return uint256(Error.NO_ERROR); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return ( failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0 ); } /* * Return if repayAmount is zero. * Put behind `repayBorrowAllowed` for accuring potential COMP rewards. */ if (repayAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return (uint256(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); if (vars.repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(vars.repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require( vars.amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED" ); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in native token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, true); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./InterestRateModel.sol"; import "./ERC3156FlashBorrowerInterface.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint256 internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /** * @notice Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Implementation address for this contract */ address public implementation; } contract CSupplyCapStorage { /** * @notice Internal cash counter for this CToken. Should equal underlying.balanceOf(address(this)) for CERC20. */ uint256 public internalCash; } contract CCollateralCapStorage { /** * @notice Total number of tokens used as collateral in circulation. */ uint256 public totalCollateralTokens; /** * @notice Record of token balances which could be treated as collateral for each account. * If collateral cap is not set, the value should be equal to accountTokens. */ mapping(address => uint256) public accountCollateralTokens; /** * @notice Check if accountCollateralTokens have been initialized. */ mapping(address => bool) public isCollateralTokenInit; /** * @notice Collateral cap for this CToken, zero for no cap. */ uint256 public collateralCap; } /*** Interface ***/ contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow( address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows ); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) public view returns (uint256); function exchangeRateCurrent() public returns (uint256); function exchangeRateStored() public view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() public returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256); function _acceptAdmin() external returns (uint256); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256); function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _reduceReserves(uint256 reduceAmount) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256); } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) external returns (uint256); function _addReserves(uint256 addAmount) external returns (uint256); } contract CWrappedNativeInterface is CErc20Interface { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function mintNative() external payable returns (uint256); function redeemNative(uint256 redeemTokens) external returns (uint256); function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256); function borrowNative(uint256 borrowAmount) external returns (uint256); function repayBorrowNative() external payable returns (uint256); function liquidateBorrowNative(address borrower, CTokenInterface cTokenCollateral) external payable returns (uint256); function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); function _addReservesNative() external payable returns (uint256); } contract CCapableErc20Interface is CErc20Interface, CSupplyCapStorage { /** * @notice Flash loan fee ratio */ uint256 public constant flashFeeBips = 3; /*** Market Events ***/ /** * @notice Event emitted when a flashloan occured */ event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee); /*** User Interface ***/ function gulp() external; } contract CCollateralCapErc20Interface is CCapableErc20Interface, CCollateralCapStorage { /*** Admin Events ***/ /** * @notice Event emitted when collateral cap is set */ event NewCollateralCap(address token, uint256 newCap); /** * @notice Event emitted when user collateral is changed */ event UserCollateralChanged(address account, uint256 newCollateralTokens); /*** User Interface ***/ function registerCollateral(address account) external returns (uint256); function unregisterCollateral(address account) external; function flashLoan( ERC3156FlashBorrowerInterface receiver, address initiator, uint256 amount, bytes calldata data ) external returns (bool); /*** Admin Functions ***/ function _setCollateralCap(uint256 newCollateralCap) external; } contract CDelegatorInterface { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /*** External interface ***/ /** * @title Flash loan receiver interface */ interface IFlashloanReceiver { function executeOperation( address sender, address underlying, uint256 amount, uint256 fee, bytes calldata params ) external; } pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./EIP20NonStandardInterface.sol"; import "./InterestRateModel.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CTokenNoInterest is CTokenInterface, Exponential, TokenErrorReporter { address public constant EVIL_SPELL = 0x560A8E3B79d23b0A525E15C6F3486c6A293DDAd2; /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = getCTokenBalanceInternal(account); uint256 borrowBalance = borrowBalanceStoredInternal(account); uint256 exchangeRateMantissa = exchangeRateStoredInternal(); return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Function to get the evil spell's debt * @return The debt */ function getAlphaDebt() internal view returns (uint256) { return accountBorrows[EVIL_SPELL].principal; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @dev The total borrows exclude the debts from Alpha * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate(getCashPrior(), sub_(totalBorrows, getAlphaDebt()), totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @dev The total borrows exclude the debts from Alpha * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { uint256 cashPrior = getCashPrior(); uint256 borrows = sub_(totalBorrows, getAlphaDebt()); uint256 rate = interestRateModel.getSupplyRate(cashPrior, borrows, totalReserves, reserveFactorMantissa); uint256 interest = mul_(rate, sub_(add_(cashPrior, borrows), totalReserves)); return div_(interest, sub_(add_(cashPrior, totalBorrows), totalReserves)); } /** * @notice Returns the estimated per-block borrow interest rate for this cToken after some change * @return The borrow interest rate per block, scaled by 1e18 */ function estimateBorrowRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } return interestRateModel.getBorrowRate(cashPriorNew, sub_(totalBorrowsNew, getAlphaDebt()), totalReserves); } /** * @notice Returns the estimated per-block supply interest rate for this cToken after some change * @return The supply interest rate per block, scaled by 1e18 */ function estimateSupplyRatePerBlockAfterChange(uint256 change, bool repay) external view returns (uint256) { uint256 cashPriorNew; uint256 totalBorrowsNew; if (repay) { cashPriorNew = add_(getCashPrior(), change); totalBorrowsNew = sub_(totalBorrows, change); } else { cashPriorNew = sub_(getCashPrior(), change); totalBorrowsNew = add_(totalBorrows, change); } uint256 borrows = sub_(totalBorrowsNew, getAlphaDebt()); uint256 rate = interestRateModel.getSupplyRate(cashPriorNew, borrows, totalReserves, reserveFactorMantissa); uint256 interest = mul_(rate, sub_(add_(cashPriorNew, borrows), totalReserves)); return div_(interest, sub_(add_(cashPriorNew, totalBorrowsNew), totalReserves)); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return the calculated balance or 0 if error code is non-zero */ function borrowBalanceStoredInternal(address account) internal view returns (uint256) { // The evil spell won't have further borrow interests. if (account == EVIL_SPELL) { return getAlphaDebt(); } /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex); uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex); return result; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves); uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply})); return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; uint256 borrowPriorForInterestCalculation = sub_(borrowsPrior, getAlphaDebt()); /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate( cashPrior, borrowPriorForInterestCalculation, reservesPrior ); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = sub_(currentBlockNumber, accrualBlockNumberPrior); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), blockDelta); uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowPriorForInterestCalculation); uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior); uint256 totalReservesNew = mul_ScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint256(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount, isNative); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0, isNative); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount, isNative); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount, isNative); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh( address payable borrower, uint256 borrowAmount, bool isNative ) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* * Return if borrowAmount is zero. * Put behind `borrowAllowed` for accuring potential COMP rewards. */ if (borrowAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return uint256(Error.NO_ERROR); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount); vars.totalBorrowsNew = add_(totalBorrows, borrowAmount); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount, isNative); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount, bool isNative ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return ( failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0 ); } /* * Return if repayAmount is zero. * Put behind `repayBorrowAllowed` for accuring potential COMP rewards. */ if (repayAmount == 0) { accountBorrows[borrower].interestIndex = borrowIndex; return (uint256(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount); vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral, isNative); } struct LiquidateBorrowLocalVars { uint256 repayBorrowError; uint256 actualRepayAmount; uint256 amountSeizeError; uint256 seizeTokens; } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral, bool isNative ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } LiquidateBorrowLocalVars memory vars; /* Fail if repayBorrow fails */ (vars.repayBorrowError, vars.actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount, isNative); if (vars.repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(vars.repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (vars.amountSeizeError, vars.seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), vars.actualRepayAmount ); require( vars.amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED" ); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= vars.seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, vars.seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, vars.seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, vars.actualRepayAmount, address(cTokenCollateral), vars.seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify( address(this), address(cTokenCollateral), liquidator, borrower, vars.actualRepayAmount, vars.seizeTokens ); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount, isNative); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount, isNative); totalReservesNew = add_(totalReserves, actualAddAmount); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = sub_(totalReserves, reduceAmount); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. // Restrict reducing reserves in native token. Implementations except `CWrappedNative` won't use parameter `isNative`. doTransferOut(admin, reduceAmount, true); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount, bool isNative ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut( address payable to, uint256 amount, bool isNative ) internal; /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256); /** * @notice Get the account's cToken balances */ function getCTokenBalanceInternal(address account) internal view returns (uint256); /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block */ function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256); /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn, bool isNative ) internal returns (uint256); /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256); /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } pragma solidity ^0.5.16; import "./CToken.sol"; import "./ComptrollerStorage.sol"; contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } interface ComptrollerInterfaceExtension { function checkMembership(address account, CToken cToken) external view returns (bool); function updateCTokenVersion(address cToken, ComptrollerV1Storage.Version version) external; function flashloanAllowed( address cToken, address receiver, uint256 amount, bytes calldata params ) external view returns (bool); } pragma solidity ^0.5.16; import "./CToken.sol"; import "./PriceOracle/PriceOracle.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /** * @notice Per-account mapping of "assets you are in" */ mapping(address => CToken[]) public accountAssets; enum Version { VANILLA, COLLATERALCAP, WRAPPEDNATIVE } struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint256 collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice CToken version Version version; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The portion of compRate that each market currently receives mapping(address => uint256) public compSpeeds; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint256)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint256) public compAccrued; // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; // @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market. address public supplyCapGuardian; // @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; // @notice creditLimits allowed specific protocols to borrow and repay without collateral. mapping(address => uint256) public creditLimits; // @notice flashloanGuardianPaused can pause flash loan as a safety mechanism. mapping(address => bool) public flashloanGuardianPaused; /// @notice liquidityMining the liquidity mining module that handles the LM rewards distribution. address public liquidityMining; } pragma solidity ^0.5.16; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom( address src, address dst, uint256 amount ) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } pragma solidity ^0.5.16; interface ERC3156FlashBorrowerInterface { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } pragma solidity ^0.5.16; import "./ERC3156FlashBorrowerInterface.sol"; interface ERC3156FlashLenderInterface { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( ERC3156FlashBorrowerInterface receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_FRESHNESS_CHECK, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_FRESHNESS_CHECK, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } pragma solidity ^0.5.16; import "./CarefulMath.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ uint256 numerator = mul_(expScale, scalar); return Exp({mantissa: div_(numerator, divisor)}); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { Exp memory fraction = div_ScalarByExp(scalar, divisor); return truncate(fraction); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } pragma solidity ^0.5.16; /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } pragma solidity ^0.5.16; import "../CToken.sol"; contract PriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken cToken) external view returns (uint256); }
User supplies assets into the market and receives cTokens in exchange Assumes interest has already been accrued up to the current block minter The address of the account which is supplying the assets mintAmount The amount of the underlying asset to supply isNative The amount is in native or not return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount./ Make sure accountCollateralTokens of `minter` is initialized. Fail if mint not allowed / Return if mintAmount is zero. Put behind `mintAllowed` for accuring potential COMP rewards./ Verify market's block number equals current block number / We only allocate collateral tokens if the minter has entered the market./
function mintFresh( address minter, uint256 mintAmount, bool isNative ) internal returns (uint256, uint256) { initializeAccountCollateralTokens(minter); uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } if (mintAmount == 0) { return (uint256(Error.NO_ERROR), 0); } if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(address(this)))) { increaseUserCollateralInternal(minter, vars.mintTokens); } emit Transfer(address(this), minter, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); }
6,292,233
// SPDX-License-Identifier: MIT /** * @title Rock Paper Scissors Lizard Spock * @author Clément Lesaege - <clement@lesaege.com> */ /* This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. */ pragma solidity ^0.8.4; contract RPS{ address payable public j1; // The first player creating the contract. address payable public j2; // The second player. enum Move {Null, Rock, Paper, Scissors, Spock, Lizard} // Possible moves. Note that if the parity of the moves is the same the lower one wins, otherwise the higher one. bytes32 public c1Hash; // Commitment of j1. Move public c2; // Move of j2. Move.Null before he played. uint256 public stake; // Amout bet by each party. uint256 public TIMEOUT = 5 minutes; // If some party takes more than TIMEOUT to respond, the other can call TIMEOUT to win. uint256 public lastAction; // The time of the last action. Usefull to determine if someone has timed out. /** @dev Constructor. Must send the amount at stake when creating the contract. Note that the move and salt must be saved. * @param _c1Hash Must be equal to keccak256(c1,salt) where c1 is the move of the j1. */ constructor(address payable _j1, bytes32 _c1Hash, address payable _j2) payable { stake = msg.value; // La mise correspond à la quantité d'ethers envoyés. j1=_j1; j2=_j2; c1Hash=_c1Hash; lastAction=block.timestamp; } /** @dev To be called by j2 and provided stake. * @param _c2 The move submitted by j2. */ function play(Move _c2) payable public { require(c2==Move.Null); // J2 has not played yet. require(msg.value==stake); // J2 has paid the stake. require(msg.sender==j2); // Only j2 can call this function. c2=_c2; lastAction=block.timestamp; } /** @dev To be called by j1. Reveal the move and send the ETH to the winning party or split them. * @param _c1 The move played by j1. * @param _salt The salt used when submitting the commitment when the constructor was called. */ function solve(Move _c1, uint256 _salt) public { require(c2!=Move.Null); // J2 must have played. require(msg.sender==j1); // J1 can call this. require(keccak256(abi.encodePacked(_c1,_salt))==c1Hash); // Verify the value is the commited one. require(stake != 0); // Prevent reentrancy. // If j1 or j2 throws at fallback it won't get funds and that is his fault. // Despite what the warnings say, we should not use transfer as a throwing fallback would be able to block the contract, in case of tie. uint reward = stake; stake=0; if (win(_c1,c2)) { (bool success, ) = j1.call{value: (2*reward)}(""); require(success, "Transfer to j1 failed."); } else if (win(c2,_c1)) { (bool success, ) = j2.call{value: (2*reward)}(""); require(success, "Transfer to j2 failed."); } else { (bool success1, ) = j1.call{value: (reward)}(""); require(success1, "Transfer to j1 failed."); (bool success2, ) = j2.call{value: (reward)}(""); require(success2, "Transfer to j2 failed."); } } /** @dev Let j2 get the funds back if j1 did not play. */ function j1Timeout() public { require(c2!=Move.Null); // J2 already played. require(block.timestamp > lastAction + TIMEOUT); // Timeout time has passed. require(stake != 0); uint reward = stake; stake=0; (bool success, ) = j2.call{value: (2*reward)}(""); require(success, "Transfer to j2 failed."); } /** @dev Let j1 take back the funds if j2 never play. */ function j2Timeout() public { require(c2==Move.Null); // J2 has not played. require(block.timestamp > lastAction + TIMEOUT); // Timeout time has passed. require(stake != 0); uint reward = stake; stake=0; (bool success, ) = j1.call{value: (2*reward)}(""); require(success, "Transfer to j1 failed."); } /** @dev Is this move winning over the other. * @param _c1 The first move. * @param _c2 The move the first move is considered again. * @return w True if c1 beats c2. False if c1 is beaten by c2 or in case of tie. */ function win(Move _c1, Move _c2) pure public returns (bool w) { if (_c1 == _c2) return false; // They played the same so no winner. else if (_c1==Move.Null) return false; // They did not play. else if (uint(_c1)%2==uint(_c2)%2) return (_c1<_c2); else return (_c1>_c2); } } contract Hasher{ /** @dev Give the commitement. Must only be called locally. * @param _c The move. * @param _salt The salt to increase entropy. */ function hash(uint8 _c, uint256 _salt) pure public returns(bytes32) { return keccak256(abi.encodePacked(_c,_salt)); } } contract RPSFactory { bool public gameOn; address public currentRPSAddress; // Last RPS contract address /** @dev Create a RPS game contract. Must send the amount at stake when creating the contract. Note that the move and salt must be saved. * @param _c1Hash Must be equal to keccak256(c1,salt) where c1 is the move of the j1. */ function createRPS (bytes32 _c1Hash, address payable _j2) payable public { if (gameOn) { RPS currentRPS = RPS(currentRPSAddress); uint currentStake = currentRPS.stake(); require(currentStake == 0, "Current game not ended"); } RPS newRPS = (new RPS){value: msg.value}(payable(msg.sender), _c1Hash, _j2); currentRPSAddress = address(newRPS); gameOn = true; } }
To be called by j2 and provided stake. _c2 The move submitted by j2./
function play(Move _c2) payable public { c2=_c2; lastAction=block.timestamp; }
12,812,423
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */ contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title ABLE Dollar token * * @dev Implementation of the ABLE Dollar token */ contract AbleDollarToken is Ownable, StandardBurnableToken, MintableToken { string public name = "ABLE Dollar X Token"; string public symbol = "ABLD"; uint8 public decimals = 18; uint public INITIAL_SUPPLY = 1000000000000000000000000000; mapping (address => bool) public frozenAccount; event Freeze(address target, bool freezed); event UnFreeze(address target, bool freezed); /** * @dev constructor for Able Dollar Token */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { revert(); } /** * @dev Function to freeze address * @param _target The address that will be freezed. */ function freezeAccount(address _target) onlyOwner public { require(_target != address(0)); frozenAccount[_target] = true; emit Freeze(_target, true); } /** * @dev Function to freeze address * @param _target The address that will be freezed. */ function unfreezeAccount(address _target) onlyOwner public { require(_target != address(0)); frozenAccount[_target] = false; emit UnFreeze(_target, false); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen return super.transfer(_to,_value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(!frozenAccount[msg.sender]); // Check if approved is frozen require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen return super.transferFrom(_from, _to, _value); } }
Transfers control of the contract to a newOwner. _newOwner The address to transfer ownership to./
function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
2,150,279
./full_match/10/0xacDC0755137Bd4B1b148802a927CEA137e08B45b/sources/contracts/plugins/Crafter/CrafterMint.sol
Must be recipe creator Used to withdraw recipe outputs. Reverse logic as deposit(). withdrawAmount How many times the craft outputs should be withdrawn/ Requires Decrease craftableAmount (check-effects)Pop tokenIds from end of array
function withdraw(uint96 withdrawAmount) external onlyOwner { require(withdrawAmount > 0, 'CrafterTransfer: withdrawAmount cannot be 0!'); require(withdrawAmount <= craftableAmount, 'CrafterTransfer: Not enough resources!'); craftableAmount -= withdrawAmount; for (uint256 i = 0; i < outputs.length; i++) { CraftLib.Ingredient storage ingredient = outputs[i]; if (ingredient.token == CraftLib.TokenType.erc721) { for (uint256 j = 0; j < withdrawAmount; j++) ingredient.tokenIds.pop(); } } emit RecipeUpdate(craftableAmount); }
3,780,288
pragma solidity 0.5.12; import "../MVNTokenCore.sol"; contract MVNTokenCoreMock is MVNTokenCore { constructor( address transitAccount ) public MVNTokenCore(transitAccount) { } function onlyGatewayMock() public view onlyGateway { // solhint-disable-previous-line no-empty-blocks } function disableSeizingPermamently() external { _disableSeizingPermamently(msg.sender); } function pause() external { _pause(msg.sender); } function setGateway( address newGateway ) external { _setGateway(newGateway); } function setInternalSupply( uint256 newInternalSupply ) external { _setInternalSupply(newInternalSupply); } function transferToInternalNetwork( address sender, uint256 amount ) external { _transferToInternalNetwork(sender, amount); } function unpause() external { _unpause(msg.sender); } function getInternalSupply() external view returns (uint256) { return _getInternalSupply(); } // Causes a compilation error if super._pause is not internal function _disableSeizingPermamently( address account ) internal { super._disableSeizingPermamently(account); } // Causes a compilation error if super._pause is not internal function _pause( address account ) internal { super._pause(account); } // Causes a compilation error if super._setGateway is not internal function _setGateway( address newGateway ) internal { super._setGateway(newGateway); } // Causes a compilation error if super._setTotalSupply is not internal function _setInternalSupply( uint256 newInternalSupply ) internal { super._setInternalSupply(newInternalSupply); } // Causes a compilation error if super._transferToInternalNetwork is not internal function _transferToInternalNetwork( address sender, uint256 amount ) internal { super._transferToInternalNetwork(sender, amount); } // Causes a compilation error if super._unpause is not internal function _unpause( address account ) internal { super._unpause(account); } // Causes a compilation error if super._getInternalSupply is not internal function _getInternalSupply() internal view returns (uint256) { return super._getInternalSupply(); } }
Causes a compilation error if super._unpause is not internal
function _unpause( address account ) internal { super._unpause(account); }
6,379,882
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
Check if `_childId` is a child TAO of `_taoId` _taoId The TAO ID to be checked _childId The child TAO ID to check return true if yes. Otherwise return false./
function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); }
10,007,399
// BK Ok - Recent version pragma solidity ^0.4.11; // ---------------------------------------------------------------------------- // Dao.Casino Crowdsale Token Contract // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd for Dao.Casino 2017 // The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths, borrowed from OpenZeppelin // ---------------------------------------------------------------------------- library SafeMath { // ------------------------------------------------------------------------ // Add a number to another number, checking for overflows // ------------------------------------------------------------------------ // BK Ok - Overflow protected function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } // ------------------------------------------------------------------------ // Subtract a number from another number, checking for underflows // ------------------------------------------------------------------------ // BK Ok - Underflow protected function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { // BK Next 3 lines Ok address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); // BK Ok - Constructor assigns `owner` variable function Owned() { owner = msg.sender; } // BK Ok - Only owner can execute function modifier onlyOwner { // BK Ok - Could be replaced with `require(msg.sender == owner);` require(msg.sender == owner); _; } // BK Ok - Propose ownership transfer function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; } // BK Ok - Accept ownership transfer function acceptOwnership() { if (msg.sender == newOwner) { OwnershipTransferred(owner, newOwner); owner = newOwner; } } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract ERC20Token is Owned { // BK Ok - For overflow and underflow protection using SafeMath for uint; // ------------------------------------------------------------------------ // Total Supply // ------------------------------------------------------------------------ // BK Ok uint256 _totalSupply = 0; // ------------------------------------------------------------------------ // Balances for each account // ------------------------------------------------------------------------ // BK Ok mapping(address => uint256) balances; // ------------------------------------------------------------------------ // Owner of account approves the transfer of an amount to another account // ------------------------------------------------------------------------ // BK Ok mapping(address => mapping (address => uint256)) allowed; // ------------------------------------------------------------------------ // Get the total token supply // ------------------------------------------------------------------------ // BK Ok function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } // ------------------------------------------------------------------------ // Get the account balance of another account with address _owner // ------------------------------------------------------------------------ // BK Ok function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner&#39;s account to another account // ------------------------------------------------------------------------ // BK NOTE - This function will return true/false instead of throwing an // error, as the conditions protect against overflows and // underflows // BK NOTE - This function does not protect against the short address // bug, but the short address bug is more the responsibility // of automated processes checking the data sent to this function function transfer(address _to, uint256 _amount) returns (bool success) { // BK Ok - Account has sufficient balance to transfer if (balances[msg.sender] >= _amount // User has balance // BK Ok - Non-zero amount && _amount > 0 // Non-zero transfer // BK Ok - Overflow protection && balances[_to] + _amount > balances[_to] // Overflow check ) { // BK Ok balances[msg.sender] = balances[msg.sender].sub(_amount); // BK Ok balances[_to] = balances[_to].add(_amount); // BK Ok - Logging Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the // current allowance with _value. // ------------------------------------------------------------------------ // BK NOTE - This simpler method of `approve(...)` together with // `transferFrom(...)` can be used in the double spending attack, // but the risk is low, and can be mitigated by the user setting // the approval limit to 0 before changing the limit function approve( address _spender, uint256 _amount ) returns (bool success) { // BK Ok allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner&#39;s // balance to the spender&#39;s account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ // BK NOTE - This function will return true/false instead of throwing an // error, as the conditions protect against overflows and // underflows // BK NOTE - This simpler method of `transferFrom(...)` together with // `approve(...)` can be used in the double spending attack, // but the risk is low, and can be mitigated by the user setting // the approval limit to 0 before changing the limit // BK NOTE - This function does not protect against the short address // bug, but the short address bug is more the responsibility // of automated processes checking the data sent to this function function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { // BK Ok - Account has sufficient balance to transfer if (balances[_from] >= _amount // From a/c has balance // BK Ok - Account is authorised to spend at least this amount && allowed[_from][msg.sender] >= _amount // Transfer approved // BK Ok - Non-zero amount && _amount > 0 // Non-zero transfer // BK Ok - Overflow protection && balances[_to] + _amount > balances[_to] // Overflow check ) { // BK Ok balances[_from] = balances[_from].sub(_amount); // BK Ok allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); // BK Ok balances[_to] = balances[_to].add(_amount); // BK Ok Transfer(_from, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ // BK Ok function allowance( address _owner, address _spender ) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // BK Ok event Transfer(address indexed _from, address indexed _to, uint256 _value); // BK Ok event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ArenaplayToken is ERC20Token { // ------------------------------------------------------------------------ // Token information // ------------------------------------------------------------------------ // BK Next 3 lines Ok. Using uint8 for decimals instead of uint256 string public constant symbol = "APY"; string public constant name = "Arenaplay.io"; uint8 public constant decimals = 18; // > new Date("2017-06-29T13:00:00").getTime()/1000 // 1498741200 // Do not use `now` here // BK NOTE - This contract uses the date/time instead of blocks to determine // the start, end and BET/ETH scale. The use of date/time in // these contracts can be used by miners to skew the block time. // This is not a significant risk in a crowdfunding contract. uint256 public constant STARTDATE = 1501173471; // BK Ok uint256 public constant ENDDATE = STARTDATE + 39 days; // Cap USD 25mil @ 296.1470 ETH/USD // BK NOTE - The following constant will need to be updated with the correct // ETH/USD exchange rate. The aim for Dao.Casino is to raise // USD 25 million, INCLUDING the precommitments. This cap will // have to take into account the ETH equivalent amount of the // precommitment uint256 public constant CAP = 44432 ether; // Cannot have a constant address here - Solidity bug // https://github.com/ethereum/solidity/issues/2441 // BK Ok address public multisig = 0x0e43311768025D0773F62fBF4a6cd083C508d979; // BK Ok - To compare against the `CAP` variable uint256 public totalEthers; // BK Ok - Constructor function ArenplayToken() { } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // BK Ok - Calculate the BET/ETH at this point in time function buyPrice() constant returns (uint256) { return buyPriceAt(now); } // BK Ok - Calculate BET/ETH at any point in time. Can be used in EtherScan // to determine past, current or future BET/ETH rate // BK NOTE - Scale is continuous function buyPriceAt(uint256 at) constant returns (uint256) { if (at < STARTDATE) { return 0; } else if (at < (STARTDATE + 9 days)) { return 2700; } else if (at < (STARTDATE + 18 days)) { return 2400; } else if (at < (STARTDATE + 27 days)) { return 2050; } else if (at <= ENDDATE) { return 1500; } else { return 0; } } // ------------------------------------------------------------------------ // Buy tokens from the contract // ------------------------------------------------------------------------ // BK Ok - Account can send tokens directly to this contract&#39;s address function () payable { proxyPayment(msg.sender); } // ------------------------------------------------------------------------ // Exchanges can buy on behalf of participant // ------------------------------------------------------------------------ // BK Ok function proxyPayment(address participant) payable { // No contributions before the start of the crowdsale // BK Ok require(now >= STARTDATE); // No contributions after the end of the crowdsale // BK Ok require(now <= ENDDATE); // No 0 contributions // BK Ok require(msg.value > 0); // Add ETH raised to total // BK Ok - Overflow protected totalEthers = totalEthers.add(msg.value); // Cannot exceed cap // BK Ok require(totalEthers <= CAP); // What is the BET to ETH rate // BK Ok uint256 _buyPrice = buyPrice(); // Calculate #BET - this is safe as _buyPrice is known // and msg.value is restricted to valid values // BK Ok uint tokens = msg.value * _buyPrice; // Check tokens > 0 // BK Ok require(tokens > 0); // Compute tokens for foundation 30% // Number of tokens restricted so maths is safe // BK Ok uint multisigTokens = tokens * 2 / 7; // Add to total supply // BK Ok _totalSupply = _totalSupply.add(tokens); // BK Ok _totalSupply = _totalSupply.add(multisigTokens); // Add to balances // BK Ok balances[participant] = balances[participant].add(tokens); // BK Ok balances[multisig] = balances[multisig].add(multisigTokens); // Log events // BK Next 4 lines Ok TokensBought(participant, msg.value, totalEthers, tokens, multisigTokens, _totalSupply, _buyPrice); Transfer(0x0, participant, tokens); Transfer(0x0, multisig, multisigTokens); // Move the funds to a safe wallet // https://github.com/ConsenSys/smart-contract-best-practices#be-aware-of-the-tradeoffs-between-send-transfer-and-callvalue multisig.transfer(msg.value); } // BK Ok event TokensBought(address indexed buyer, uint256 ethers, uint256 newEtherBalance, uint256 tokens, uint256 multisigTokens, uint256 newTotalSupply, uint256 buyPrice); // ------------------------------------------------------------------------ // Owner to add precommitment funding token balance before the crowdsale // commences // ------------------------------------------------------------------------ // BK NOTE - Owner can only execute this before the crowdsale starts // BK NOTE - Owner must add amount * 3 / 7 for the foundation for each // precommitment amount // BK NOTE - The CAP must take into account the equivalent ETH raised // for the precommitment amounts function addPrecommitment(address participant, uint balance) onlyOwner { // BK Ok require(now < STARTDATE); // BK Ok require(balance > 0); // BK Ok balances[participant] = balances[participant].add(balance); // BK Ok _totalSupply = _totalSupply.add(balance); // BK Ok Transfer(0x0, participant, balance); } // ------------------------------------------------------------------------ // Transfer the balance from owner&#39;s account to another account, with a // check that the crowdsale is finalised // ------------------------------------------------------------------------ // BK Ok function transfer(address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached // BK Ok require(now > ENDDATE || totalEthers == CAP); // Standard transfer // BK Ok return super.transfer(_to, _amount); } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner&#39;s // balance to another account, with a check that the crowdsale is // finalised // ------------------------------------------------------------------------ // BK Ok function transferFrom(address _from, address _to, uint _amount) returns (bool success) { // Cannot transfer before crowdsale ends or cap reached // BK Ok require(now > ENDDATE || totalEthers == CAP); // Standard transferFrom // BK Ok return super.transferFrom(_from, _to, _amount); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ // BK Ok - Only owner function transferAnyERC20Token(address tokenAddress, uint amount) onlyOwner returns (bool success) { // BK Ok return ERC20Token(tokenAddress).transfer(owner, amount); } }
BK Ok - Propose ownership transfer
function transferOwnership(address _newOwner) onlyOwner { newOwner = _newOwner; }
7,879,878
./partial_match/222000222/0x40C4A5Ad0C2a3213C0c3D47eE077849cbE7A24a0/sources/contracts/collections/NFTify721.sol
Handle mint request Requirement: - caller must be owner or controller/
function mint( address account, uint256 id, bytes memory data ) public { require( _msgSender() == controller || _msgSender() == owner(), "NFTify721: only owner or controller" ); _safeMint(account, id, data); }
16,909,842
./partial_match/1/0x89bc08BA00f135d608bc335f6B33D7a9ABCC98aF/sources/contracts/LoanCore.sol
Returns the LoanData struct for the specified loan ID. loanId The ID of the given loan. return loanData The struct containing loan state and terms./
function getLoan(uint256 loanId) external view override returns (LoanLibrary.LoanData memory loanData) { return loans[loanId]; }
15,886,952
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is ERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private _initSupply; constructor (string name, string symbol, uint8 decimals, uint256 initSupply) public { _name = name; _symbol = symbol; _decimals = decimals; _initSupply = initSupply.mul(10 **uint256(decimals)); } /** * @return the name of the token. */ function name() public view returns (string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * @return the initial Supply of the token. */ function initSupply() public view returns (uint256) { return _initSupply; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } /** * @title C11 * @dev ERC20 Token */ contract C11 is ERC20, ERC20Detailed, Ownable, ReentrancyGuard { using SafeMath for uint256; mapping (address => bool) status; // Address where funds can be collected address private _walletP; // Address where funds can be collected too address private _walletN; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // _rate multiply index uint256 private _x; // _rate share index uint256 private _y; // Amount of wei raised uint256 private _weiRaised; /** * @dev Constructor that gives msg.sender initialSupply of existing tokens. */ constructor () public ERC20Detailed("C11", "C11", 18, 20000000 ) { _mint(msg.sender, initSupply()); } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyOwner returns (bool) { _mint(to, value); return true; } /** * @dev Function to burn tokens * @param to The address to burn tokens. * @param value The amount of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function burn(address to, uint256 value) public onlyOwner returns (bool) { _burn(to, value); return true; } /** * @dev check an account's status * @return bool */ function CheckStatus(address account) public view returns (bool) { require(account != address(0)); bool currentStatus = status[account]; return currentStatus; } /** * @dev change an account's status. OnlyOwner * @return bool */ function ChangeStatus(address account) public onlyOwner { require(account != address(0)); bool currentStatus1 = status[account]; status[account] = (currentStatus1 == true) ? false : true; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer fund with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(msg.sender, msg.value); } function buyTokens(address beneficiary, uint256 weiAmount) public nonReentrant payable { require(beneficiary != address(0) && beneficiary !=_walletP && beneficiary !=_walletN); require(weiAmount != 0); require(_walletP != 0); require(_walletN != 0); require(CheckStatus(beneficiary) != true); // calculate token amount to be created uint256 tokens = weiAmount.div(_y).mul(_x).mul(_rate); // compass address CurrentFundWallet = (balanceOf(_walletP) > balanceOf(_walletN) == true) ? _walletP : _walletN; // check token amount to be transfered from _wallet require(balanceOf(CurrentFundWallet) > tokens); // update state _weiRaised = _weiRaised.add(weiAmount); // transfer tokens to beneficiary from CurrentFundWallet _transfer(CurrentFundWallet, beneficiary, tokens); // transfer weiAmount to CurrentFundWallet CurrentFundWallet.transfer(weiAmount); } /** * Set Rate. onlyOwner */ function setRate(uint256 rate) public onlyOwner { require(rate > 1); _rate = rate; } /** * Set X. onlyOwner */ function setX(uint256 x) public onlyOwner { require(x >= 1); _x = x; } /** * Set Y. onlyOwner */ function setY(uint256 y) public onlyOwner { require(y >= 1); _y = y; } /** * Set the Positiv _wallet. onlyOwner */ function setPositivWallet(address PositivWallet) public onlyOwner { _walletP = PositivWallet; } /** * @return the Positiv _wallet. */ function PositivWallet() public view returns (address) { return _walletP; } /** * Set the Negativ _wallet. onlyOwner */ function setNegativWallet(address NegativWallet) public onlyOwner { _walletN = NegativWallet; } /** * @return the Negativ _wallet. */ function NegativWallet() public view returns (address) { return _walletN; } /** * @return Rate. */ function Rate() public view returns (uint256) { return _rate; } /** * @return _X. */ function X() public view returns (uint256) { return _x; } /** * @return _Y. */ function Y() public view returns (uint256) { return _y; } /** * @return the number of wei income Total. */ function WeiRaised() public view returns (uint256) { return _weiRaised; } }
check an account's status return bool/
function CheckStatus(address account) public view returns (bool) { require(account != address(0)); bool currentStatus = status[account]; return currentStatus; }
15,792,462
./full_match/137/0x9D006610b7F491aaCd03449D13020Ca99f62A661/sources/contracts/vdfyn.sol
Leave the lair. Claim back your QUICK.
function leave(uint256 _dQuickAmount) external { uint256 totalDQuick = totalSupply(); uint256 quickAmount = _dQuickAmount.mul(quick.balanceOf(address(this))).div(totalDQuick); _burn(msg.sender, _dQuickAmount); quick.transfer(msg.sender, quickAmount); }
4,724,798
./partial_match/1/0x9e376F30D4e47Cc4f792BfC682caeb5dc76155f7/sources/MarketCreationRewards.sol
function to calculate user incentive for market creation _createdBy Address of market creator _gasCosumed Gas consumed by the transaction till now _marketId Index of market/Adding buffer gas for below calculations
function calculateMarketCreationIncentive(address _createdBy, uint256 _gasCosumed, uint64 _marketId) external onlyInternal { _checkIfCreatorStaked(_createdBy, _marketId); marketCreationRewardUserData[_createdBy].marketsCreated.push(_marketId); uint256 gasUsedTotal; gasUsedTotal = _gasCosumed + 84000; uint256 gasPrice = _checkGasPrice(); uint256 gasCost = gasUsedTotal.mul(gasPrice); (, uint256 incentive) = marketUtility.getValueAndMultiplierParameters(ETH_ADDRESS, gasCost); marketCreationRewardUserData[_createdBy].incentives = marketCreationRewardUserData[_createdBy].incentives.add(incentive); emit MarketCreationReward(_createdBy, _marketId, incentive, gasUsedTotal, gasCost, gasPrice, tx.gasprice, maxGasPrice, marketCreationRewardData[_marketId].rewardPoolSharePerc); }
15,474,625
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/KeepToken.sol"; import "@keep-network/keep-core/contracts/TokenStaking.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/cryptography/MerkleProof.sol"; /// @title ECDSA Rewards distributor /// @notice This contract can be used by stakers to claim their rewards for /// participation in the keep network for operating ECDSA nodes. /// @dev This contract is based on the Uniswap's Merkle Distributor /// https://github.com/Uniswap/merkle-distributor with some modifications: /// - added a map of merkle root keys. Whenever a new merkle root is put in the /// map, we assign 'true' value to this key /// - added 'allocate()' function that will be called each time to allocate /// new KEEP rewards for a given merkle root. Merkle root is going to be generated /// regulary (ex. every week) and it is also means that an interval for that /// merkle root has passed /// - changed code accordingly to process claimed rewards using a map of merkle /// roots contract ECDSARewardsDistributor is Ownable { using SafeERC20 for KeepToken; KeepToken public token; TokenStaking public tokenStaking; // This event is triggered whenever a call to #claim succeeds. event RewardsClaimed( bytes32 indexed merkleRoot, uint256 indexed index, address indexed operator, address beneficiary, uint256 amount ); // This event is triggered whenever rewards are allocated. event RewardsAllocated(bytes32 merkleRoot, uint256 amount); // Map of merkle roots indicating whether a given interval was allocated with // KEEP token rewards. For each interval there is always created a new merkle // tree including a root, rewarded operators along with their amounts and proofs. mapping(bytes32 => bool) private merkleRoots; // Bytes32 key is a merkle root and the value is a packed array of booleans. mapping(bytes32 => mapping(uint256 => uint256)) private claimedBitMap; constructor(address _token, address _tokenStaking) public { token = KeepToken(_token); tokenStaking = TokenStaking(_tokenStaking); } /// Claim KEEP rewards for a given merkle root (interval) and the given operator /// address. Rewards will be sent to a beneficiary assigned to the operator. /// @param merkleRoot Merkle root for a given interval. /// @param index Index of the operator in the merkle tree. /// @param operator Operator address that reward will be claimed. /// @param amount The amount of KEEP reward to be claimed. /// @param merkleProof Array of merkle proofs. function claim( bytes32 merkleRoot, uint256 index, address operator, uint256 amount, bytes32[] calldata merkleProof ) external { require( merkleRoots[merkleRoot], "Rewards must be allocated for a given merkle root" ); require(!isClaimed(merkleRoot, index), "Reward already claimed"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, operator, amount)); require( MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof" ); // Mark it claimed and send the token. _setClaimed(merkleRoot, index); address beneficiary = tokenStaking.beneficiaryOf(operator); require(IERC20(token).transfer(beneficiary, amount), "Transfer failed"); emit RewardsClaimed(merkleRoot, index, operator, beneficiary, amount); } /// Allocates amount of KEEP for a given merkle root. /// @param merkleRoot Merkle root for a given interval. /// @param amount The amount of KEEP tokens allocated for the merkle root. function allocate(bytes32 merkleRoot, uint256 amount) public onlyOwner { token.safeTransferFrom(msg.sender, address(this), amount); merkleRoots[merkleRoot] = true; emit RewardsAllocated(merkleRoot, amount); } function isClaimed(bytes32 merkleRoot, uint256 index) public view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[merkleRoot][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(bytes32 merkleRoot, uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[merkleRoot][claimedWordIndex] = claimedBitMap[merkleRoot][claimedWordIndex] | (1 << claimedBitIndex); } } pragma solidity 0.5.17; import "@keep-network/keep-core/contracts/PhasedEscrow.sol"; /// @title ECDSARewardsEscrowBeneficiary /// @notice Transfer the received tokens from PhasedEscrow to a designated /// ECDSARewards contract. contract ECDSARewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } /// @title ECDSABackportRewardsEscrowBeneficiary /// @notice Trasfer the received tokens from Phased Escrow to a designated /// ECDSABackportRewards contract. contract ECDSABackportRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./Escrow.sol"; interface IBeneficiaryContract { function __escrowSentTokens(uint256 amount) external; } /// @title PhasedEscrow /// @notice A token holder contract allowing contract owner to set beneficiary of /// tokens held by the contract and allowing the owner to withdraw the /// tokens to that beneficiary in phases. contract PhasedEscrow is Ownable { using SafeERC20 for IERC20; event BeneficiaryUpdated(address beneficiary); event TokensWithdrawn(address beneficiary, uint256 amount); IERC20 public token; IBeneficiaryContract public beneficiary; constructor(IERC20 _token) public { token = _token; } /// @notice Funds the escrow by transferring all of the approved tokens /// to the escrow. function receiveApproval( address _from, uint256 _value, address _token, bytes memory ) public { require(IERC20(_token) == token, "Unsupported token"); token.safeTransferFrom(_from, address(this), _value); } /// @notice Sets the provided address as a beneficiary allowing it to /// withdraw all tokens from escrow. This function can be called only /// by escrow owner. function setBeneficiary(IBeneficiaryContract _beneficiary) external onlyOwner { beneficiary = _beneficiary; emit BeneficiaryUpdated(address(beneficiary)); } /// @notice Withdraws the specified number of tokens from escrow to the /// beneficiary. If the beneficiary is not set, or there are /// insufficient tokens in escrow, the function fails. function withdraw(uint256 amount) external onlyOwner { require(address(beneficiary) != address(0), "Beneficiary not assigned"); uint256 balance = token.balanceOf(address(this)); require(amount <= balance, "Not enough tokens for withdrawal"); token.safeTransfer(address(beneficiary), amount); emit TokensWithdrawn(address(beneficiary), amount); beneficiary.__escrowSentTokens(amount); } /// @notice Withdraws all funds from a non-phased Escrow passed as /// a parameter. For this function to succeed, this PhasedEscrow /// has to be set as a beneficiary of the non-phased Escrow. function withdrawFromEscrow(Escrow _escrow) public { _escrow.withdraw(); } } interface ICurveRewards { function notifyRewardAmount(uint256 amount) external; } /// @title CurveRewardsEscrowBeneficiary /// @notice A beneficiary contract that can receive a withdrawal phase from a /// PhasedEscrow contract. Immediately stakes the received tokens on a /// designated CurveRewards contract. contract CurveRewardsEscrowBeneficiary is Ownable { IERC20 public token; ICurveRewards public curveRewards; constructor(IERC20 _token, ICurveRewards _curveRewards) public { token = _token; curveRewards = _curveRewards; } function __escrowSentTokens(uint256 amount) external onlyOwner { token.approve(address(curveRewards), amount); curveRewards.notifyRewardAmount(amount); } } /// @dev Interface of recipient contract for approveAndCall pattern. interface IStakerRewards { function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } /// @title StakerRewardsBeneficiary /// @notice An abstract beneficiary contract that can receive a withdrawal phase /// from a PhasedEscrow contract. The received tokens are immediately /// funded for a designated rewards escrow beneficiary contract. contract StakerRewardsBeneficiary is Ownable { IERC20 public token; IStakerRewards public stakerRewards; constructor(IERC20 _token, IStakerRewards _stakerRewards) public { token = _token; stakerRewards = _stakerRewards; } function __escrowSentTokens(uint256 amount) external onlyOwner { bool success = token.approve(address(stakerRewards), amount); require(success, "Token transfer approval failed"); stakerRewards.receiveApproval( address(this), amount, address(token), "" ); } } /// @title BeaconBackportRewardsEscrowBeneficiary /// @notice Transfer the received tokens to a designated /// BeaconBackportRewardsEscrowBeneficiary contract. contract BeaconBackportRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } /// @title BeaconRewardsEscrowBeneficiary /// @notice Transfer the received tokens to a designated /// BeaconRewardsEscrowBeneficiary contract. contract BeaconRewardsEscrowBeneficiary is StakerRewardsBeneficiary { constructor(IERC20 _token, IStakerRewards _stakerRewards) public StakerRewardsBeneficiary(_token, _stakerRewards) {} } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; // @title Escrow // @notice A token holder contract allowing contract owner to set beneficiary of // all tokens held by the contract and allowing the beneficiary to withdraw // the tokens. contract Escrow is Ownable { using SafeERC20 for IERC20; event BeneficiaryUpdated(address beneficiary); event TokensWithdrawn(address beneficiary, uint256 amount); IERC20 public token; address public beneficiary; constructor(IERC20 _token) public { token = _token; } // @notice Sets the provided address as a beneficiary allowing it to // withdraw all tokens from escrow. This function can be called only // by escrow owner. function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = _beneficiary; emit BeneficiaryUpdated(beneficiary); } // @notice Withdraws all tokens from escrow to the beneficiary. // If the beneficiary is not set, caller is not the beneficiary, or there // are no tokens in escrow, function fails. function withdraw() public { require(beneficiary != address(0), "Beneficiary not assigned"); require(msg.sender == beneficiary, "Caller is not the beneficiary"); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "No tokens to withdraw"); token.safeTransfer(beneficiary, amount); emit TokensWithdrawn(beneficiary, amount); } } pragma solidity ^0.5.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash < proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; /// @dev Interface of recipient contract for approveAndCall pattern. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } /// @title KEEP Token /// @dev Standard ERC20Burnable token contract KeepToken is ERC20Burnable, ERC20Detailed { string public constant NAME = "KEEP Token"; string public constant SYMBOL = "KEEP"; uint8 public constant DECIMALS = 18; // The number of digits after the decimal place when displaying token values on-screen. uint256 public constant INITIAL_SUPPLY = 10**27; // 1 billion tokens, 18 decimal places. /// @dev Gives msg.sender all of existing tokens. constructor() public ERC20Detailed(NAME, SYMBOL, DECIMALS) { _mint(msg.sender, INITIAL_SUPPLY); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` tokens /// on your behalf and then ping the contract about it. /// @param _spender The address authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } } pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity ^0.5.0; import "./ERC20.sol"; /** * @dev Extension of `ERC20` that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is ERC20 { /** * @dev Destoys `amount` tokens from the caller. * * See `ERC20._burn`. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev See `ERC20._burnFrom`. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./StakeDelegatable.sol"; import "./libraries/staking/MinimumStakeSchedule.sol"; import "./libraries/staking/GrantStaking.sol"; import "./libraries/staking/Locks.sol"; import "./libraries/staking/TopUps.sol"; import "./utils/PercentUtils.sol"; import "./utils/BytesLib.sol"; import "./Authorizations.sol"; import "./TokenStakingEscrow.sol"; import "./TokenSender.sol"; /// @title TokenStaking /// @notice A token staking contract for a specified standard ERC20Burnable token. /// A holder of the specified token can stake delegate its tokens to this contract /// and recover the stake after undelegation period is over. contract TokenStaking is Authorizations, StakeDelegatable { using BytesLib for bytes; using SafeMath for uint256; using PercentUtils for uint256; using SafeERC20 for ERC20Burnable; using GrantStaking for GrantStaking.Storage; using Locks for Locks.Storage; using TopUps for TopUps.Storage; event StakeDelegated( address indexed owner, address indexed operator ); event OperatorStaked( address indexed operator, address indexed beneficiary, address indexed authorizer, uint256 value ); event StakeOwnershipTransferred( address indexed operator, address indexed newOwner ); event TopUpInitiated(address indexed operator, uint256 topUp); event TopUpCompleted(address indexed operator, uint256 newAmount); event Undelegated(address indexed operator, uint256 undelegatedAt); event RecoveredStake(address operator); event TokensSlashed(address indexed operator, uint256 amount); event TokensSeized(address indexed operator, uint256 amount); event StakeLocked(address indexed operator, address lockCreator, uint256 until); event LockReleased(address indexed operator, address lockCreator); event ExpiredLockReleased(address indexed operator, address lockCreator); uint256 public deployedAt; uint256 public initializationPeriod; // varies between mainnet and testnet ERC20Burnable internal token; TokenGrant internal tokenGrant; TokenStakingEscrow internal escrow; GrantStaking.Storage internal grantStaking; Locks.Storage internal locks; TopUps.Storage internal topUps; uint256 internal constant twoWeeks = 1209600; // [sec] uint256 internal constant twoMonths = 5184000; // [sec] // 2020-04-28; the date of deploying KEEP token. // TX: 0xea22d72bc7de4c82798df7194734024a1f2fd57b173d0e065864ff4e9d3dc014 uint256 internal constant minimumStakeScheduleStart = 1588042366; /// @notice Creates a token staking contract for a provided Standard ERC20Burnable token. /// @param _token KEEP token contract. /// @param _tokenGrant KEEP token grant contract. /// @param _escrow Escrow dedicated for this staking contract. /// @param _registry Keep contract registry contract. /// @param _initializationPeriod To avoid certain attacks on work selection, recently created /// operators must wait for a specific period of time before being eligible for work selection. constructor( ERC20Burnable _token, TokenGrant _tokenGrant, TokenStakingEscrow _escrow, KeepRegistry _registry, uint256 _initializationPeriod ) Authorizations(_registry) public { token = _token; tokenGrant = _tokenGrant; escrow = _escrow; registry = _registry; initializationPeriod = _initializationPeriod; deployedAt = block.timestamp; } /// @notice Returns minimum amount of KEEP that allows sMPC cluster client to /// participate in the Keep network. Expressed as number with 18-decimal places. /// Initial minimum stake is higher than the final and lowered periodically based /// on the amount of steps and the length of the minimum stake schedule in seconds. function minimumStake() public view returns (uint256) { return MinimumStakeSchedule.current(minimumStakeScheduleStart); } /// @notice Returns the current value of the undelegation period. /// The staking contract guarantees that an undelegated operator’s stakes /// will stay locked for a period of time after undelegation, and thus /// available as collateral for any work the operator is engaged in. /// The undelegation period is two weeks for the first two months and /// two months after that. function undelegationPeriod() public view returns(uint256) { return block.timestamp < deployedAt.add(twoMonths) ? twoWeeks : twoMonths; } /// @notice Receives approval of token transfer and stakes the approved /// amount or adds the approved amount to an existing delegation (a “top-up”). /// In case of a top-up, it is expected that the operator stake is not /// undelegated and that the top-up is performed from the same source of /// tokens as the initial delegation. That is, if the tokens were delegated /// from a grant, top-up has to be performed from the same grant. If the /// delegation was done using liquid tokens, only liquid tokens from the /// same owner can be used to top-up the stake. /// Top-up can not be cancelled so it is important to be careful with the /// amount of KEEP added to the stake. /// @dev Requires that the provided token contract be the same one linked to /// this contract. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and stake. /// @param _token Token contract address. /// @param _extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes), ignored for a top-up /// - Operator address (20 bytes) /// - Authorizer address (20 bytes), ignored for a top-up /// - Grant ID (32 bytes) - required only when called by TokenStakingEscrow function receiveApproval( address _from, uint256 _value, address _token, bytes memory _extraData ) public { require(ERC20Burnable(_token) == token, "Unrecognized token"); require(_extraData.length >= 60, "Corrupted delegation data"); // Transfer tokens to this contract. token.safeTransferFrom(_from, address(this), _value); address operator = _extraData.toAddress(20); // See if there is an existing delegation for this operator... if (operators[operator].packedParams.getCreationTimestamp() == 0) { // If there is no existing delegation, delegate tokens using // beneficiary and authorizer passed in _extraData. delegate(_from, _value, operator, _extraData); } else { // If there is an existing delegation, top-up the stake. topUp(_from, _value, operator, _extraData); } } /// @notice Delegates tokens to a new operator using beneficiary and /// authorizer passed in _extraData parameter. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and stake. /// @param _operator The new operator address. /// @param _extraData Data for stake delegation as passed to receiveApproval. function delegate( address _from, uint256 _value, address _operator, bytes memory _extraData ) internal { require(_value >= minimumStake(), "Less than the minimum stake"); address payable beneficiary = address(uint160(_extraData.toAddress(0))); address authorizer = _extraData.toAddress(40); operators[_operator] = Operator( OperatorParams.pack(_value, block.timestamp, 0), _from, beneficiary, authorizer ); grantStaking.tryCapturingDelegationData( tokenGrant, address(escrow), _from, _operator, _extraData ); emit StakeDelegated(_from, _operator); emit OperatorStaked(_operator, beneficiary, authorizer, _value); } /// @notice Performs top-up to an existing operator. Tokens added during /// stake initialization period are immediatelly added to the stake and /// stake initialization timer is reset to the current block. Tokens added /// in a top-up after the stake initialization period is over are not /// included in the operator stake until the initialization period for /// a top-up passes and top-up is committed. Operator must not have the stake /// undelegated. It is expected that the top-up is done from the same source /// of tokens as the initial delegation. That is, if the tokens were /// delegated from a grant, top-up has to be performed from the same grant. /// If the delegation was done using liquid tokens, only liquid tokens from /// the same owner can be used to top-up the stake. /// Top-up can not be cancelled so it is important to be careful with the /// amount of KEEP added to the stake. /// @param _from The owner of the tokens who approved them to transfer. /// @param _value Approved amount for the transfer and top-up to /// an existing stake. /// @param _operator The new operator address. /// @param _extraData Data for stake delegation as passed to receiveApproval function topUp( address _from, uint256 _value, address _operator, bytes memory _extraData ) internal { // Top-up comes from a grant if it's been initiated from TokenGrantStake // contract or if it's been initiated from TokenStakingEscrow by // redelegation. bool isFromGrant = address(tokenGrant.grantStakes(_operator)) == _from || address(escrow) == _from; if (grantStaking.hasGrantDelegated(_operator)) { // Operator has grant delegated. We need to see if the top-up // is performed also from a grant. require(isFromGrant, "Must be from a grant"); // If it is from a grant, we need to make sure it's from the same // grant as the original delegation. We do not want to mix unlocking // schedules. uint256 previousGrantId = grantStaking.getGrantForOperator(_operator); (, uint256 grantId) = grantStaking.tryCapturingDelegationData( tokenGrant, address(escrow), _from, _operator, _extraData ); require(grantId == previousGrantId, "Not the same grant"); } else { // Operator has no grant delegated. We need to see if the top-up // is performed from liquid tokens of the same owner. require(!isFromGrant, "Must not be from a grant"); require(operators[_operator].owner == _from, "Not the same owner"); } uint256 operatorParams = operators[_operator].packedParams; if (!_isInitialized(operatorParams)) { // If the stake is not yet initialized, we add tokens immediately // but we also reset stake initialization time counter. operators[_operator].packedParams = topUps.instantComplete( _value, _operator, operatorParams, escrow ); } else { // If the stake is initialized, we do NOT add tokens immediately. // We initiate the top-up and will add tokens to the stake only // after the initialization period for a top-up passes. topUps.initiate(_value, _operator, operatorParams, escrow); } } /// @notice Commits pending top-up for the provided operator. If the top-up /// did not pass the initialization period, the function fails. /// @param _operator The operator with a pending top-up that is getting /// committed. function commitTopUp(address _operator) public { operators[_operator].packedParams = topUps.commit( _operator, operators[_operator].packedParams, initializationPeriod ); } /// @notice Cancels stake of tokens within the operator initialization period /// without being subjected to the token lockup for the undelegation period. /// This can be used to undo mistaken delegation to the wrong operator address. /// @param _operator Address of the stake operator. function cancelStake(address _operator) public { address owner = operators[_operator].owner; require( msg.sender == owner || msg.sender == _operator || grantStaking.canUndelegate(_operator, tokenGrant), "Not authorized" ); uint256 operatorParams = operators[_operator].packedParams; require( !_isInitialized(operatorParams), "Initialized stake" ); uint256 amount = operatorParams.getAmount(); operators[_operator].packedParams = operatorParams.setAmount(0); transferOrDeposit(owner, _operator, amount); } /// @notice Undelegates staked tokens. You will be able to recover your stake by calling /// `recoverStake()` with operator address once undelegation period is over. /// @param _operator Address of the stake operator. function undelegate(address _operator) public { undelegateAt(_operator, block.timestamp); } /// @notice Set an undelegation time for staked tokens. /// Undelegation will begin at the specified timestamp. /// You will be able to recover your stake by calling /// `recoverStake()` with operator address once undelegation period is over. /// @param _operator Address of the stake operator. /// @param _undelegationTimestamp The timestamp undelegation is to start at. function undelegateAt( address _operator, uint256 _undelegationTimestamp ) public { require( msg.sender == _operator || msg.sender == operators[_operator].owner || grantStaking.canUndelegate(_operator, tokenGrant), "Not authorized" ); uint256 oldParams = operators[_operator].packedParams; require( _undelegationTimestamp >= block.timestamp && _undelegationTimestamp > oldParams.getCreationTimestamp().add(initializationPeriod), "Invalid timestamp" ); uint256 existingUndelegationTimestamp = oldParams.getUndelegationTimestamp(); require( // Undelegation not in progress OR existingUndelegationTimestamp == 0 || // Undelegating sooner than previously set time OR existingUndelegationTimestamp > _undelegationTimestamp || // We have already checked above that msg.sender is owner, grantee, // or operator. Only owner and grantee are eligible to postpone the // delegation so it is enough if we exclude operator here. msg.sender != _operator, "Operator may not postpone" ); operators[_operator].packedParams = oldParams.setUndelegationTimestamp( _undelegationTimestamp ); emit Undelegated(_operator, _undelegationTimestamp); } /// @notice Recovers staked tokens and transfers them back to the owner. /// Recovering tokens can only be performed when the operator finished /// undelegating. /// @param _operator Operator address. function recoverStake(address _operator) public { uint256 operatorParams = operators[_operator].packedParams; require( operatorParams.getUndelegationTimestamp() != 0, "Not undelegated" ); require( _isUndelegatingFinished(operatorParams), "Still undelegating" ); require( !isStakeLocked(_operator), "Locked stake" ); uint256 amount = operatorParams.getAmount(); // If there is a pending top-up, force-commit it before returning tokens. amount = amount.add(topUps.cancel(_operator)); operators[_operator].packedParams = operatorParams.setAmount(0); transferOrDeposit(operators[_operator].owner, _operator, amount); emit RecoveredStake(_operator); } /// @notice Gets stake delegation info for the given operator. /// @param _operator Operator address. /// @return amount The amount of tokens the given operator delegated. /// @return createdAt The time when the stake has been delegated. /// @return undelegatedAt The time when undelegation has been requested. /// If undelegation has not been requested, 0 is returned. function getDelegationInfo(address _operator) public view returns (uint256 amount, uint256 createdAt, uint256 undelegatedAt) { return operators[_operator].packedParams.unpack(); } /// @notice Locks given operator stake for the specified duration. /// Locked stake may not be recovered until the lock expires or is released, /// even if the normal undelegation period has passed. /// Only previously authorized operator contract can lock the stake. /// @param operator Operator address. /// @param duration Lock duration in seconds. function lockStake( address operator, uint256 duration ) public onlyApprovedOperatorContract(msg.sender) { require( isAuthorizedForOperator(operator, msg.sender), "Not authorized" ); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isUndelegating(operatorParams), "Undelegating stake" ); locks.lockStake(operator, duration); } /// @notice Removes a lock the caller had previously placed on the operator. /// @dev Only for operator contracts. /// To remove expired or disabled locks, use `releaseExpiredLocks`. /// The authorization check ensures that the caller must have been able /// to place a lock on the operator sometime in the past. /// We don't need to check for current approval status of the caller /// because unlocking stake cannot harm the operator /// nor interfere with other operator contracts. /// Therefore even disabled operator contracts may freely unlock stake. /// @param operator Operator address. function unlockStake( address operator ) public { require( isAuthorizedForOperator(operator, msg.sender), "Not authorized" ); locks.releaseLock(operator); } /// @notice Removes the lock of the specified operator contract /// if the lock has expired or the contract has been disabled. /// @dev Necessary for removing locks placed by contracts /// that have been disabled by the panic button. /// Also applicable to prevent inadvertent DoS of `recoverStake` /// if too many operator contracts have failed to clean up their locks. function releaseExpiredLock( address operator, address operatorContract ) public { locks.releaseExpiredLock(operator, operatorContract, address(this)); } /// @notice Check whether the operator has any active locks /// that haven't expired yet /// and whose creators aren't disabled by the panic button. function isStakeLocked(address operator) public view returns (bool) { return locks.isStakeLocked(operator, address(this)); } /// @notice Get the locks placed on the operator. /// @return creators The addresses of operator contracts /// that have placed a lock on the operator. /// @return expirations The expiration times /// of the locks placed on the operator. function getLocks(address operator) public view returns (address[] memory creators, uint256[] memory expirations) { return locks.getLocks(operator); } /// @notice Slash provided token amount from every member in the misbehaved /// operators array and burn 100% of all the tokens. /// @param amountToSlash Token amount to slash from every misbehaved operator. /// @param misbehavedOperators Array of addresses to seize the tokens from. function slash(uint256 amountToSlash, address[] memory misbehavedOperators) public onlyApprovedOperatorContract(msg.sender) { uint256 totalAmountToBurn; address authoritySource = getAuthoritySource(msg.sender); for (uint i = 0; i < misbehavedOperators.length; i++) { address operator = misbehavedOperators[i]; require(authorizations[authoritySource][operator], "Not authorized"); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isStakeReleased(operator, operatorParams, msg.sender), "Stake is released" ); uint256 currentAmount = operatorParams.getAmount(); if (currentAmount < amountToSlash) { totalAmountToBurn = totalAmountToBurn.add(currentAmount); operators[operator].packedParams = operatorParams.setAmount(0); emit TokensSlashed(operator, currentAmount); } else { totalAmountToBurn = totalAmountToBurn.add(amountToSlash); operators[operator].packedParams = operatorParams.setAmount( currentAmount.sub(amountToSlash) ); emit TokensSlashed(operator, amountToSlash); } } token.burn(totalAmountToBurn); } /// @notice Seize provided token amount from every member in the misbehaved /// operators array. The tattletale is rewarded with 5% of the total seized /// amount scaled by the reward adjustment parameter and the rest 95% is burned. /// @param amountToSeize Token amount to seize from every misbehaved operator. /// @param rewardMultiplier Reward adjustment in percentage. Min 1% and 100% max. /// @param tattletale Address to receive the 5% reward. /// @param misbehavedOperators Array of addresses to seize the tokens from. function seize( uint256 amountToSeize, uint256 rewardMultiplier, address tattletale, address[] memory misbehavedOperators ) public onlyApprovedOperatorContract(msg.sender) { uint256 totalAmountToBurn; address authoritySource = getAuthoritySource(msg.sender); for (uint i = 0; i < misbehavedOperators.length; i++) { address operator = misbehavedOperators[i]; require(authorizations[authoritySource][operator], "Not authorized"); uint256 operatorParams = operators[operator].packedParams; require( _isInitialized(operatorParams), "Inactive stake" ); require( !_isStakeReleased(operator, operatorParams, msg.sender), "Stake is released" ); uint256 currentAmount = operatorParams.getAmount(); if (currentAmount < amountToSeize) { totalAmountToBurn = totalAmountToBurn.add(currentAmount); operators[operator].packedParams = operatorParams.setAmount(0); emit TokensSeized(operator, currentAmount); } else { totalAmountToBurn = totalAmountToBurn.add(amountToSeize); operators[operator].packedParams = operatorParams.setAmount( currentAmount.sub(amountToSeize) ); emit TokensSeized(operator, amountToSeize); } } uint256 tattletaleReward = (totalAmountToBurn.percent(5)).percent(rewardMultiplier); token.safeTransfer(tattletale, tattletaleReward); token.burn(totalAmountToBurn.sub(tattletaleReward)); } /// @notice Allows the current staking relationship owner to transfer the /// ownership to someone else. /// @param operator Address of the stake operator. /// @param newOwner Address of the new staking relationship owner. function transferStakeOwnership(address operator, address newOwner) public { require(msg.sender == operators[operator].owner, "Not authorized"); operators[operator].owner = newOwner; emit StakeOwnershipTransferred(operator, newOwner); } /// @notice Gets the eligible stake balance of the specified address. /// An eligible stake is a stake that passed the initialization period /// and is not currently undelegating. Also, the operator had to approve /// the specified operator contract. /// /// Operator with a minimum required amount of eligible stake can join the /// network and participate in new work selection. /// /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. /// @return an uint256 representing the eligible stake balance. function eligibleStake( address _operator, address _operatorContract ) public view returns (uint256 balance) { uint256 operatorParams = operators[_operator].packedParams; // To be eligible for work selection, the operator must: // - have the operator contract authorized // - have the stake initialized // - must not be undelegating; keep in mind the `undelegatedAt` may be // set to a time in the future, to schedule undelegation in advance. // In this case the operator is still eligible until the timestamp // `undelegatedAt`. if ( isAuthorizedForOperator(_operator, _operatorContract) && _isInitialized(operatorParams) && !_isUndelegating(operatorParams) ) { balance = operatorParams.getAmount(); } } /// @notice Gets the active stake balance of the specified address. /// An active stake is a stake that passed the initialization period, /// and may be in the process of undelegation /// but has not been released yet, /// either because the undelegation period is not over, /// or because the operator contract has an active lock on the operator. /// Also, the operator had to approve the specified operator contract. /// /// The difference between eligible stake is that active stake does not make /// the operator eligible for work selection but it may be still finishing /// earlier work until the stake is released. /// Operator with a minimum required /// amount of active stake can join the network but cannot be selected to any /// new work. /// /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. /// @return an uint256 representing the eligible stake balance. function activeStake( address _operator, address _operatorContract ) public view returns (uint256 balance) { uint256 operatorParams = operators[_operator].packedParams; if ( isAuthorizedForOperator(_operator, _operatorContract) && _isInitialized(operatorParams) && !_isStakeReleased( _operator, operatorParams, _operatorContract ) ) { balance = operatorParams.getAmount(); } } /// @notice Checks if the specified account has enough active stake to become /// network operator and that the specified operator contract has been /// authorized for potential slashing. /// /// Having the required minimum of active stake makes the operator eligible /// to join the network. If the active stake is not currently undelegating, /// operator is also eligible for work selection. /// /// @param staker Staker's address /// @param operatorContract Operator contract's address /// @return True if has enough active stake to participate in the network, /// false otherwise. function hasMinimumStake( address staker, address operatorContract ) public view returns(bool) { return activeStake(staker, operatorContract) >= minimumStake(); } /// @notice Is the operator with the given params initialized function _isInitialized(uint256 _operatorParams) internal view returns (bool) { return block.timestamp > _operatorParams.getCreationTimestamp().add(initializationPeriod); } /// @notice Is the operator with the given params undelegating function _isUndelegating(uint256 _operatorParams) internal view returns (bool) { uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt); } /// @notice Has the operator with the given params finished undelegating function _isUndelegatingFinished(uint256 _operatorParams) internal view returns (bool) { uint256 undelegatedAt = _operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt.add(undelegationPeriod())); } /// @notice Get whether the operator's stake is released /// as far as the operator contract is concerned. /// If the operator contract has a lock on the operator, /// the operator's stake is be released when the lock expires. /// Otherwise the stake is released when the operator finishes undelegating. function _isStakeReleased( address _operator, uint256 _operatorParams, address _operatorContract ) internal view returns (bool) { return _isUndelegatingFinished(_operatorParams) && locks.isStakeReleased(_operator, _operatorContract); } function transferOrDeposit( address _owner, address _operator, uint256 _amount ) internal { if (grantStaking.hasGrantDelegated(_operator)) { // For tokens staked from a grant, transfer them to the escrow. TokenSender(address(token)).approveAndCall( address(escrow), _amount, abi.encode(_operator, grantStaking.getGrantForOperator(_operator)) ); } else { // For liquid tokens staked, transfer them straight to the owner. token.safeTransfer(_owner, _amount); } } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./utils/OperatorParams.sol"; /// @title Stake Delegatable /// @notice A base contract to allow stake delegation for staking contracts. contract StakeDelegatable { using OperatorParams for uint256; mapping(address => Operator) internal operators; struct Operator { uint256 packedParams; address owner; address payable beneficiary; address authorizer; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function balanceOf(address _address) public view returns (uint256 balance) { return operators[_address].packedParams.getAmount(); } /// @notice Gets the stake owner for the specified operator address. /// @return Stake owner address. function ownerOf(address _operator) public view returns (address) { return operators[_operator].owner; } /// @notice Gets the beneficiary for the specified operator address. /// @return Beneficiary address. function beneficiaryOf(address _operator) public view returns (address payable) { return operators[_operator].beneficiary; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address) { return operators[_operator].authorizer; } } pragma solidity 0.5.17; library OperatorParams { // OperatorParams packs values that are commonly used together // into a single uint256 to reduce the cost functions // like querying eligibility. // // An OperatorParams uint256 contains: // - the operator's staked token amount (uint128) // - the operator's creation timestamp (uint64) // - the operator's undelegation timestamp (uint64) // // These are packed as [amount | createdAt | undelegatedAt] // // Staked KEEP is stored in an uint128, // which is sufficient because KEEP tokens have 18 decimals (2^60) // and there will be at most 10^9 KEEP in existence (2^30). // // Creation and undelegation times are stored in an uint64 each. // Thus uint64s would be sufficient for around 3*10^11 years. uint256 constant TIMESTAMP_WIDTH = 64; uint256 constant AMOUNT_WIDTH = 128; uint256 constant TIMESTAMP_MAX = (2**TIMESTAMP_WIDTH) - 1; uint256 constant AMOUNT_MAX = (2**AMOUNT_WIDTH) - 1; uint256 constant CREATION_SHIFT = TIMESTAMP_WIDTH; uint256 constant AMOUNT_SHIFT = 2 * TIMESTAMP_WIDTH; function pack( uint256 amount, uint256 createdAt, uint256 undelegatedAt ) internal pure returns (uint256) { // Check for staked amount overflow. // We shouldn't actually ever need this. require( amount <= AMOUNT_MAX, "uint128 overflow" ); // Bitwise OR the timestamps together. // The resulting number is equal or greater than either, // and tells if we have a bit set outside the 64 available bits. require( (createdAt | undelegatedAt) <= TIMESTAMP_MAX, "uint64 overflow" ); return (amount << AMOUNT_SHIFT | createdAt << CREATION_SHIFT | undelegatedAt); } function unpack(uint256 packedParams) internal pure returns ( uint256 amount, uint256 createdAt, uint256 undelegatedAt ) { amount = getAmount(packedParams); createdAt = getCreationTimestamp(packedParams); undelegatedAt = getUndelegationTimestamp(packedParams); } function getAmount(uint256 packedParams) internal pure returns (uint256) { return (packedParams >> AMOUNT_SHIFT) & AMOUNT_MAX; } function setAmount( uint256 packedParams, uint256 amount ) internal pure returns (uint256) { return pack( amount, getCreationTimestamp(packedParams), getUndelegationTimestamp(packedParams) ); } function getCreationTimestamp(uint256 packedParams) internal pure returns (uint256) { return (packedParams >> CREATION_SHIFT) & TIMESTAMP_MAX; } function setCreationTimestamp( uint256 packedParams, uint256 creationTimestamp ) internal pure returns (uint256) { return pack( getAmount(packedParams), creationTimestamp, getUndelegationTimestamp(packedParams) ); } function getUndelegationTimestamp(uint256 packedParams) internal pure returns (uint256) { return packedParams & TIMESTAMP_MAX; } function setUndelegationTimestamp( uint256 packedParams, uint256 undelegationTimestamp ) internal pure returns (uint256) { return pack( getAmount(packedParams), getCreationTimestamp(packedParams), undelegationTimestamp ); } function setAmountAndCreationTimestamp( uint256 packedParams, uint256 amount, uint256 creationTimestamp ) internal pure returns (uint256) { return pack( amount, creationTimestamp, getUndelegationTimestamp(packedParams) ); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @notice MinimumStakeSchedule defines the minimum stake parametrization and /// schedule. It starts with a minimum stake of 100k KEEP. Over the following /// 2 years, the minimum stake is lowered periodically using a uniform stepwise /// function, eventually ending at 10k. library MinimumStakeSchedule { using SafeMath for uint256; // 2 years in seconds (seconds per day * days in a year * years) uint256 public constant schedule = 86400 * 365 * 2; uint256 public constant steps = 10; uint256 public constant base = 10000 * 1e18; /// @notice Returns the current value of the minimum stake. The minimum /// stake is lowered periodically over the course of 2 years since the time /// of the shedule start and eventually ends at 10k KEEP. function current(uint256 scheduleStart) internal view returns (uint256) { if (now < scheduleStart.add(schedule)) { uint256 currentStep = steps.mul(now.sub(scheduleStart)).div(schedule); return base.mul(steps.sub(currentStep)); } return base; } } pragma solidity 0.5.17; import "../../TokenGrant.sol"; import "../../TokenStakingEscrow.sol"; import "../..//utils/BytesLib.sol"; import "../RolesLookup.sol"; /// @notice TokenStaking contract library allowing to capture the details of /// delegated grants and offering functions allowing to check grantee /// authentication for stake delegation management. library GrantStaking { using BytesLib for bytes; using RolesLookup for address payable; /// @dev Grant ID is flagged with the most significant bit set, to /// distinguish the grant ID `0` from default (null) value. The flag is /// toggled with bitwise XOR (`^`) which keeps all other bits intact but /// flips the flag bit. The flag should be set before writing to /// `operatorToGrant`, and unset after reading from `operatorToGrant` /// before using the value. uint256 constant GRANT_ID_FLAG = 1 << 255; struct Storage { /// @dev Do not read or write this mapping directly; please use /// `hasGrantDelegated`, `setGrantForOperator`, and `getGrantForOperator` /// instead. mapping (address => uint256) _operatorToGrant; } /// @notice Tries to capture delegation data if the pending delegation has /// been created from a grant. There are only two possibilities and they /// need to be handled differently: delegation comes from the TokenGrant /// contract or delegation comes from TokenStakingEscrow. In those two cases /// grant ID has to be captured in a different way. /// @dev In case of a delegation from the escrow, it is expected that grant /// ID is passed in extraData bytes array. When the delegation comes from /// the TokenGrant contract, delegation data are obtained directly from that /// contract using `tryCapturingGrantId` function. /// @param tokenGrant KEEP token grant contract reference. /// @param escrow TokenStakingEscrow contract address. /// @param from The owner of the tokens who approved them to transfer. /// @param operator The operator tokens are delegated to. /// @param extraData Data for stake delegation, as passed to /// `receiveApproval` of `TokenStaking`. function tryCapturingDelegationData( Storage storage self, TokenGrant tokenGrant, address escrow, address from, address operator, bytes memory extraData ) public returns (bool, uint256) { if (from == escrow) { require(extraData.length == 92, "Corrupted delegation data from escrow"); uint256 grantId = extraData.toUint(60); setGrantForOperator(self, operator, grantId); return (true, grantId); } else { return tryCapturingGrantId(self, tokenGrant, operator); } } /// @notice Checks if the delegation for the given operator has been created /// from a grant defined in the passed token grant contract and if so, /// captures the grant ID for that delegation. /// Grant ID can be later retrieved based on the operator address and used /// to authenticate grantee or to fetch the information about grant /// unlocking schedule for escrow. /// @param tokenGrant KEEP token grant contract reference. /// @param operator The operator tokens are delegated to. function tryCapturingGrantId( Storage storage self, TokenGrant tokenGrant, address operator ) internal returns (bool, uint256) { (bool success, bytes memory data) = address(tokenGrant).call( abi.encodeWithSignature("getGrantStakeDetails(address)", operator) ); if (success) { (uint256 grantId,,address grantStakingContract) = abi.decode( data, (uint256, uint256, address) ); // Double-check if the delegation in TokenGrant has been defined // for this staking contract. If not, it means it's an old // delegation and the current one does not come from a grant. // The scenario covered here is: // - grantee delegated to operator A from a TokenGrant using another // staking contract, // - someone delegates to operator A using liquid tokens and this // staking contract. // Without this check, we'd consider the second delegation as coming // from a grant. if (address(this) != grantStakingContract) { return (false, 0); } setGrantForOperator(self, operator, grantId); return (true, grantId); } return (false, 0); } /// @notice Returns true if the given operator operates on stake delegated /// from a grant. false is returned otherwise. /// @param operator The operator to which tokens from a grant are /// potentially delegated to. function hasGrantDelegated( Storage storage self, address operator ) public view returns (bool) { return self._operatorToGrant[operator] != 0; } /// @notice Associates operator with the provided grant ID. It means that /// the given operator delegates on stake from the grant with this ID. /// @param operator The operator tokens are delegate to. /// @param grantId Identifier of a grant from which the tokens are delegated /// to. function setGrantForOperator( Storage storage self, address operator, uint256 grantId ) public { self._operatorToGrant[operator] = grantId ^ GRANT_ID_FLAG; } /// @notice Returns grant ID for the provided operator. If the operator /// does not operate on stake delegated from a grant, function reverts. /// @dev To avoid reverting in case the grant ID for the operator does not /// exist, consider calling hasGrantDelegated before. /// @param operator The operator tokens are delegate to. function getGrantForOperator( Storage storage self, address operator ) public view returns (uint256) { uint256 grantId = self._operatorToGrant[operator]; require (grantId != 0, "No grant for the operator"); return grantId ^ GRANT_ID_FLAG; } /// @notice Returns true if msg.sender is grantee eligible to trigger stake /// undelegation for this operator. Function checks both standard grantee /// and managed grantee case. /// @param operator The operator tokens are delegated to. /// @param tokenGrant KEEP token grant contract reference. function canUndelegate( Storage storage self, address operator, TokenGrant tokenGrant ) public returns (bool) { // First of all, we need to see if the operator has grant delegated. // If not, we don't need to bother about checking grantee or // managed grantee and we just return false. if (!hasGrantDelegated(self, operator)) { return false; } uint256 grantId = getGrantForOperator(self, operator); (,,,,uint256 revokedAt, address grantee) = tokenGrant.getGrant(grantId); // Is msg.sender grantee of a standard grant? if (msg.sender == grantee) { return true; } // If not, we need to dig deeper and see if we are dealing with // a grantee from a managed grant. if ((msg.sender).isManagedGranteeForGrant(grantId, tokenGrant)) { return true; } // There is only one possibility left - grant has been revoked and // grant manager wants to take back delegated tokens. if (revokedAt == 0) { return false; } (address grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); return msg.sender == grantManager; } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./KeepToken.sol"; import "./utils/BytesLib.sol"; import "./TokenGrant.sol"; import "./ManagedGrant.sol"; import "./TokenSender.sol"; /// @title TokenStakingEscrow /// @notice Escrow lets the staking contract to deposit undelegated, granted /// tokens and either withdraw them based on the grant unlocking schedule or /// re-delegate them to another operator. /// @dev The owner of TokenStakingEscrow is TokenStaking contract and only owner /// can deposit. This contract works with an assumption that operator is unique /// in the scope of `TokenStaking`, that is, no more than one delegation in the /// `TokenStaking` can be done do the given operator ever. Even if the previous /// delegation ended, operator address cannot be reused. contract TokenStakingEscrow is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; using BytesLib for bytes; using UnlockingSchedule for uint256; event Deposited( address indexed operator, uint256 indexed grantId, uint256 amount ); event DepositRedelegated( address indexed previousOperator, address indexed newOperator, uint256 indexed grantId, uint256 amount ); event DepositWithdrawn( address indexed operator, address indexed grantee, uint256 amount ); event RevokedDepositWithdrawn( address indexed operator, address indexed grantManager, uint256 amount ); event EscrowAuthorized( address indexed grantManager, address escrow ); IERC20 public keepToken; TokenGrant public tokenGrant; struct Deposit { uint256 grantId; uint256 amount; uint256 withdrawn; uint256 redelegated; } // operator address -> KEEP deposit mapping(address => Deposit) internal deposits; // Other escrows authorized by grant manager. Grantee may request to migrate // tokens to another authorized escrow. // grant manager -> escrow -> authorized? mapping(address => mapping (address => bool)) internal authorizedEscrows; constructor( KeepToken _keepToken, TokenGrant _tokenGrant ) public { keepToken = _keepToken; tokenGrant = _tokenGrant; } /// @notice receiveApproval accepts deposits from staking contract and /// stores them in the escrow by the operator address from which they were /// undelegated. Function expects operator address and grant identifier to /// be passed as ABI-encoded information in extraData. Grant with the given /// identifier has to exist. /// @param from Address depositing tokens - it has to be the address of /// TokenStaking contract owning TokenStakingEscrow. /// @param value The amount of KEEP tokens deposited. /// @param token The address of KEEP token contract. /// @param extraData ABI-encoded data containing operator address (32 bytes) /// and grant ID (32 bytes). function receiveApproval( address from, uint256 value, address token, bytes memory extraData ) public { require(IERC20(token) == keepToken, "Not a KEEP token"); require(msg.sender == token, "KEEP token is not the sender"); require(extraData.length == 64, "Unexpected data length"); (address operator, uint256 grantId) = abi.decode( extraData, (address, uint256) ); receiveDeposit(from, value, operator, grantId); } /// @notice Redelegates deposit or part of the deposit to another operator. /// Uses the same staking contract as the original delegation. /// @param previousOperator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @dev Only grantee is allowed to call this function. For managed grant, /// caller has to be the managed grantee. /// @param amount Amount of tokens to delegate. /// @param extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function redelegate( address previousOperator, uint256 amount, bytes memory extraData ) public { require(extraData.length == 60, "Corrupted delegation data"); Deposit memory deposit = deposits[previousOperator]; uint256 grantId = deposit.grantId; address newOperator = extraData.toAddress(20); require(isGrantee(msg.sender, grantId), "Not authorized"); require(getAmountRevoked(grantId) == 0, "Grant revoked"); require( availableAmount(previousOperator) >= amount, "Insufficient balance" ); require( !hasDeposit(newOperator), "Redelegating to previously used operator is not allowed" ); deposits[previousOperator].redelegated = deposit.redelegated.add(amount); TokenSender(address(keepToken)).approveAndCall( owner(), // TokenStaking contract associated with the escrow amount, abi.encodePacked(extraData, grantId) ); emit DepositRedelegated( previousOperator, newOperator, grantId, amount ); } /// @notice Returns true if there is a deposit for the given operator in /// the escrow. Otherwise, returns false. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function hasDeposit(address operator) public view returns (bool) { return depositedAmount(operator) > 0; } /// @notice Returns the currently available amount deposited in the escrow /// that may or may not be currently withdrawable. The available amount /// is the amount initially deposited minus the amount withdrawn and /// redelegated so far from that deposit. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function availableAmount(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; return deposit.amount.sub(deposit.withdrawn).sub(deposit.redelegated); } /// @notice Returns the total amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositedAmount(address operator) public view returns (uint256) { return deposits[operator].amount; } /// @notice Returns grant ID for the amount deposited in the escrow after /// undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositGrantId(address operator) public view returns (uint256) { return deposits[operator].grantId; } /// @notice Returns the amount withdrawn so far from the value deposited /// in the escrow contract after undelegating it from the provided operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositWithdrawnAmount(address operator) public view returns (uint256) { return deposits[operator].withdrawn; } /// @notice Returns the total amount redelegated so far from the value /// deposited in the escrow contract after undelegating it from the provided /// operator. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function depositRedelegatedAmount(address operator) public view returns (uint256) { return deposits[operator].redelegated; } /// @notice Returns the currently withdrawable amount that was previously /// deposited in the escrow after undelegating it from the provided operator. /// Tokens are unlocked based on their grant unlocking schedule. /// Function returns 0 for non-existing deposits and revoked grants if they /// have been revoked before they fully unlocked. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawable(address operator) public view returns (uint256) { Deposit memory deposit = deposits[operator]; // Staked tokens can be only withdrawn by grantee for non-revoked grant // assuming that grant has not fully unlocked before it's been // revoked. // // It is not possible for the escrow to determine the number of tokens // it should return to the grantee of a revoked grant given different // possible staking contracts and staking policies. // // If the entire grant unlocked before it's been reverted, escrow // lets to withdraw the entire deposited amount. if (getAmountRevoked(deposit.grantId) == 0) { ( uint256 duration, uint256 start, uint256 cliff ) = getUnlockingSchedule(deposit.grantId); uint256 unlocked = now.getUnlockedAmount( deposit.amount, duration, start, cliff ); if (deposit.withdrawn.add(deposit.redelegated) < unlocked) { return unlocked.sub(deposit.withdrawn).sub(deposit.redelegated); } } return 0; } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. Important: this function can not be /// called for a `ManagedGrant` grantee. This may lead to locking tokens. /// For `ManagedGrant`, please use `withdrawToManagedGrantee` instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdraw(address operator) public { Deposit memory deposit = deposits[operator]; address grantee = getGrantee(deposit.grantId); // Make sure this function is not called for a managed grant. // If called for a managed grant, tokens could be locked there. // Better be safe than sorry. (bool success, ) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); require(!success, "Can not be called for managed grant"); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Withdraws currently unlocked tokens deposited in the escrow /// after undelegating them from the provided operator. Only grantee or /// operator can call this function. This function works only for /// `ManagedGrant` grantees. For a standard grant, please use `withdraw` /// instead. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawToManagedGrantee(address operator) public { Deposit memory deposit = deposits[operator]; address managedGrant = getGrantee(deposit.grantId); address grantee = getManagedGrantee(managedGrant); require( msg.sender == grantee || msg.sender == operator, "Only grantee or operator can withdraw" ); withdraw(deposit, operator, grantee); } /// @notice Migrates all available tokens to another authorized escrow. /// Can be requested only by grantee. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. /// @param receivingEscrow Escrow to which tokens should be migrated. /// @dev The receiving escrow needs to accept deposits from this escrow, at /// least for the period of migration. function migrate( address operator, address receivingEscrow ) public { Deposit memory deposit = deposits[operator]; require(isGrantee(msg.sender, deposit.grantId), "Not authorized"); address grantManager = getGrantManager(deposit.grantId); require( authorizedEscrows[grantManager][receivingEscrow], "Escrow not authorized" ); uint256 amountLeft = availableAmount(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amountLeft); TokenSender(address(keepToken)).approveAndCall( receivingEscrow, amountLeft, abi.encode(operator, deposit.grantId) ); } /// @notice Withdraws the entire amount that is still deposited in the /// escrow in case the grant has been revoked. Anyone can call this function /// and the entire amount is transferred back to the grant manager. /// @param operator Address of the operator from the undelegated/canceled /// delegation from which tokens were deposited. function withdrawRevoked(address operator) public { Deposit memory deposit = deposits[operator]; require( getAmountRevoked(deposit.grantId) > 0, "No revoked tokens to withdraw" ); address grantManager = getGrantManager(deposit.grantId); withdrawRevoked(deposit, operator, grantManager); } /// @notice Used by grant manager to authorize another escrows for // funds migration. function authorizeEscrow(address anotherEscrow) public { require( anotherEscrow != address(0x0), "Escrow address can't be zero" ); authorizedEscrows[msg.sender][anotherEscrow] = true; emit EscrowAuthorized(msg.sender, anotherEscrow); } /// @notice Resolves the final grantee of ManagedGrant contract. If the /// provided address is not a ManagedGrant contract, function reverts. /// @param managedGrant Address of the managed grant contract. function getManagedGrantee( address managedGrant ) public view returns(address) { ManagedGrant grant = ManagedGrant(managedGrant); return grant.grantee(); } function receiveDeposit( address from, uint256 value, address operator, uint256 grantId ) internal { // This contract works with an assumption that operator is unique. // This is fine as long as the staking contract works with the same // assumption so we are limiting deposits to the staking contract only. require(from == owner(), "Only owner can deposit"); require( getAmountGranted(grantId) > 0, "Grant with this ID does not exist" ); require( !hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); keepToken.safeTransferFrom(from, address(this), value); deposits[operator] = Deposit(grantId, value, 0, 0); emit Deposited(operator, grantId, value); } function isGrantee( address maybeGrantee, uint256 grantId ) internal returns (bool) { // Let's check the simplest case first - standard grantee. // If the given address is set as a grantee for grant with the given ID, // we return true. address grantee = getGrantee(grantId); if (maybeGrantee == grantee) { return true; } // If the given address is not a standard grantee, there is still // a chance that address is a managed grantee. We are calling // getManagedGrantee that will cast the grantee to ManagedGrant and try // to call getGrantee() function. If this call returns non-zero address, // it means we are dealing with a ManagedGrant. (, bytes memory result) = address(this).call( abi.encodeWithSignature("getManagedGrantee(address)", grantee) ); if (result.length == 0) { return false; } // At this point we know we are dealing with a ManagedGrant, so the last // thing we need to check is whether the managed grantee of that grant // is the grantee address passed as a parameter. address managedGrantee = abi.decode(result, (address)); return maybeGrantee == managedGrantee; } function withdraw( Deposit memory deposit, address operator, address grantee ) internal { uint256 amount = withdrawable(operator); deposits[operator].withdrawn = deposit.withdrawn.add(amount); keepToken.safeTransfer(grantee, amount); emit DepositWithdrawn(operator, grantee, amount); } function withdrawRevoked( Deposit memory deposit, address operator, address grantManager ) internal { uint256 amount = availableAmount(operator); deposits[operator].withdrawn = amount; keepToken.safeTransfer(grantManager, amount); emit RevokedDepositWithdrawn(operator, grantManager, amount); } function getAmountGranted(uint256 grantId) internal view returns ( uint256 amountGranted ) { (amountGranted,,,,,) = tokenGrant.getGrant(grantId); } function getAmountRevoked(uint256 grantId) internal view returns ( uint256 amountRevoked ) { (,,,amountRevoked,,) = tokenGrant.getGrant(grantId); } function getUnlockingSchedule(uint256 grantId) internal view returns ( uint256 duration, uint256 start, uint256 cliff ) { (,duration,start,cliff,) = tokenGrant.getGrantUnlockingSchedule(grantId); } function getGrantee(uint256 grantId) internal view returns ( address grantee ) { (,,,,,grantee) = tokenGrant.getGrant(grantId); } function getGrantManager(uint256 grantId) internal view returns ( address grantManager ) { (grantManager,,,,) = tokenGrant.getGrantUnlockingSchedule(grantId); } } pragma solidity ^0.5.4; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "./TokenGrant.sol"; /// @title ManagedGrant /// @notice A managed grant acts as the grantee towards the token grant contract, /// proxying instructions from the actual grantee. /// The address used by the actual grantee /// to issue instructions and withdraw tokens /// can be reassigned with the consent of the grant manager. contract ManagedGrant { using SafeERC20 for ERC20Burnable; ERC20Burnable public token; TokenGrant public tokenGrant; address public grantManager; uint256 public grantId; address public grantee; address public requestedNewGrantee; event GranteeReassignmentRequested( address newGrantee ); event GranteeReassignmentConfirmed( address oldGrantee, address newGrantee ); event GranteeReassignmentCancelled( address cancelledRequestedGrantee ); event GranteeReassignmentChanged( address previouslyRequestedGrantee, address newRequestedGrantee ); event TokensWithdrawn( address destination, uint256 amount ); constructor( address _tokenAddress, address _tokenGrant, address _grantManager, uint256 _grantId, address _grantee ) public { token = ERC20Burnable(_tokenAddress); tokenGrant = TokenGrant(_tokenGrant); grantManager = _grantManager; grantId = _grantId; grantee = _grantee; } /// @notice Request a reassignment of the grantee address. /// Can only be called by the grantee. /// @param _newGrantee The requested new grantee. function requestGranteeReassignment(address _newGrantee) public onlyGrantee noRequestedReassignment { _setRequestedNewGrantee(_newGrantee); emit GranteeReassignmentRequested(_newGrantee); } /// @notice Cancel a pending grantee reassignment request. /// Can only be called by the grantee. function cancelReassignmentRequest() public onlyGrantee withRequestedReassignment { address cancelledGrantee = requestedNewGrantee; requestedNewGrantee = address(0); emit GranteeReassignmentCancelled(cancelledGrantee); } /// @notice Change a pending reassignment request to a different grantee. /// Can only be called by the grantee. /// @param _newGrantee The address of the new requested grantee. function changeReassignmentRequest(address _newGrantee) public onlyGrantee withRequestedReassignment { address previouslyRequestedGrantee = requestedNewGrantee; require( previouslyRequestedGrantee != _newGrantee, "Unchanged reassignment request" ); _setRequestedNewGrantee(_newGrantee); emit GranteeReassignmentChanged(previouslyRequestedGrantee, _newGrantee); } /// @notice Confirm a grantee reassignment request and set the new grantee as the grantee. /// Can only be called by the grant manager. /// @param _newGrantee The address of the new grantee. /// Must match the currently requested new grantee. function confirmGranteeReassignment(address _newGrantee) public onlyManager withRequestedReassignment { address oldGrantee = grantee; require( requestedNewGrantee == _newGrantee, "Reassignment address mismatch" ); grantee = requestedNewGrantee; requestedNewGrantee = address(0); emit GranteeReassignmentConfirmed(oldGrantee, _newGrantee); } /// @notice Withdraw all unlocked tokens from the grant. function withdraw() public onlyGrantee { require( requestedNewGrantee == address(0), "Can not withdraw with pending reassignment" ); tokenGrant.withdraw(grantId); uint256 amount = token.balanceOf(address(this)); token.safeTransfer(grantee, amount); emit TokensWithdrawn(grantee, amount); } /// @notice Stake tokens from the grant. /// @param _stakingContract The contract to stake the tokens on. /// @param _amount The amount of tokens to stake. /// @param _extraData Data for the stake delegation. /// This byte array must have the following values concatenated: /// beneficiary address (20 bytes) /// operator address (20 bytes) /// authorizer address (20 bytes) function stake( address _stakingContract, uint256 _amount, bytes memory _extraData ) public onlyGrantee { tokenGrant.stake(grantId, _stakingContract, _amount, _extraData); } /// @notice Cancel delegating tokens to the given operator. function cancelStake(address _operator) public onlyGranteeOr(_operator) { tokenGrant.cancelStake(_operator); } /// @notice Begin undelegating tokens from the given operator. function undelegate(address _operator) public onlyGranteeOr(_operator) { tokenGrant.undelegate(_operator); } /// @notice Recover tokens previously staked and delegated to the operator. function recoverStake(address _operator) public { tokenGrant.recoverStake(_operator); } function _setRequestedNewGrantee(address _newGrantee) internal { require(_newGrantee != address(0), "Invalid new grantee address"); require(_newGrantee != grantee, "New grantee same as current grantee"); requestedNewGrantee = _newGrantee; } modifier withRequestedReassignment { require( requestedNewGrantee != address(0), "No reassignment requested" ); _; } modifier noRequestedReassignment { require( requestedNewGrantee == address(0), "Reassignment already requested" ); _; } modifier onlyGrantee { require( msg.sender == grantee, "Only grantee may perform this action" ); _; } modifier onlyGranteeOr(address _operator) { require( msg.sender == grantee || msg.sender == _operator, "Only grantee or operator may perform this action" ); _; } modifier onlyManager { require( msg.sender == grantManager, "Only grantManager may perform this action" ); _; } } pragma solidity 0.5.17; /// @dev Interface of sender contract for approveAndCall pattern. interface TokenSender { function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external; } pragma solidity 0.5.17; import "../utils/AddressArrayUtils.sol"; import "../StakeDelegatable.sol"; import "../TokenGrant.sol"; import "../ManagedGrant.sol"; /// @title Roles Lookup /// @notice Library facilitating lookup of roles in stake delegation setup. library RolesLookup { using AddressArrayUtils for address[]; /// @notice Returns true if the tokenOwner delegated tokens to operator /// using the provided stakeDelegatable contract. Othwerwise, returns false. /// This function works only for the case when tokenOwner own those tokens /// and those are not tokens from a grant. function isTokenOwnerForOperator( address tokenOwner, address operator, StakeDelegatable stakeDelegatable ) internal view returns (bool) { return stakeDelegatable.ownerOf(operator) == tokenOwner; } /// @notice Returns true if the grantee delegated tokens to operator /// with the provided tokenGrant contract. Otherwise, returns false. /// This function works only for the case when tokens were generated from /// a non-managed grant, that is, the grantee is a non-contract address to /// which the delegated tokens were granted. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isGranteeForOperator( address grantee, address operator, TokenGrant tokenGrant ) internal view returns (bool) { address[] memory operators = tokenGrant.getGranteeOperators(grantee); return operators.contains(operator); } /// @notice Returns true if the grantee from the given managed grant contract /// delegated tokens to operator with the provided tokenGrant contract. /// Otherwise, returns false. In case the grantee declared by the managed /// grant contract does not match the provided grantee, function reverts. /// This function works only for cases when grantee, from TokenGrant's /// perspective, is a smart contract exposing grantee() function returning /// the final grantee. One possibility is the ManagedGrant contract. /// @dev This function does not validate the staking reltionship on /// a particular staking contract. It only checks whether the grantee /// staked at least one time with the given operator. If you are interested /// in a particular token staking contract, you need to perform additional /// check. function isManagedGranteeForOperator( address grantee, address operator, address managedGrantContract, TokenGrant tokenGrant ) internal view returns (bool) { require( ManagedGrant(managedGrantContract).grantee() == grantee, "Not a grantee of the provided contract" ); address[] memory operators = tokenGrant.getGranteeOperators( managedGrantContract ); return operators.contains(operator); } /// @notice Returns true if grant with the given ID has been created with /// managed grant pointing currently to the grantee passed as a parameter. /// @dev The function does not revert if grant has not been created with /// a managed grantee. This function is not a view because it uses low-level /// call to check if the grant has been created with a managed grant. /// It does not however modify any state. function isManagedGranteeForGrant( address grantee, uint256 grantId, TokenGrant tokenGrant ) internal returns (bool) { (,,,,, address managedGrant) = tokenGrant.getGrant(grantId); (, bytes memory result) = managedGrant.call( abi.encodeWithSignature("grantee()") ); if (result.length == 0) { return false; } address managedGrantee = abi.decode(result, (address)); return grantee == managedGrantee; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { AuthorityVerifier } from "../../Authorizations.sol"; import "./LockUtils.sol"; library Locks { using SafeMath for uint256; using LockUtils for LockUtils.LockSet; event StakeLocked(address indexed operator, address lockCreator, uint256 until); event LockReleased(address indexed operator, address lockCreator); event ExpiredLockReleased(address indexed operator, address lockCreator); uint256 public constant maximumLockDuration = 86400 * 200; // 200 days in seconds struct Storage { // Locks placed on the operator. // `operatorLocks[operator]` returns all locks placed on the operator. // Each authorized operator contract can place one lock on an operator. mapping(address => LockUtils.LockSet) operatorLocks; } function lockStake( Storage storage self, address operator, uint256 duration ) public { require(duration <= maximumLockDuration, "Lock duration too long"); self.operatorLocks[operator].setLock( msg.sender, uint96(block.timestamp.add(duration)) ); emit StakeLocked(operator, msg.sender, block.timestamp.add(duration)); } function releaseLock( Storage storage self, address operator ) public { self.operatorLocks[operator].releaseLock(msg.sender); emit LockReleased(operator, msg.sender); } function releaseExpiredLock( Storage storage self, address operator, address operatorContract, address authorityVerifier ) public { LockUtils.LockSet storage locks = self.operatorLocks[operator]; require( locks.contains(operatorContract), "No matching lock present" ); bool expired = block.timestamp >= locks.getLockTime(operatorContract); bool disabled = !AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(operatorContract); require( expired || disabled, "Lock still active and valid" ); locks.releaseLock(operatorContract); emit ExpiredLockReleased(operator, operatorContract); } /// @dev AuthorityVerifier is a trusted implementation and not a third-party, /// external contract. AuthorityVerifier never reverts on the check and /// has a reasonable gas consumption. function isStakeLocked( Storage storage self, address operator, address authorityVerifier ) public view returns (bool) { LockUtils.Lock[] storage _locks = self.operatorLocks[operator].locks; LockUtils.Lock memory lock; for (uint i = 0; i < _locks.length; i++) { lock = _locks[i]; if (block.timestamp < lock.expiresAt) { if ( AuthorityVerifier(authorityVerifier) .isApprovedOperatorContract(lock.creator) ) { return true; } } } return false; } function isStakeReleased( Storage storage self, address operator, address operatorContract ) public view returns (bool) { LockUtils.LockSet storage locks = self.operatorLocks[operator]; // `getLockTime` returns 0 if the lock doesn't exist, // thus we don't need to check for its presence separately. return block.timestamp >= locks.getLockTime(operatorContract); } function getLocks( Storage storage self, address operator ) public view returns (address[] memory creators, uint256[] memory expirations) { uint256 lockCount = self.operatorLocks[operator].locks.length; creators = new address[](lockCount); expirations = new uint256[](lockCount); LockUtils.Lock memory lock; for (uint i = 0; i < lockCount; i++) { lock = self.operatorLocks[operator].locks[i]; creators[i] = lock.creator; expirations[i] = lock.expiresAt; } } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./KeepRegistry.sol"; /// @title AuthorityDelegator /// @notice An operator contract can delegate authority to other operator /// contracts by implementing the AuthorityDelegator interface. /// /// To delegate authority, /// the recipient of delegated authority must call `claimDelegatedAuthority`, /// specifying the contract it wants delegated authority from. /// The staking contract calls `delegator.__isRecognized(recipient)` /// and if the call returns `true`, /// the named delegator contract is set as the recipient's authority delegator. /// Any future checks of registry approval or per-operator authorization /// will transparently mirror the delegator's status. /// /// Authority can be delegated recursively; /// an operator contract receiving delegated authority /// can recognize other operator contracts as recipients of its authority. interface AuthorityDelegator { function __isRecognized(address delegatedAuthorityRecipient) external returns (bool); } /// @title AuthorityVerifier /// @notice An operator contract can delegate authority to other operator /// contracts. Entry in the registry is not updated and source contract remains /// listed there as authorized. This interface is a verifier that support verification /// of contract authorization in case of authority delegation from the source contract. interface AuthorityVerifier { /// @notice Returns true if the given operator contract has been approved /// for use. The function never reverts. function isApprovedOperatorContract(address _operatorContract) external view returns (bool); } contract Authorizations is AuthorityVerifier { // Authorized operator contracts. mapping(address => mapping (address => bool)) internal authorizations; // Granters of delegated authority to operator contracts. // E.g. keep factories granting delegated authority to keeps. // `delegatedAuthority[keep] = factory` mapping(address => address) internal delegatedAuthority; // Registry contract with a list of approved operator contracts and upgraders. KeepRegistry internal registry; modifier onlyApprovedOperatorContract(address operatorContract) { require( isApprovedOperatorContract(operatorContract), "Operator contract unapproved" ); _; } constructor(KeepRegistry _registry) public { registry = _registry; } /// @notice Gets the authorizer for the specified operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address); /// @notice Authorizes operator contract to access staked token balance of /// the provided operator. Can only be executed by stake operator authorizer. /// Contracts using delegated authority /// cannot be authorized with `authorizeOperatorContract`. /// Instead, authorize `getAuthoritySource(_operatorContract)`. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function authorizeOperatorContract(address _operator, address _operatorContract) public onlyApprovedOperatorContract(_operatorContract) { require( authorizerOf(_operator) == msg.sender, "Not operator authorizer" ); require( getAuthoritySource(_operatorContract) == _operatorContract, "Delegated authority used" ); authorizations[_operatorContract][_operator] = true; } /// @notice Checks if operator contract has access to the staked token balance of /// the provided operator. /// @param _operator address of stake operator. /// @param _operatorContract address of operator contract. function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool) { return authorizations[getAuthoritySource(_operatorContract)][_operator]; } /// @notice Grant the sender the same authority as `delegatedAuthoritySource` /// @dev If `delegatedAuthoritySource` is an approved operator contract /// and recognizes the claimant, this relationship will be recorded in /// `delegatedAuthority`. Later, the claimant can slash, seize, place locks etc. /// on operators that have authorized the `delegatedAuthoritySource`. /// If the `delegatedAuthoritySource` is disabled with the panic button, /// any recipients of delegated authority from it will also be disabled. function claimDelegatedAuthority( address delegatedAuthoritySource ) public onlyApprovedOperatorContract(delegatedAuthoritySource) { require( AuthorityDelegator(delegatedAuthoritySource).__isRecognized(msg.sender), "Unrecognized claimant" ); delegatedAuthority[msg.sender] = delegatedAuthoritySource; } /// @notice Checks if the operator contract is authorized in the registry. /// If the contract uses delegated authority it checks authorization of the /// source contract. /// @param _operatorContract address of operator contract. /// @return True if operator contract is approved, false if operator contract /// has not been approved or if it was disabled by the panic button. function isApprovedOperatorContract(address _operatorContract) public view returns (bool) { return registry.isApprovedOperatorContract( getAuthoritySource(_operatorContract) ); } /// @notice Get the source of the operator contract's authority. /// If the contract uses delegated authority, /// returns the original source of the delegated authority. /// If the contract doesn't use delegated authority, /// returns the contract itself. /// Authorize `getAuthoritySource(operatorContract)` /// to grant `operatorContract` the authority to penalize an operator. function getAuthoritySource( address operatorContract ) public view returns (address) { address delegatedAuthoritySource = delegatedAuthority[operatorContract]; if (delegatedAuthoritySource == address(0)) { return operatorContract; } return getAuthoritySource(delegatedAuthoritySource); } } pragma solidity 0.5.17; library LockUtils { struct Lock { address creator; uint96 expiresAt; } /// @notice The LockSet is like an array of unique `uint256`s, /// but additionally supports O(1) membership tests and removals. /// @dev Because the LockSet relies on a mapping, /// it can only be used in storage, not in memory. struct LockSet { // locks[positions[lock.creator] - 1] = lock Lock[] locks; mapping(address => uint256) positions; } /// @notice Check whether the LockSet `self` contains a lock by `creator` function contains(LockSet storage self, address creator) internal view returns (bool) { return (self.positions[creator] != 0); } function getLockTime(LockSet storage self, address creator) internal view returns (uint96) { uint256 positionPlusOne = self.positions[creator]; if (positionPlusOne == 0) { return 0; } return self.locks[positionPlusOne - 1].expiresAt; } /// @notice Set the lock of `creator` to `expiresAt`, /// overriding the current value if any. function setLock( LockSet storage self, address _creator, uint96 _expiresAt ) internal { uint256 positionPlusOne = self.positions[_creator]; Lock memory lock = Lock(_creator, _expiresAt); // No existing lock if (positionPlusOne == 0) { self.locks.push(lock); self.positions[_creator] = self.locks.length; // Existing lock present } else { self.locks[positionPlusOne - 1].expiresAt = _expiresAt; } } /// @notice Remove the lock of `creator`. /// If no lock present, do nothing. function releaseLock( LockSet storage self, address _creator ) internal { uint256 positionPlusOne = self.positions[_creator]; if (positionPlusOne != 0) { uint256 lockCount = self.locks.length; if (positionPlusOne != lockCount) { // Not the last lock, // so we need to move the last lock into the emptied position. Lock memory lastLock = self.locks[lockCount - 1]; self.locks[positionPlusOne - 1] = lastLock; self.positions[lastLock.creator] = positionPlusOne; } self.locks.length--; self.positions[_creator] = 0; } } /// @notice Return the locks of the LockSet `self`. function enumerate(LockSet storage self) internal view returns (Lock[] memory) { return self.locks; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../TokenStakingEscrow.sol"; import "../../utils/OperatorParams.sol"; /// @notice TokenStaking contract library allowing to perform two-step stake /// top-ups for existing delegations. /// Top-up is a two-step process: it is initiated with a declared top-up value /// and after waiting for at least the initialization period it can be /// committed. library TopUps { using SafeMath for uint256; using OperatorParams for uint256; event TopUpInitiated(address indexed operator, uint256 topUp); event TopUpCompleted(address indexed operator, uint256 newAmount); struct TopUp { uint256 amount; uint256 createdAt; } struct Storage { // operator -> TopUp mapping(address => TopUp) topUps; } /// @notice Performs top-up in one step when stake is not yet initialized by /// adding the top-up amount to the stake and resetting stake initialization /// time counter. /// @dev This function should be called only for not yet initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. /// @return New value of parameters. It should be updated for the operator /// in the staking contract. function instantComplete( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public returns (uint256 newParams) { // Stake is not yet initialized so we don't need to check if the // operator is not undelegating - initializing and undelegating at the // same time is not possible. We do however, need to check whether the // operator has not canceled its previous stake for that operator, // depositing the stake it in the escrow. We do not want to allow // resurrecting operators with cancelled stake by top-ups. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); uint256 newAmount = operatorParams.getAmount().add(value); newParams = operatorParams.setAmountAndCreationTimestamp( newAmount, block.timestamp ); emit TopUpCompleted(operator, newAmount); } /// @notice Initiates top-up of the given value for tokens delegated to /// the provided operator. If there is an existing top-up still /// initializing, top-up values are summed up and initialization period /// is set to the current block timestamp. /// @dev This function should be called only for active operators with /// initialized stake. /// @param value Top-up value, the number of tokens added to the stake. /// @param operator Operator The operator with existing delegation to which /// the tokens should be added to. /// @param operatorParams Parameters of that operator, as stored in the /// staking contract. /// @param escrow Reference to TokenStakingEscrow contract. function initiate( Storage storage self, uint256 value, address operator, uint256 operatorParams, TokenStakingEscrow escrow ) public { // Stake is initialized, the operator is still active so we need // to check if it's not undelegating. require(!isUndelegating(operatorParams), "Stake undelegated"); // We also need to check if the stake for the operator is not already // in the escrow because it's been previously cancelled. require( !escrow.hasDeposit(operator), "Stake for the operator already deposited in the escrow" ); require(value > 0, "Top-up value must be greater than zero"); TopUp memory awaiting = self.topUps[operator]; self.topUps[operator] = TopUp(awaiting.amount.add(value), now); emit TopUpInitiated(operator, value); } /// @notice Commits the top-up if it passed the initialization period. /// Tokens are added to the stake once the top-up is committed. /// @param operator Operator The operator with a pending stake top-up. /// @param initializationPeriod Stake initialization period. function commit( Storage storage self, address operator, uint256 operatorParams, uint256 initializationPeriod ) public returns (uint256 newParams) { TopUp memory topUp = self.topUps[operator]; require(topUp.amount > 0, "No top up to commit"); require( now > topUp.createdAt.add(initializationPeriod), "Stake is initializing" ); uint256 newAmount = operatorParams.getAmount().add(topUp.amount); newParams = operatorParams.setAmount(newAmount); delete self.topUps[operator]; emit TopUpCompleted(operator, newAmount); } /// @notice Cancels pending, initiating top-up. If there is no initiating /// top-up for the operator, function does nothing. This function should be /// used when the stake is recovered to return tokens from a pending, /// initiating top-up. /// @param operator Operator The operator from which the stake is recovered. function cancel( Storage storage self, address operator ) public returns (uint256) { TopUp memory topUp = self.topUps[operator]; if (topUp.amount == 0) { return 0; } delete self.topUps[operator]; return topUp.amount; } /// @notice Returns true if the given operatorParams indicate that the /// operator is undelegating its stake or that it completed stake /// undelegation. /// @param operatorParams Parameters of the operator, as stored in the /// staking contract. function isUndelegating(uint256 operatorParams) internal view returns (bool) { uint256 undelegatedAt = operatorParams.getUndelegationTimestamp(); return (undelegatedAt != 0) && (block.timestamp > undelegatedAt); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library PercentUtils { using SafeMath for uint256; // Return `b`% of `a` // 200.percent(40) == 80 // Commutative, works both ways function percent(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(100); } // Return `a` as percentage of `b`: // 80.asPercentOf(200) == 40 function asPercentOf(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(100).div(b); } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./TokenStaking.sol"; import "./TokenSender.sol"; import "./utils/BytesLib.sol"; /// @dev Interface of sender contract for approveAndCall pattern. interface tokenSender { function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external; } contract TokenGrantStake { using SafeMath for uint256; using BytesLib for bytes; ERC20Burnable token; TokenStaking tokenStaking; address tokenGrant; // Address of the master grant contract. uint256 grantId; // ID of the grant for this stake. uint256 amount; // Amount of staked tokens. address operator; // Operator of the stake. constructor( address _tokenAddress, uint256 _grantId, address _tokenStaking ) public { require( _tokenAddress != address(0x0), "Token address can't be zero." ); require( _tokenStaking != address(0x0), "Staking contract address can't be zero." ); token = ERC20Burnable(_tokenAddress); tokenGrant = msg.sender; grantId = _grantId; tokenStaking = TokenStaking(_tokenStaking); } function stake( uint256 _amount, bytes memory _extraData ) public onlyGrant { amount = _amount; operator = _extraData.toAddress(20); tokenSender(address(token)).approveAndCall( address(tokenStaking), _amount, _extraData ); } function getGrantId() public view onlyGrant returns (uint256) { return grantId; } function getAmount() public view onlyGrant returns (uint256) { return amount; } function getStakingContract() public view onlyGrant returns (address) { return address(tokenStaking); } function getDetails() public view onlyGrant returns ( uint256 _grantId, uint256 _amount, address _tokenStaking ) { return ( grantId, amount, address(tokenStaking) ); } function cancelStake() public onlyGrant returns (uint256) { tokenStaking.cancelStake(operator); return returnTokens(); } function undelegate() public onlyGrant { tokenStaking.undelegate(operator); } function recoverStake() public onlyGrant returns (uint256) { tokenStaking.recoverStake(operator); return returnTokens(); } function returnTokens() internal returns (uint256) { uint256 returnedAmount = token.balanceOf(address(this)); amount -= returnedAmount; token.transfer(tokenGrant, returnedAmount); return returnedAmount; } modifier onlyGrant { require( msg.sender == tokenGrant, "For token grant contract only" ); _; } } pragma solidity 0.5.17; /// @title GrantStakingPolicy /// @notice A staking policy defines the function `getStakeableAmount` /// which calculates how many tokens may be staked from a token grant. contract GrantStakingPolicy { function getStakeableAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff, uint256 withdrawn) public view returns (uint256); } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; library UnlockingSchedule { using SafeMath for uint256; function getUnlockedAmount( uint256 _now, uint256 grantedAmount, uint256 duration, uint256 start, uint256 cliff ) internal pure returns (uint256) { bool cliffNotReached = _now < cliff; if (cliffNotReached) { return 0; } uint256 timeElapsed = _now.sub(start); bool unlockingPeriodFinished = timeElapsed >= duration; if (unlockingPeriodFinished) { return grantedAmount; } return grantedAmount.mul(timeElapsed).div(duration); } } pragma solidity 0.5.17; /* Verison pulled from https://github.com/summa-tx/bitcoin-spv/blob/2535e4edaeaac4b2b095903fce684ae1c05761bc/solidity/contracts/BytesLib.sol */ /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1), "Uint8 conversion out of bounds."); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } pragma solidity 0.5.17; /// @title KeepRegistry /// @notice Governance owned registry of approved contracts and roles. contract KeepRegistry { enum ContractStatus {New, Approved, Disabled} // Governance role is to enable recovery from key compromise by rekeying // other roles. Also, it can disable operator contract panic buttons // permanently. address public governance; // Registry Keeper maintains approved operator contracts. Each operator // contract must be approved before it can be authorized by a staker or // used by a service contract. address public registryKeeper; // Each operator contract has a Panic Button which can disable malicious // or malfunctioning contract that have been previously approved by the // Registry Keeper. // // New operator contract added to the registry has a default panic button // value assigned (defaultPanicButton). Panic button for each operator // contract can be later updated by Governance to individual value. // // It is possible to disable panic button for individual contract by // setting the panic button to zero address. In such case, operator contract // can not be disabled and is permanently approved in the registry. mapping(address => address) public panicButtons; // Default panic button for each new operator contract added to the // registry. Can be later updated for each contract. address public defaultPanicButton; // Each service contract has a Operator Contract Upgrader whose purpose // is to manage operator contracts for that specific service contract. // The Operator Contract Upgrader can add new operator contracts to the // service contract’s operator contract list, and deprecate old ones. mapping(address => address) public operatorContractUpgraders; // Operator contract may have a Service Contract Upgrader whose purpose is // to manage service contracts for that specific operator contract. // Service Contract Upgrader can add and remove service contracts // from the list of service contracts approved to work with the operator // contract. List of service contracts is maintained in the operator // contract and is optional - not every operator contract needs to have // a list of service contracts it wants to cooperate with. mapping(address => address) public serviceContractUpgraders; // The registry of operator contracts mapping(address => ContractStatus) public operatorContracts; event OperatorContractApproved(address operatorContract); event OperatorContractDisabled(address operatorContract); event GovernanceUpdated(address governance); event RegistryKeeperUpdated(address registryKeeper); event DefaultPanicButtonUpdated(address defaultPanicButton); event OperatorContractPanicButtonDisabled(address operatorContract); event OperatorContractPanicButtonUpdated( address operatorContract, address panicButton ); event OperatorContractUpgraderUpdated( address serviceContract, address upgrader ); event ServiceContractUpgraderUpdated( address operatorContract, address keeper ); modifier onlyGovernance() { require(governance == msg.sender, "Not authorized"); _; } modifier onlyRegistryKeeper() { require(registryKeeper == msg.sender, "Not authorized"); _; } modifier onlyPanicButton(address _operatorContract) { address panicButton = panicButtons[_operatorContract]; require(panicButton != address(0), "Panic button disabled"); require(panicButton == msg.sender, "Not authorized"); _; } modifier onlyForNewContract(address _operatorContract) { require( isNewOperatorContract(_operatorContract), "Not a new operator contract" ); _; } modifier onlyForApprovedContract(address _operatorContract) { require( isApprovedOperatorContract(_operatorContract), "Not an approved operator contract" ); _; } constructor() public { governance = msg.sender; registryKeeper = msg.sender; defaultPanicButton = msg.sender; } function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceUpdated(governance); } function setRegistryKeeper(address _registryKeeper) public onlyGovernance { registryKeeper = _registryKeeper; emit RegistryKeeperUpdated(registryKeeper); } function setDefaultPanicButton(address _panicButton) public onlyGovernance { defaultPanicButton = _panicButton; emit DefaultPanicButtonUpdated(defaultPanicButton); } function setOperatorContractPanicButton( address _operatorContract, address _panicButton ) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Disabled panic button cannot be updated" ); require( _panicButton != address(0), "Panic button must be non-zero address" ); panicButtons[_operatorContract] = _panicButton; emit OperatorContractPanicButtonUpdated( _operatorContract, _panicButton ); } function disableOperatorContractPanicButton(address _operatorContract) public onlyForApprovedContract(_operatorContract) onlyGovernance { require( panicButtons[_operatorContract] != address(0), "Panic button already disabled" ); panicButtons[_operatorContract] = address(0); emit OperatorContractPanicButtonDisabled(_operatorContract); } function setOperatorContractUpgrader( address _serviceContract, address _operatorContractUpgrader ) public onlyGovernance { operatorContractUpgraders[_serviceContract] = _operatorContractUpgrader; emit OperatorContractUpgraderUpdated( _serviceContract, _operatorContractUpgrader ); } function setServiceContractUpgrader( address _operatorContract, address _serviceContractUpgrader ) public onlyGovernance { serviceContractUpgraders[_operatorContract] = _serviceContractUpgrader; emit ServiceContractUpgraderUpdated( _operatorContract, _serviceContractUpgrader ); } function approveOperatorContract(address operatorContract) public onlyForNewContract(operatorContract) onlyRegistryKeeper { operatorContracts[operatorContract] = ContractStatus.Approved; panicButtons[operatorContract] = defaultPanicButton; emit OperatorContractApproved(operatorContract); } function disableOperatorContract(address operatorContract) public onlyForApprovedContract(operatorContract) onlyPanicButton(operatorContract) { operatorContracts[operatorContract] = ContractStatus.Disabled; emit OperatorContractDisabled(operatorContract); } function isNewOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.New; } function isApprovedOperatorContract(address operatorContract) public view returns (bool) { return operatorContracts[operatorContract] == ContractStatus.Approved; } function operatorContractUpgraderFor(address _serviceContract) public view returns (address) { return operatorContractUpgraders[_serviceContract]; } function serviceContractUpgraderFor(address _operatorContract) public view returns (address) { return serviceContractUpgraders[_operatorContract]; } } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./libraries/grant/UnlockingSchedule.sol"; import "./utils/BytesLib.sol"; import "./utils/AddressArrayUtils.sol"; import "./TokenStaking.sol"; import "./TokenGrantStake.sol"; import "./GrantStakingPolicy.sol"; /// @title TokenGrant /// @notice A token grant contract for a specified standard ERC20Burnable token. /// Has additional functionality to stake delegate/undelegate token grants. /// Tokens are granted to the grantee via unlocking scheme and can be /// withdrawn gradually based on the unlocking schedule cliff and unlocking duration. /// Optionally grant can be revoked by the token grant manager. contract TokenGrant { using SafeMath for uint256; using UnlockingSchedule for uint256; using SafeERC20 for ERC20Burnable; using BytesLib for bytes; using AddressArrayUtils for address[]; event TokenGrantCreated(uint256 id); event TokenGrantWithdrawn(uint256 indexed grantId, uint256 amount); event TokenGrantStaked(uint256 indexed grantId, uint256 amount, address operator); event TokenGrantRevoked(uint256 id); event StakingContractAuthorized(address indexed grantManager, address stakingContract); struct Grant { address grantManager; // Token grant manager. address grantee; // Address to which granted tokens are going to be withdrawn. uint256 revokedAt; // Timestamp at which grant was revoked by the grant manager. uint256 revokedAmount; // The number of tokens revoked from the grantee. uint256 revokedWithdrawn; // The number of tokens returned to the grant creator. bool revocable; // Whether grant manager can revoke the grant. uint256 amount; // Amount of tokens to be granted. uint256 duration; // Duration in seconds of the period in which the granted tokens will unlock. uint256 start; // Timestamp at which the linear unlocking schedule will start. uint256 cliff; // Timestamp before which no tokens will be unlocked. uint256 withdrawn; // Amount that was withdrawn to the grantee. uint256 staked; // Amount that was staked by the grantee. GrantStakingPolicy stakingPolicy; } uint256 public numGrants; ERC20Burnable public token; // Staking contracts authorized by the given grant manager. // grant manager -> staking contract -> authorized? mapping(address => mapping (address => bool)) internal stakingContracts; // Token grants. mapping(uint256 => Grant) public grants; // Token grants stakes. mapping(address => TokenGrantStake) public grantStakes; // Mapping of token grant IDs per particular address // involved in a grant as a grantee or as a grant manager. mapping(address => uint256[]) public grantIndices; // Token grants balances. Sum of all granted tokens to a grantee. // This includes granted tokens that are already unlocked and // available to be withdrawn to the grantee mapping(address => uint256) public balances; // Mapping of operator addresses per particular grantee address. mapping(address => address[]) public granteesToOperators; /// @notice Creates a token grant contract for a provided Standard ERC20Burnable token. /// @param _tokenAddress address of a token that will be linked to this contract. constructor(address _tokenAddress) public { require(_tokenAddress != address(0x0), "Token address can't be zero."); token = ERC20Burnable(_tokenAddress); } /// @notice Used by grant manager to authorize staking contract with the given /// address. function authorizeStakingContract(address _stakingContract) public { require( _stakingContract != address(0x0), "Staking contract address can't be zero" ); stakingContracts[msg.sender][_stakingContract] = true; emit StakingContractAuthorized(msg.sender, _stakingContract); } /// @notice Gets the amount of granted tokens to the specified address. /// @param _owner The address to query the grants balance of. /// @return An uint256 representing the grants balance owned by the passed address. function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /// @notice Gets the stake balance of the specified address. /// @param _address The address to query the balance of. /// @return An uint256 representing the amount staked by the passed address. function stakeBalanceOf(address _address) public view returns (uint256 balance) { for (uint i = 0; i < grantIndices[_address].length; i++) { uint256 id = grantIndices[_address][i]; balance += grants[id].staked; } return balance; } /// @notice Gets grant by ID. Returns only basic grant data. /// If you need unlocking schedule for the grant you must call `getGrantUnlockingSchedule()` /// This is to avoid Ethereum `Stack too deep` issue described here: /// https://forum.ethereum.org/discussion/2400/error-stack-too-deep-try-removing-local-variables /// @param _id ID of the token grant. /// @return amount The amount of tokens the grant provides. /// @return withdrawn The amount of tokens that have already been withdrawn /// from the grant. /// @return staked The amount of tokens that have been staked from the grant. /// @return revoked A boolean indicating whether the grant has been revoked, /// which is to say that it is no longer unlocking. /// @return grantee The grantee of grant. function getGrant(uint256 _id) public view returns ( uint256 amount, uint256 withdrawn, uint256 staked, uint256 revokedAmount, uint256 revokedAt, address grantee ) { return ( grants[_id].amount, grants[_id].withdrawn, grants[_id].staked, grants[_id].revokedAmount, grants[_id].revokedAt, grants[_id].grantee ); } /// @notice Gets grant unlocking schedule by grant ID. /// @param _id ID of the token grant. /// @return grantManager The address designated as the manager of the grant, /// which is the only address that can revoke this grant. /// @return duration The duration, in seconds, during which the tokens will /// unlocking linearly. /// @return start The start time, as a timestamp comparing to `now`. /// @return cliff The timestamp, before which none of the tokens in the grant /// will be unlocked, and after which a linear amount based on /// the time elapsed since the start will be unlocked. /// @return policy The address of the grant's staking policy. function getGrantUnlockingSchedule( uint256 _id ) public view returns ( address grantManager, uint256 duration, uint256 start, uint256 cliff, address policy ) { return ( grants[_id].grantManager, grants[_id].duration, grants[_id].start, grants[_id].cliff, address(grants[_id].stakingPolicy) ); } /// @notice Gets grant ids of the specified address. /// @param _granteeOrGrantManager The address to query. /// @return An uint256 array of grant IDs. function getGrants(address _granteeOrGrantManager) public view returns (uint256[] memory) { return grantIndices[_granteeOrGrantManager]; } /// @notice Gets operator addresses of the specified grantee address. /// @param grantee The grantee address. /// @return An array of all operators for a given grantee. function getGranteeOperators(address grantee) public view returns (address[] memory) { return granteesToOperators[grantee]; } /// @notice Gets grant stake details of the given operator. /// @param operator The operator address. /// @return grantId ID of the token grant. /// @return amount The amount of tokens the given operator delegated. /// @return stakingContract The address of staking contract. function getGrantStakeDetails(address operator) public view returns (uint256 grantId, uint256 amount, address stakingContract) { return grantStakes[operator].getDetails(); } /// @notice Receives approval of token transfer and creates a token grant with a unlocking /// schedule where balance withdrawn to the grantee gradually in a linear fashion until /// start + duration. By then all of the balance will have unlocked. /// @param _from The owner of the tokens who approved them to transfer. /// @param _amount Approved amount for the transfer to create token grant. /// @param _token Token contract address. /// @param _extraData This byte array must have the following values ABI encoded: /// grantManager (address) Address of the grant manager. /// grantee (address) Address of the grantee. /// duration (uint256) Duration in seconds of the unlocking period. /// start (uint256) Timestamp at which unlocking will start. /// cliffDuration (uint256) Duration in seconds of the cliff; /// no tokens will be unlocked until the time `start + cliff`. /// revocable (bool) Whether the token grant is revocable or not (1 or 0). /// stakingPolicy (address) Address of the staking policy for the grant. function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _extraData) public { require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract."); require(_amount <= token.balanceOf(_from), "Sender must have enough amount."); (address _grantManager, address _grantee, uint256 _duration, uint256 _start, uint256 _cliffDuration, bool _revocable, address _stakingPolicy) = abi.decode( _extraData, (address, address, uint256, uint256, uint256, bool, address) ); require(_grantee != address(0), "Grantee address can't be zero."); require( _cliffDuration <= _duration, "Unlocking cliff duration must be less or equal total unlocking duration." ); require(_stakingPolicy != address(0), "Staking policy can't be zero."); uint256 id = numGrants++; grants[id] = Grant( _grantManager, _grantee, 0, 0, 0, _revocable, _amount, _duration, _start, _start.add(_cliffDuration), 0, 0, GrantStakingPolicy(_stakingPolicy) ); // Maintain a record to make it easier to query grants by grant manager. grantIndices[_from].push(id); // Maintain a record to make it easier to query grants by grantee. grantIndices[_grantee].push(id); token.safeTransferFrom(_from, address(this), _amount); // Maintain a record of the unlocked amount balances[_grantee] = balances[_grantee].add(_amount); emit TokenGrantCreated(id); } /// @notice Withdraws Token grant amount to grantee. /// @dev Transfers unlocked tokens of the token grant to grantee. /// @param _id Grant ID. function withdraw(uint256 _id) public { uint256 amount = withdrawable(_id); require(amount > 0, "Grant available to withdraw amount should be greater than zero."); // Update withdrawn amount. grants[_id].withdrawn = grants[_id].withdrawn.add(amount); // Update grantee grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(amount); // Transfer tokens from this contract balance to the grantee token balance. token.safeTransfer(grants[_id].grantee, amount); emit TokenGrantWithdrawn(_id, amount); } /// @notice Calculates and returns unlocked grant amount. /// @dev Calculates token grant amount that has already unlocked, /// including any tokens that have already been withdrawn by the grantee as well /// as any tokens that are available to withdraw but have not yet been withdrawn. /// @param _id Grant ID. function unlockedAmount(uint256 _id) public view returns (uint256) { Grant storage grant = grants[_id]; return (grant.revokedAt != 0) // Grant revoked -> return what is remaining ? grant.amount.sub(grant.revokedAmount) // Not revoked -> calculate the unlocked amount normally : now.getUnlockedAmount( grant.amount, grant.duration, grant.start, grant.cliff ); } /// @notice Calculates withdrawable granted amount. /// @dev Calculates the amount that has already unlocked but hasn't been withdrawn yet. /// @param _id Grant ID. function withdrawable(uint256 _id) public view returns (uint256) { uint256 unlocked = unlockedAmount(_id); uint256 withdrawn = grants[_id].withdrawn; uint256 staked = grants[_id].staked; if (withdrawn.add(staked) >= unlocked) { return 0; } else { return unlocked.sub(withdrawn).sub(staked); } } /// @notice Allows the grant manager to revoke the grant. /// @dev Granted tokens that are already unlocked (releasable amount) /// remain in the grant so grantee can still withdraw them /// the rest are revoked and withdrawable by token grant manager. /// @param _id Grant ID. function revoke(uint256 _id) public { require(grants[_id].grantManager == msg.sender, "Only grant manager can revoke."); require(grants[_id].revocable, "Grant must be revocable in the first place."); require(grants[_id].revokedAt == 0, "Grant must not be already revoked."); uint256 unlockedAmount = unlockedAmount(_id); uint256 revokedAmount = grants[_id].amount.sub(unlockedAmount); grants[_id].revokedAt = now; grants[_id].revokedAmount = revokedAmount; // Update grantee's grants balance. balances[grants[_id].grantee] = balances[grants[_id].grantee].sub(revokedAmount); emit TokenGrantRevoked(_id); } /// @notice Allows the grant manager to withdraw revoked tokens. /// @dev Will withdraw as many of the revoked tokens as possible /// without pushing the grant contract into a token deficit. /// If the grantee has staked more tokens than the unlocked amount, /// those tokens will remain in the grant until undelegated and returned, /// after which they can be withdrawn by calling `withdrawRevoked` again. /// @param _id Grant ID. function withdrawRevoked(uint256 _id) public { Grant storage grant = grants[_id]; require( grant.grantManager == msg.sender, "Only grant manager can withdraw revoked tokens." ); uint256 revoked = grant.revokedAmount; uint256 revokedWithdrawn = grant.revokedWithdrawn; require(revokedWithdrawn < revoked, "All revoked tokens withdrawn."); uint256 revokedRemaining = revoked.sub(revokedWithdrawn); uint256 totalAmount = grant.amount; uint256 staked = grant.staked; uint256 granteeWithdrawn = grant.withdrawn; uint256 remainingPresentInGrant = totalAmount.sub(staked).sub(revokedWithdrawn).sub(granteeWithdrawn); require(remainingPresentInGrant > 0, "No revoked tokens withdrawable."); uint256 amountToWithdraw = remainingPresentInGrant < revokedRemaining ? remainingPresentInGrant : revokedRemaining; token.safeTransfer(msg.sender, amountToWithdraw); grant.revokedWithdrawn += amountToWithdraw; } /// @notice Stake token grant. /// @dev Stakable token grant amount is determined /// by the grant's staking policy. /// @param _id Grant Id. /// @param _stakingContract Address of the staking contract. /// @param _amount Amount to stake. /// @param _extraData Data for stake delegation. This byte array must have /// the following values concatenated: /// - Beneficiary address (20 bytes) /// - Operator address (20 bytes) /// - Authorizer address (20 bytes) function stake(uint256 _id, address _stakingContract, uint256 _amount, bytes memory _extraData) public { require(grants[_id].grantee == msg.sender, "Only grantee of the grant can stake it."); require(grants[_id].revokedAt == 0, "Revoked grant can not be staked"); require( stakingContracts[grants[_id].grantManager][_stakingContract], "Provided staking contract is not authorized." ); // Expecting 60 bytes _extraData for stake delegation. require(_extraData.length == 60, "Stake delegation data must be provided."); address operator = _extraData.toAddress(20); // Calculate available amount. Amount of unlocked tokens minus what user already withdrawn and staked. require(_amount <= availableToStake(_id), "Must have available granted amount to stake."); // Keep staking record. TokenGrantStake grantStake = new TokenGrantStake( address(token), _id, _stakingContract ); grantStakes[operator] = grantStake; granteesToOperators[grants[_id].grantee].push(operator); grants[_id].staked += _amount; token.transfer(address(grantStake), _amount); // Staking contract expects 40 bytes _extraData for stake delegation. // 20 bytes beneficiary's address + 20 bytes operator's address. grantStake.stake(_amount, _extraData); emit TokenGrantStaked(_id, _amount, operator); } /// @notice Returns the amount of tokens available for staking from the grant. /// The stakeable amount is determined by the staking policy of the grant. /// If the grantee has withdrawn some tokens /// or the policy returns an erroneously high value, /// the stakeable amount is limited to the number of tokens remaining. /// @param _grantId Identifier of the grant function availableToStake(uint256 _grantId) public view returns (uint256) { Grant storage grant = grants[_grantId]; // Revoked grants cannot be staked. // If the grant isn't revoked, the number of revoked tokens is 0. if (grant.revokedAt != 0) { return 0; } uint256 amount = grant.amount; uint256 withdrawn = grant.withdrawn; uint256 remaining = amount.sub(withdrawn); uint256 stakeable = grant.stakingPolicy.getStakeableAmount( now, amount, grant.duration, grant.start, grant.cliff, withdrawn ); // Clamp the stakeable amount to what is left in the grant // in the case of a malfunctioning staking policy. if (stakeable > remaining) { stakeable = remaining; } return stakeable.sub(grant.staked); } /// @notice Cancels delegation within the operator initialization period /// without being subjected to the stake lockup for the undelegation period. /// This can be used to undo mistaken delegation to the wrong operator address. /// @param _operator Address of the stake operator. function cancelStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can cancel the delegation." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Undelegate the token grant. /// @param _operator Operator of the stake. function undelegate(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( msg.sender == _operator || msg.sender == grants[grantId].grantee, "Only operator or grantee can undelegate." ); grantStake.undelegate(); } /// @notice Force cancellation of a revoked grant's stake. /// Can be used by the grant manager /// to immediately withdraw tokens back into the grant, /// from an operator still within the initialization period. /// These tokens can then be withdrawn /// if some revoked tokens haven't been withdrawn yet. function cancelRevokedStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force cancellation of revoked grant stake." ); uint256 returned = grantStake.cancelStake(); grants[grantId].staked = grants[grantId].staked.sub(returned); } /// @notice Force undelegation of a revoked grant's stake. /// @dev Can be called by the grant manager once the grant is revoked. /// Has to be done this way, instead of undelegating all operators when the /// grant is revoked, because the latter method is vulnerable to DoS via /// out-of-gas. function undelegateRevoked(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 grantId = grantStake.getGrantId(); require( grants[grantId].revokedAt != 0, "Grant must be revoked" ); require( msg.sender == grants[grantId].grantManager, "Only grant manager can force undelegation of revoked grant stake" ); grantStake.undelegate(); } /// @notice Recover stake of the token grant. /// Recovers the tokens correctly /// even if they were earlier recovered directly in the staking contract. /// @param _operator Operator of the stake. function recoverStake(address _operator) public { TokenGrantStake grantStake = grantStakes[_operator]; uint256 returned = grantStake.recoverStake(); uint256 grantId = grantStake.getGrantId(); grants[grantId].staked = grants[grantId].staked.sub(returned); delete grantStakes[_operator]; } } pragma solidity 0.5.17; library AddressArrayUtils { function contains(address[] memory self, address _address) internal pure returns (bool) { for (uint i = 0; i < self.length; i++) { if (_address == self[i]) { return true; } } return false; } function removeAddress(address[] storage self, address _addressToRemove) internal returns (address[] storage) { for (uint i = 0; i < self.length; i++) { // If address is found in array. if (_addressToRemove == self[i]) { // Delete element at index and shift array. for (uint j = i; j < self.length-1; j++) { self[j] = self[j+1]; } self.length--; i--; } } return self; } }
Remove the lock of `creator`. If no lock present, do nothing. Not the last lock, so we need to move the last lock into the emptied position.
function releaseLock( LockSet storage self, address _creator ) internal { uint256 positionPlusOne = self.positions[_creator]; if (positionPlusOne != 0) { uint256 lockCount = self.locks.length; if (positionPlusOne != lockCount) { Lock memory lastLock = self.locks[lockCount - 1]; self.locks[positionPlusOne - 1] = lastLock; self.positions[lastLock.creator] = positionPlusOne; } self.locks.length--; self.positions[_creator] = 0; } }
12,847,213
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; contract Authorizeable is AccessControl { bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE"); constructor (){ _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(MODERATOR_ROLE, msg.sender); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "./ExchangeCore.sol"; /** * @title Exchange * @author Wyvern Protocol Developers */ contract Exchange is ExchangeCore { /* external ABI-encodable method wrappers. */ function hashOrder_(address maker, address target, address token, uint256 percent, uint256 price, uint256 tokenId, uint256 listingTime, uint256 expirationTime, uint256 salt) external pure returns (bytes32 hash) { return hashOrder(Order(maker, target, token, percent, price, tokenId, listingTime, expirationTime, salt)); } function hashToSign_(bytes32 orderHash) external view returns (bytes32 hash) { return hashToSign(orderHash); } function addFarmAddress_(address _token)public onlyOwner{ addFarmAddress(_token); } function addMoneyHandAddress_(address _contract)public onlyOwner{ addMoneyHandAdd(_contract); } function validateOrderParameters_(address maker, address target, address token, uint256 percent, uint price, uint tokenId, uint listingTime, uint expirationTime, uint salt) external view returns (bool) { Order memory order = Order(maker, target, token, percent, price, tokenId, listingTime, expirationTime, salt); return validateOrderParameters(order, hashOrder(order)); } function validateOrderAuthorization_(bytes32 hash, address maker, bytes calldata signature) external view returns (bool) { return validateOrderAuthorization(hash, maker, signature); } function atomicMatch_(address[6] memory addresses, uint256[12] memory uints, bytes memory signatures) public payable { return atomicMatch( Order(addresses[0], addresses[1], addresses[2], (uints[0]), uints[1], uints[2], uints[3], uints[4], uints[5]), Order(addresses[3], addresses[4], addresses[5], (uints[6]), uints[7], uints[8], uints[9], uints[10], uints[11]), signatures ); } function ecrecover_(bytes32 calculatedHashToSign, bytes memory signature) public view returns (address) { (uint8 v, bytes32 r, bytes32 s) = abi.decode(signature, (uint8, bytes32, bytes32)); return ecrecover(keccak256(abi.encodePacked(personalSignPrefix,"32",calculatedHashToSign)), v, r, s); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./lib/ReentrancyGuarded.sol"; import "./lib/EIP712.sol"; import "./lib/EIP1271.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./MoneyHandler.sol"; import "./FarmV2.sol"; contract ExchangeCore is ReentrancyGuarded, EIP712, Ownable{ using SafeERC20 for IERC20; bytes4 constant internal EIP_1271_MAGICVALUE = 0x20c13b0b; bytes internal personalSignPrefix = "\x19Ethereum Signed Message:\n"; MoneyHandler public moneyHand; IERC20 public token; FarmV2 public farm; /* Struct definitions. */ /* An order, convenience struct. */ struct Order { /* Order maker address. */ address maker; /* Order maker address. */ address target; /* token address */ address token; /*distribution percentage */ uint256 percent; /* Order price. */ uint256 price; /* NFT tokenId */ uint256 tokenId; /* Order listing timestamp. */ uint256 listingTime; /* Order expiration timestamp - 0 for no expiry. */ uint256 expirationTime; /* Order salt to prevent duplicate hashes. */ uint256 salt; } /* Constants */ /* Order typehash for EIP 712 compatibility. */ bytes32 constant ORDER_TYPEHASH = keccak256( "Order(address maker,address target,address moneyHandler,uint256 price,uint256 tokenId,uint256 listingTime,uint256 expirationTime,uint256 salt)" ); /* Variables */ /* Trusted proxy registry contracts. */ mapping(address => bool) public registries; mapping(address => address) public orders; /* Order fill status, by maker address then by hash. */ mapping(address => mapping(bytes32 => uint)) public fills; mapping(address => mapping(bytes32 => bool)) public approved; /* Events */ event OrderApproved (bytes32 indexed hash, address indexed maker, uint amount, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderFillChanged (bytes32 indexed hash, address indexed maker, uint newFill); event OrdersMatched (bytes32 firstHash, bytes32 secondHash, address indexed firstMaker, address indexed secondMaker); /* Functions */ function addFarmAddress(address _token) internal onlyOwner{ //token = IERC20(_token); farm = FarmV2(_token); } function addMoneyHandAdd(address _contract) internal onlyOwner{ moneyHand = MoneyHandler(_contract); } function hashOrder(Order memory order) internal pure returns (bytes32 hash) { /* Per EIP 712. */ return keccak256(abi.encode( ORDER_TYPEHASH, order.maker, order.target, order.token, order.percent, order.price, order.tokenId, order.listingTime, order.expirationTime, order.salt )); } function hashToSign(bytes32 orderHash) internal view returns (bytes32 hash) { /* Calculate the string a user must sign. */ return keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, orderHash )); } function exists(address what) internal view returns (bool) { uint size; assembly { size := extcodesize(what) } return size > 0; } function validateOrderParameters(Order memory order, bytes32 hash_) internal view returns (bool) { /* Order must be listed and not be expired. */ if (order.listingTime > block.timestamp || (order.expirationTime != 0 && order.expirationTime <= block.timestamp)) { return false; } return true; } function validateOrderAuthorization(bytes32 hash, address maker, bytes memory signature) internal view returns (bool) { /* Memoized authentication. If order has already been partially filled, order must be authenticated. */ if (fills[maker][hash] > 0) { return true; } /* Order authentication. Order must be either: */ /* (a): sent by maker */ if (maker == msg.sender) { return true; } /* (b): previously approved */ if (approved[maker][hash]) { return true; } /* Calculate hash which must be signed. */ bytes32 calculatedHashToSign = hashToSign(hash); (uint8 v, bytes32 r, bytes32 s) = abi.decode(signature, (uint8, bytes32, bytes32)); if (ecrecover(keccak256(abi.encodePacked(personalSignPrefix,"32",calculatedHashToSign)), v, r, s)==maker) { return true; } return false; } function atomicMatch(Order memory seller, Order memory buyer, bytes memory signatures) internal reentrancyGuard { IERC1155 collection = IERC1155(seller.target); //IERC20 token_ = IERC20(buyer.target); require(seller.price == buyer.price, "price is not equal"); /* CHECKS */ /* Calculate first order hash. */ bytes32 firstHash = hashOrder(seller); /* Check first order validity. */ require(validateOrderParameters(seller, firstHash), "First order has invalid parameters"); /* Calculate second order hash. */ bytes32 secondHash = hashOrder(buyer); /* Check second order validity. */ require(validateOrderParameters(buyer, secondHash), "Second order has invalid parameters"); require(fills[seller.maker][firstHash]==0, "this order already filled"); /* Prevent self-matching (possibly unnecessary, but safer). */ require(firstHash != secondHash, "Self-matching orders is prohibited"); { /* Calculate signatures (must be awkwardly decoded here due to stack size constraints). */ (bytes memory firstSignature, bytes memory secondSignature) = abi.decode(signatures, (bytes, bytes)); /* Check first order authorization. */ require(validateOrderAuthorization(firstHash, seller.maker, firstSignature), "First order failed authorization"); /* Check second order authorization. */ require(validateOrderAuthorization(secondHash, buyer.maker, secondSignature), "Second order failed authorization"); } require(collection.isApprovedForAll(seller.maker, address(this)), "Seller must be approve"); require(collection.balanceOf(seller.maker, seller.tokenId) > 0, "Seller must be have enough funds"); if(address(farm)==seller.token){ farm = FarmV2(seller.token); require(farm.rewardedStones(buyer.maker) >= seller.price, "Buyer must be have enough funds"); farm.sell(seller.price, buyer.maker, seller.maker); collection.safeTransferFrom(seller.maker,buyer.maker, seller.tokenId, 1, ""); } else{ IERC20 token_ = IERC20(seller.token); require(token_.balanceOf(buyer.maker) >= seller.price, "Buyer must be have enough funds"); uint256 sellmul= SafeMath.mul(seller.price,seller.percent); uint256 sellAmount= SafeMath.div(sellmul,10**18); uint256 sharePerc = SafeMath.sub(10**18,seller.percent); uint256 sharemul = SafeMath.mul(seller.price,sharePerc); uint256 shareAmount = SafeMath.div(sharemul,10**18); token_.safeTransferFrom(buyer.maker, address(this), seller.price); collection.safeTransferFrom(seller.maker,buyer.maker, seller.tokenId, 1, ""); token_.transfer(seller.maker, sellAmount); token_.transfer(address(moneyHand),shareAmount); moneyHand.updateCollecMny(seller.target,shareAmount); } // Price will transfer to money transfer contract // moneyHand.updateRecieved(seller.target, shareAmount); fills[seller.maker][firstHash] = seller.price; /* LOGS */ /* Log match event. */ emit OrdersMatched(firstHash, secondHash, buyer.maker, seller.maker); } } pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./Authorizeable.sol"; contract Farm is Ownable{ using SafeERC20 for ERC20; using SafeMath for uint256; uint256 public limit = 10000 ether; uint256 public total; struct Staker { uint256 amount; uint256 stones; uint256 timestamp; } mapping(address => Staker) public stakers; ERC20 private _token; // constructor() {} function setTokenAddress(ERC20 token_) external onlyOwner { _token = token_; } function giveAway(address _address, uint256 stones) external onlyOwner { stakers[_address].stones = stones; } function farmed(address sender) public view returns (uint256) { // Returns how many ERN this account has farmed return (stakers[sender].amount); } function farmedStart(address sender) public view returns (uint) { // Returns when this account started farming return (stakers[sender].timestamp); } function payment(address buyer, uint256 amount) external returns (bool) { consolidate(buyer); require(rewardedStones(buyer) >= amount, "Insufficient stones!"); stakers[buyer].stones = stakers[buyer].stones.sub(amount); return true; } function rewardedStones(address staker) public view returns (uint256) { if (stakers[staker].amount < 1000) { return stakers[staker].stones; } // solium-disable-next-line security/no-block-members uint256 _seconds = block.timestamp.sub(stakers[staker].timestamp).div(1 seconds); return stakers[staker].stones.add(stakers[staker].amount.div(1e18).mul(_seconds).mul(11574074074074000)); } function consolidate(address staker) internal { uint256 stones = rewardedStones(staker); stakers[staker].stones = stones; } function deposit(uint256 amount) public { address sender = msg.sender; require(stakers[sender].amount.add(amount) <= limit, "Limit 10000 ERN"); _token.safeTransferFrom(sender, address(this), amount); consolidate(sender); total = total.add(amount); stakers[sender].amount = stakers[sender].amount.add(amount); // solium-disable-next-line security/no-block-members stakers[sender].timestamp = block.timestamp; } function withdraw(uint256 amount) public { address sender = msg.sender; require(stakers[sender].amount >= amount, "Insufficient amount!"); require(_token.transfer(address(sender), amount), "Transfer error!"); consolidate(sender); stakers[sender].amount = stakers[sender].amount.sub(amount); total = total.sub(amount); // solium-disable-next-line security/no-block-members stakers[sender].timestamp = block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./Authorizeable.sol"; import "./Farm.sol"; contract FarmV2 is AccessControl{ using SafeERC20 for ERC20; using SafeMath for uint256; uint256 public limit = 10000 ether; uint256 public total; Farm private _farmv1; bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE")); struct Staker { uint256 amount; uint256 stones; uint256 timestamp; bool oldStaker; } mapping(address => Staker) public stakers; ERC20 private _token; constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function setTokenAddress(ERC20 token_, address farmv1_) external onlyRole(DEFAULT_ADMIN_ROLE) { _token = token_; _farmv1 = Farm(farmv1_); } function giveAway(address _address, uint256 stones) external onlyRole(DEFAULT_ADMIN_ROLE) { stakers[_address].stones = stones; } function farmed(address sender) public view returns (uint256) { // Returns how many ERN this account has farmed return (stakers[sender].amount); } function farmedStart(address sender) public view returns (uint) { // Returns when this account started farming return (stakers[sender].timestamp); } function payment(address buyer, uint256 amount) public onlyRole(COLLECTION_ROLE) returns (bool) { consolidate(buyer); require(rewardedStones(buyer) >= amount, "Insufficient stones!"); stakers[buyer].stones = stakers[buyer].stones.sub(amount); stakers[buyer].timestamp = block.timestamp; return true; } function rewardedStones(address staker) public view returns (uint256) { if (stakers[staker].amount < 1000) { return stakers[staker].stones; } // solium-disable-next-line security/no-block-members uint256 _seconds = block.timestamp.sub(stakers[staker].timestamp).div(1 seconds); return stakers[staker].stones.add(stakers[staker].amount.div(1e18).mul(_seconds).mul(11574074074074000)); } function consolidate(address staker) internal { uint256 stones = rewardedStones(staker); stakers[staker].stones = stones; } function deposit(uint256 amount ) public { address account = msg.sender; uint256 oldAmount = _farmv1.rewardedStones(account); require(_token.balanceOf(account) > 0, "your balance is insufficient"); require(stakers[account].amount.add(amount) <= limit, "Limit 10000 ERN"); _token.safeTransferFrom(account, address(this), amount); consolidate(account); total = total.add(amount); stakers[account].amount = stakers[account].amount.add(amount); if(stakers[account].oldStaker != true && oldAmount > 0) { stakers[account].stones = stakers[account].stones.add(oldAmount); stakers[account].oldStaker = true; } // solium-disable-next-line security/no-block-members stakers[account].timestamp = block.timestamp; } function withdraw(uint256 amount) public { address account = msg.sender; //require(account == msg.sender,"you are not authorized on this account!"); require(stakers[account].amount >= amount, "Insufficient amount!"); require(_token.transfer(account, amount), "Transfer error!"); consolidate(account); stakers[account].amount = stakers[account].amount.sub(amount); total = total.sub(amount); // solium-disable-next-line security/no-block-members stakers[account].timestamp = block.timestamp; } function sell(uint256 stones, address from, address to) public { require(hasRole(COLLECTION_ROLE, msg.sender), "you are not authorized on this account!"); consolidate(from); require(rewardedStones(from) >= stones, "Insufficient stones!"); stakers[from].stones = stakers[from].stones.sub(stones); stakers[from].timestamp = block.timestamp; stakers[to].stones = stakers[to].stones.add(stones); stakers[to].timestamp = block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <=0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract MoneyHandler is Context, AccessControl{ using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); IERC20 private token; // uint256 public _totalShares; uint256 public _totalReleased; // uint256 public amu = 1; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; mapping(address => uint256) public collectionMoney; address[] private _payees; uint256 private _totalCllcAmnt; bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE")); constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ /** * @dev Getter for the total shares held by payees. */ // function totalShares() public view returns (uint256) { // return _totalShares; // } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } function collecMny(address collection) public view returns (uint256) { return collectionMoney[collection]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } function updateCollecMny(address collection, uint256 amount) public onlyRole(COLLECTION_ROLE) { collectionMoney[collection] = collectionMoney[collection].add(amount); } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address account, address collection, address _token) private { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); _released[account] = _released[account].add(_shares[account]); _totalReleased = _totalReleased.add(_shares[account]); IERC20 token = IERC20(_token); token.transfer(account, _shares[account]); collectionMoney[collection] = collectionMoney[collection].sub(_shares[account]); emit PaymentReleased(account, _shares[account]); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * // shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 sharePerc_, address collection, address _token) private { require(account != address(0), "PaymentSplitter: account is the zero address"); uint256 shares_ = getAmountPer(_totalCllcAmnt,sharePerc_); _shares[account] = shares_; _payees.push(account); release(account, collection, _token); // emit PayeeAdded(account, shares_); } //Get amount per person function getAmountPer(uint256 totalAmount,uint256 sharePerc) private pure returns(uint256){ uint256 sharesmul_ = SafeMath.mul(totalAmount,sharePerc); uint256 shares_ = SafeMath.div(sharesmul_,10**18); return shares_; } function recoverToken(address _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).transfer(msg.sender, amount); } function redeem (address collection, address _token, address[] memory payees, uint256 [] memory sharePerc_) public onlyRole(DEFAULT_ADMIN_ROLE) { require(payees.length > 0, "redeem: no payees"); require(payees.length == sharePerc_.length, "redeem: no payees"); _totalCllcAmnt = collectionMoney[collection]; require(_totalCllcAmnt > 0,"redeem: insufficient funds"); uint256 totalShareAmount; for (uint256 i = 0; i < sharePerc_.length; i++) { totalShareAmount = totalShareAmount.add(getAmountPer(_totalCllcAmnt, sharePerc_[i])); } require(_totalCllcAmnt >= totalShareAmount, "redeem: the total amount in the contract must be equal to or greater than the amount to be withdraw"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], sharePerc_[i], collection, _token); } } } // SPDX-License-Identifier: MIT /* << EIP 1271 >> */ pragma solidity 0.8.0; abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant internal MAGICVALUE = 0x20c13b0b; /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature( bytes memory _data, bytes memory _signature) virtual public view returns (bytes4 magicValue); } // SPDX-License-Identifier: MIT /* << EIP 712 >> */ pragma solidity 0.8.0; /** * @title EIP712 * @author Wyvern Protocol Developers */ contract EIP712 { struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 DOMAIN_SEPARATOR; function hash(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } } // SPDX-License-Identifier: MIT /* Simple contract extension to provide a contract-global reentrancy guard on functions. */ pragma solidity 0.8.0; /** * @title ReentrancyGuarded * @author Wyvern Protocol Developers */ contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { require(!reentrancyLock, "Reentrancy detected"); reentrancyLock = true; _; reentrancyLock = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor (string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); _balances[id][from] = fromBalance - amount; _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); _balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
Order must be listed and not be expired. /
function validateOrderParameters(Order memory order, bytes32 hash_) internal view returns (bool) { if (order.listingTime > block.timestamp || (order.expirationTime != 0 && order.expirationTime <= block.timestamp)) { return false; } return true; }
13,121,238
./full_match/5/0x56fAa0936951344e2DcBB2faD6348DeA04c967de/sources/contracts/MvM.sol
setter function to pause/start level one mint
function setCanMintL1(bool _pauseMintL1) public onlyOwner { pauseMintL1 = _pauseMintL1; }
1,923,974
./partial_match/42/0xAE311d0b6302606F4927940158Aba7a2dbd22553/sources/DisposableGovernance.sol
Calls the Oraclize Query to close a given Claim after a given period of time. id Claim Id to be closed time Time (in seconds) after which Claims assessment voting needs to be closed
function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); }
3,432,858
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardEvents.sol /// @title Witnet Request Board emitting events interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardEvents { /// Emitted when a Witnet Data Request is posted to the WRB. event PostedRequest(uint256 queryId, address from); /// Emitted when a Witnet-solved result is reported to the WRB. event PostedResult(uint256 queryId, address from); /// Emitted when all data related to given query is deleted from the WRB. event DeletedQuery(uint256 queryId, address from); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardReporter.sol /// @title The Witnet Request Board Reporter interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardReporter { /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external; /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: node_modules\witnet-solidity-bridge\contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardRequestor.sol /// @title Witnet Requestor Interface /// @notice It defines how to interact with the Witnet Request Board in order to: /// - request the execution of Witnet Radon scripts (data request); /// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet; /// - read the result of any previously posted request, eventually reported by the Witnet DON. /// - remove from storage all data related to past and solved data requests, and results. /// @author The Witnet Foundation. interface IWitnetRequestBoardRequestor { /// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory); /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId); /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) external payable; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardView.sol /// @title Witnet Request Board info interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardView { /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) external view returns (uint256); /// Returns next query id to be generated by the Witnet Request Board. function getNextQueryId() external view returns (uint256); /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory); /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus); /// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequest(uint256 _queryId) external view returns (Witnet.Request memory); /// Retrieves the serialized bytecode of a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestBytecode(uint256 _queryId) external view returns (bytes memory); /// Retrieves the gas price that any assigned reporter will have to pay when reporting result /// to the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestGasPrice(uint256 _queryId) external view returns (uint256); /// Retrieves the reward currently set for the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestReward(uint256 _queryId) external view returns (uint256); /// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponse(uint256 _queryId) external view returns (Witnet.Response memory); /// Retrieves the hash of the Witnet transaction hash that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32); /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseReporter(uint256 _queryId) external view returns (address); /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory); /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view returns (uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestParser.sol /// @title The Witnet interface for decoding Witnet-provided request to Data Requests. /// This interface exposes functions to check for the success/failure of /// a Witnet-provided result, as well as to parse and convert result into /// Solidity types suitable to the application level. /// @author The Witnet Foundation. interface IWitnetRequestParser { /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory); /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory); /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool); /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool); /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns (bytes memory); /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes); /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory); /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory); /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool); /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32); /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory); /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128); /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory); /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns (string memory); /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory); /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64); /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory); } // File: node_modules\witnet-solidity-bridge\contracts\WitnetRequestBoard.sol /// @title Witnet Request Board functionality base contract. /// @author The Witnet Foundation. abstract contract WitnetRequestBoard is IWitnetRequestBoardEvents, IWitnetRequestBoardReporter, IWitnetRequestBoardRequestor, IWitnetRequestBoardView, IWitnetRequestParser { receive() external payable { revert("WitnetRequestBoard: no transfers accepted"); } } // File: witnet-solidity-bridge\contracts\UsingWitnet.sol /// @title The UsingWitnet contract /// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet. /// @author The Witnet Foundation. abstract contract UsingWitnet { WitnetRequestBoard public immutable witnet; /// Include an address to specify the WitnetRequestBoard entry point address. /// @param _wrb The WitnetRequestBoard entry point address. constructor(WitnetRequestBoard _wrb) { require(address(_wrb) != address(0), "UsingWitnet: zero address"); witnet = _wrb; } /// Provides a convenient way for client contracts extending this to block the execution of the main logic of the /// contract until a particular request has been successfully solved and reported by Witnet. modifier witnetRequestSolved(uint256 _id) { require( _witnetCheckResultAvailability(_id), "UsingWitnet: request not solved" ); _; } /// Check if a data request has been solved and reported by Witnet. /// @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. /// parties) before this method returns `true`. /// @param _id The unique identifier of a previously posted data request. /// @return A boolean telling if the request has been already resolved or not. Returns `false` also, if the result was deleted. function _witnetCheckResultAvailability(uint256 _id) internal view virtual returns (bool) { return witnet.getQueryStatus(_id) == Witnet.QueryStatus.Reported; } /// Estimate the reward amount. /// @param _gasPrice The gas price for which we want to retrieve the estimation. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward(uint256 _gasPrice) internal view virtual returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Estimates the reward amount, considering current transaction gas price. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward() internal view virtual returns (uint256) { return witnet.estimateReward(tx.gasprice); } /// Send a new request to the Witnet network with transaction value as a reward. /// @param _request An instance of `IWitnetRequest` contract. /// @return _id Sequential identifier for the request included in the WitnetRequestBoard. /// @return _reward Current reward amount escrowed by the WRB until a result gets reported. function _witnetPostRequest(IWitnetRequest _request) internal virtual returns (uint256 _id, uint256 _reward) { _reward = _witnetEstimateReward(); _id = witnet.postRequest{value: _reward}(_request); } /// Upgrade the reward for a previously posted request. /// @dev Call to `upgradeReward` function in the WitnetRequestBoard contract. /// @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. /// @return Amount in which the reward has been increased. function _witnetUpgradeReward(uint256 _id) internal virtual returns (uint256) { uint256 _currentReward = witnet.readRequestReward(_id); uint256 _newReward = _witnetEstimateReward(); uint256 _fundsToAdd = 0; if (_newReward > _currentReward) { _fundsToAdd = (_newReward - _currentReward); } witnet.upgradeReward{value: _fundsToAdd}(_id); // Let Request.gasPrice be updated return _fundsToAdd; } /// Read the Witnet-provided result to a previously posted request. /// @param _id The unique identifier of a request that was posted to Witnet. /// @return The result of the request as an instance of `Witnet.Result`. function _witnetReadResult(uint256 _id) internal view virtual returns (Witnet.Result memory) { return witnet.readResponseResult(_id); } /// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage. /// @param _id The unique identifier of a previously posted request. /// @return The Witnet-provided result to the request. function _witnetDeleteQuery(uint256 _id) internal virtual returns (Witnet.Response memory) { return witnet.deleteQuery(_id); } } // File: node_modules\witnet-solidity-bridge\contracts\requests\WitnetRequestBase.sol abstract contract WitnetRequestBase is IWitnetRequest { /// Contains a well-formed Witnet Data Request, encoded using Protocol Buffers. bytes public override bytecode; /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. bytes32 public override hash; } // File: witnet-solidity-bridge\contracts\requests\WitnetRequest.sol contract WitnetRequest is WitnetRequestBase { using Witnet for bytes; constructor(bytes memory _bytecode) { bytecode = _bytecode; hash = _bytecode.hash(); } } // File: node_modules\@openzeppelin\contracts\utils\introspection\IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: node_modules\@openzeppelin\contracts\token\ERC721\extensions\IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: node_modules\@openzeppelin\contracts\utils\Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: node_modules\@openzeppelin\contracts\utils\Context.sol /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: node_modules\@openzeppelin\contracts\utils\Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: node_modules\@openzeppelin\contracts\utils\introspection\ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin\contracts\token\ERC721\ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin\contracts\access\Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin\contracts\security\ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin\contracts\utils\Counters.sol /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: contracts\libs\Witmons.sol /// @title Witmons Library: data model and helper functions /// @author Otherplane Labs, 2021. library Witmons { struct State { Parameters params; address decorator; IWitnetRequest witnetRNG; uint256 witnetQueryId; bytes32 witnetRandomness; uint256 hatchingBlock; Counters.Counter totalSupply; mapping (/* eggIndex => Creature */ uint256 => Creature) creatures; mapping (/* tokenId => eggIndex */ uint256 => uint256) eggIndex_; } struct Parameters { address signator; uint8[] percentileMarks; uint256 expirationBlocks; } enum Status { Batching, Randomizing, Hatching, Freezed } struct Creature { uint256 tokenId; uint256 eggBirth; uint256 eggIndex; uint256 eggScore; uint256 eggRanking; bytes32 eggPhenotype; CreatureCategory eggCategory; } enum CreatureCategory { Legendary, // 0 Rare, // 1 Common // 2 } enum CreatureStatus { Inexistent, // 0 Incubating, // 1 Hatching, // 2 Alive, // 3 Freezed // 4 } /// Calculate creature category. function creatureCategory(State storage _self, uint8 _percentile100) internal view returns (CreatureCategory) { uint8 _i; uint8 _cumuled; for (; _i < _self.params.percentileMarks.length; _i ++) { _cumuled += _self.params.percentileMarks[_i]; if (_percentile100 <= _cumuled) { break; } } return CreatureCategory(_i); } /// Gets tender's current status. function status(State storage self) internal view returns (Status) { if (self.witnetRandomness != bytes32(0)) { return (block.number > self.hatchingBlock + self.params.expirationBlocks) ? Status.Freezed : Status.Hatching; } else if (self.witnetQueryId > 0) { return Status.Randomizing; } else { return Status.Batching; } } /// @dev Produces revert message when tender is not in expected status. function statusRevertMessage(Status _status) internal pure returns (string memory) { if (_status == Status.Freezed) { return "Witmons: not in Freezed status"; } else if (_status == Status.Batching) { return "Witmons: not in Batching status"; } else if (_status == Status.Randomizing) { return "Witmons: not in Randomizing status"; } else if (_status == Status.Hatching) { return "Witmons: not in Hatching status"; } else { return "Witmons: bad mood"; } } /// Returns index of Most Significant Bit of given number, applying De Bruijn O(1) algorithm. function msbDeBruijn32(uint32 _v) internal pure returns (uint8) { uint8[32] memory _bitPosition = [ 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 ]; _v |= _v >> 1; _v |= _v >> 2; _v |= _v >> 4; _v |= _v >> 8; _v |= _v >> 16; return _bitPosition[ uint32(_v * uint256(0x07c4acdd)) >> 27 ]; } /// Generates pseudo-random number uniformly distributed in range [0 .. _range). function randomUint8(bytes32 _seed, uint256 _index, uint8 _range) internal pure returns (uint8) { assert(_range > 0); uint8 _flagBits = uint8(255 - msbDeBruijn32(uint32(_range))); uint256 _number = uint256(keccak256(abi.encode(_seed, _index))) & uint256(2 ** _flagBits - 1); return uint8((_number * _range) >> _flagBits); } /// Recovers address from hash and signature. function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } } // File: contracts\interfaces\IWitmonDecorator.sol /// @title Witty Creatures 2.0 Decorating interface. /// @author Otherplane Labs, 2021. interface IWitmonDecorator { function baseURI() external view returns (string memory); function getCreatureImage(Witmons.Creature memory) external view returns (string memory); function getCreatureMetadata(Witmons.Creature memory) external view returns (string memory); } // File: contracts\interfaces\IWitmonAdmin.sol /// @title Witty Creatures 2.0 Token only-owner interface. /// @author Otherplane Labs, 2021. interface IWitmonAdmin { /// Change token/creature decorator. /// @param _decorator Decorating logic contract producing a creature's metadata, and picture. function setDecorator(IWitmonDecorator _decorator) external; /// Change batch parameters. Only possible while in 'Batching' status. /// @param _signator Externally-owned account authorize to sign egg's info before minting. /// @param _percentileMarks Creature-category ordered percentile marks (Legendary first). /// @param _expirationBlocks Number of blocks after Witnet randomness is generated, /// during which creatures may be minted. function setParameters( address _signator, uint8[] calldata _percentileMarks, uint256 _expirationBlocks ) external; /// Stops batching, which means: (a) parameters cannot change anymore, and (b) a /// random number will requested to the Witnet Decentralized Oracle Network. /// @dev While request is being attended, tender will remain in 'Randomizing' status. function stopBatching() external payable; /// Starts hatching, which means that minting of creatures will start to be possible, /// until the hatching period expires (see `_hatchingExpirationBlocks`). /// @dev During the hatching period the tender will remain in 'Hatching status'. Once the /// @dev hatching period expires, tender status will automatically change to 'Freezed'. function startHatching() external; } // File: contracts\interfaces\IWitmonEvents.sol /// @title Witty Creatures 2.0 Token events. /// @author Otherplane Labs, 2021. interface IWitmonEvents { event BatchParameters( address signator, uint8[] percentileMarks, uint256 expirationBlocks ); event DecoratorSet(IWitmonDecorator decorator); event WitnetResult(bytes32 randomness); event WitnetError(string reason); event NewCreature(uint256 eggIndex, uint256 tokenId); } // File: contracts\interfaces\IWitmonSurrogates.sol /// @title Witty Creatures 2.0 Token surrogating interface. /// @author Otherplane Labs, 2021. interface IWitmonSurrogates { function mintCreature( address _eggOwner, uint256 _eggIndex, uint256 _eggScore, uint256 _eggRanking, uint256 _totalClaimedEggs, bytes calldata _signature ) external; function previewCreatureImage( address _eggOwner, uint256 _eggIndex, uint256 _eggScore, uint256 _eggRanking, uint256 _totalClaimedEggs, bytes calldata _signature ) external view returns (string memory); } // File: contracts\interfaces\IWitmonView.sol /// @title Witty Creatures 2.0 Token viewing interface. /// @author Otherplane Labs, 2021. interface IWitmonView { function getCreatureData(uint256 _eggIndex) external view returns (Witmons.Creature memory); function getCreatureImage(uint256 _eggIndex) external view returns (string memory); function getCreatureStatus(uint256 _eggIndex) external view returns (Witmons.CreatureStatus); function getDecorator() external view returns (IWitmonDecorator); function getParameters() external view returns (Witmons.Parameters memory); function getTokenEggIndex(uint256 _tokenId) external view returns (uint256); function totalSupply() external view returns (uint256 _totalSupply); function getStatus() external view returns (Witmons.Status); } // File: contracts\WitmonERC721.sol /// @title Witty Creatures 2.0 - ERC721 Token contract /// @author Otherplane Labs, 2021. contract WitmonERC721 is ERC721, Ownable, ReentrancyGuard, UsingWitnet, IWitmonAdmin, IWitmonEvents, IWitmonSurrogates, IWitmonView { using Counters for Counters.Counter; using Strings for bytes32; using Strings for uint256; using Witmons for Witmons.State; Witmons.State internal _state; modifier inStatus(Witmons.Status _status) { require( _state.status() == _status, Witmons.statusRevertMessage(_status) ); _; } modifier tokenExists(uint256 _tokenId) { require( _exists(_tokenId), "WitmonERC721: inexistent token" ); _; } constructor( WitnetRequestBoard _witnet, IWitmonDecorator _decorator, string memory _name, string memory _symbol, address _signator, uint8[] memory _percentileMarks, uint256 _expirationBlocks ) UsingWitnet(_witnet) ERC721(_name, _symbol) { setDecorator(_decorator); setParameters( _signator, _percentileMarks, _expirationBlocks ); _state.witnetRNG = new WitnetRequest(hex"0a0f120508021a01801a0210022202100b10e807180a200a2833308094ebdc03"); } // ======================================================================== // --- 'ERC721Metadata' overriden functions ------------------------------- function baseURI() public view virtual returns (string memory) { return IWitmonDecorator(_state.decorator).baseURI(); } function metadata(uint256 _tokenId) external virtual view tokenExists(_tokenId) returns (string memory) { uint256 _eggIndex = _state.eggIndex_[_tokenId]; Witmons.Creature memory _creature = _state.creatures[_eggIndex]; assert(_tokenId == _creature.tokenId); return IWitmonDecorator(_state.decorator).getCreatureMetadata(_creature); } function tokenURI(uint256 _tokenId) public view virtual override tokenExists(_tokenId) returns (string memory) { return string(abi.encodePacked( baseURI(), _tokenId.toString() )); } // ======================================================================== // --- Implementation of 'IWitmonAdmin' ----------------------------------- /// Change token/creature decorator. /// @param _decorator Decorating logic contract producing a creature's metadata, and picture. function setDecorator(IWitmonDecorator _decorator) public virtual override onlyOwner // inState(Witmons.Status.Batching) { require(address(_decorator) != address(0), "WitmonERC721: no decorator"); _state.decorator = address(_decorator); emit DecoratorSet(_decorator); } /// Change batch parameters. Only possible while in 'Batching' status. /// @param _signator Externally-owned account authorize to sign egg's info before minting. /// @param _percentileMarks Creature-category ordered percentile marks (Legendary first). /// @param _expirationBlocks Number of blocks after Witnet randomness is generated, /// during which creatures may be minted. function setParameters( address _signator, uint8[] memory _percentileMarks, uint256 _expirationBlocks ) public virtual override onlyOwner inStatus(Witmons.Status.Batching) { require(_signator != address(0), "WitmonERC721: no signator"); require(_percentileMarks.length == uint8(Witmons.CreatureCategory.Common) + 1, "WitmonERC721: bad percentile marks"); _state.params.percentileMarks = new uint8[](_percentileMarks.length); uint8 _checkSum; for (uint8 _i = 0; _i < _percentileMarks.length; _i ++) { uint8 _mark = _percentileMarks[_i]; _state.params.percentileMarks[_i] = _mark; _checkSum += _mark; } require(_checkSum == 100, "WitmonERC721: bad percentile checksum"); _state.params.signator = _signator; _state.params.expirationBlocks = _expirationBlocks; emit BatchParameters( _signator, _percentileMarks, _expirationBlocks ); } /// Stops batching, which means: (a) parameters cannot change anymore, and (b) a /// random number will requested to the Witnet Decentralized Oracle Network. /// @dev While request is being attended, tender will remain in 'Randomizing' status. function stopBatching() external payable virtual override nonReentrant onlyOwner inStatus(Witmons.Status.Batching) { // Send the request to Witnet and store the ID for later retrieval of the result: uint256 _witnetReward; (_state.witnetQueryId, _witnetReward) = _witnetPostRequest(_state.witnetRNG); // Transfers back unused funds: if (msg.value > _witnetReward) { payable(msg.sender).transfer(msg.value - _witnetReward); } } /// Starts hatching, which means that minting of creatures will start to be possible, /// until the hatching period expires (see `_state.expirationBlocks`). /// @dev During the hatching period the tender will remain in 'Hatching status'. Once the /// @dev hatching period expires, tender status will automatically change to 'Freezed'. function startHatching() external virtual override onlyOwner inStatus(Witmons.Status.Randomizing) { uint _queryId = _state.witnetQueryId; require( _witnetCheckResultAvailability(_queryId), "WitmonERC721: randomness not yet solved" ); Witnet.Result memory _result = witnet.readResponseResult(_queryId); if (_result.success) { bytes32 _randomness = _bytesToBytes32(witnet.asBytes(_result)); _state.hatchingBlock = block.number; _state.witnetRandomness = _randomness; emit WitnetResult(_randomness); } else { _state.witnetQueryId = 0; string memory _errorMessage; // Try to read the value as an error message, catch error bytes if read fails try witnet.asErrorMessage(_result) returns (Witnet.ErrorCodes, string memory e) { _errorMessage = e; } catch (bytes memory _errorBytes) { _errorMessage = string(_errorBytes); } emit WitnetError(_errorMessage); } } // ======================================================================== // --- Implementation of 'IWitmonSurrogates' ------------------------------- function mintCreature( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes calldata _signature ) external virtual override nonReentrant inStatus(Witmons.Status.Hatching) { _verifySignatorSignature( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Verify not already minted: require( _state.creatures[_eggIndex].tokenId == 0, "WitmonERC721: already minted" ); // Increment token supply: _state.totalSupply.increment(); uint256 _tokenId = _state.totalSupply.current(); // Fulfill creature data: Witmons.Creature memory _creature = _mintCreature( _tokenId, block.timestamp, // solhint-disable not-rely-on-time _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Write to storage: _state.creatures[_eggIndex] = _creature; _state.eggIndex_[_tokenId] = _eggIndex; // Mint the token: _safeMint(_eggOwner, _tokenId); emit NewCreature(_eggIndex, _tokenId); } function previewCreatureImage( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes calldata _signature ) external view virtual override inStatus(Witmons.Status.Hatching) returns (string memory) { _verifySignatorSignature( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Preview creature image: return IWitmonDecorator(_state.decorator).getCreatureImage( _mintCreature( 0, 0, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ) ); } // ======================================================================== // --- Implementation of 'IWitmonView' ------------------------------------ function getCreatureData(uint256 _eggIndex) public view override returns (Witmons.Creature memory) { return _state.creatures[_eggIndex]; } function getCreatureImage(uint256 _eggIndex) public view override returns (string memory) { require( getCreatureStatus(_eggIndex) == Witmons.CreatureStatus.Alive, "WitmonERC721: not alive yet" ); Witmons.Creature memory _creature = _state.creatures[_eggIndex]; return IWitmonDecorator(_state.decorator).getCreatureImage(_creature); } function getCreatureStatus(uint256 _eggIndex) public view virtual override returns (Witmons.CreatureStatus) { Witmons.Creature storage _creature = _state.creatures[_eggIndex]; if (_creature.eggPhenotype != bytes32(0)) { return Witmons.CreatureStatus.Alive; } else { Witmons.Status _tenderStatus = _state.status(); if (_tenderStatus == Witmons.Status.Hatching) { return Witmons.CreatureStatus.Hatching; } else if (_tenderStatus == Witmons.Status.Freezed) { return Witmons.CreatureStatus.Freezed; } else { return Witmons.CreatureStatus.Incubating; } } } function getDecorator() external view override returns (IWitmonDecorator) { return IWitmonDecorator(_state.decorator); } function getParameters() external view override returns (Witmons.Parameters memory) { return _state.params; } function getTokenEggIndex(uint256 _tokenId) external view override returns (uint256) { return _state.eggIndex_[_tokenId]; } function totalSupply() public view override returns ( uint256 _totalSupply ) { return ( _state.totalSupply.current() ); } function getStatus() public view override returns (Witmons.Status) { return _state.status(); } // ------------------------------------------------------------------------ // --- INTERNAL VIRTUAL METHODS ------------------------------------------- // ------------------------------------------------------------------------ function _mintCreature( uint256 _tokenId, uint256 _tokenInception, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes memory _signature ) internal view virtual returns (Witmons.Creature memory) { uint8 _percentile100 = _eggRanking > _totalClaimedEggs ? 100 : uint8((_eggRanking * 100) / _totalClaimedEggs) ; return Witmons.Creature({ tokenId: _tokenId, eggBirth: _tokenInception, eggCategory: _state.creatureCategory(_percentile100), eggIndex: _eggIndex, eggScore: _eggScore, eggRanking: _eggRanking, eggPhenotype: keccak256(abi.encodePacked( _signature, _state.witnetRandomness )) }); } function _verifySignatorSignature( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes memory _signature ) internal view virtual { // Verify signator: bytes32 _eggHash = keccak256(abi.encodePacked( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs )); require( Witmons.recoverAddr(_eggHash, _signature) == _state.params.signator, "WitmonERC721: bad signature" ); } // ------------------------------------------------------------------------ // --- PRIVATE METHODS ---------------------------------------------------- // ------------------------------------------------------------------------ function _bytesToBytes32(bytes memory _bb) private pure returns (bytes32 _r) { uint _len = _bb.length > 32 ? 32 : _bb.length; for (uint _i = 0; _i < _len; _i ++) { _r |= bytes32(_bb[_i] & 0xff) >> (_i * 8); } } }
File: contracts\interfaces\IWitmonAdmin.sol Witty Creatures 2.0 Token only-owner interface. Otherplane Labs, 2021.
interface IWitmonAdmin { function setDecorator(IWitmonDecorator _decorator) external; function setParameters( address _signator, uint8[] calldata _percentileMarks, uint256 _expirationBlocks ) external; function stopBatching() external payable; function startHatching() external; }
6,983,722
pragma solidity ^0.4.22; contract createInConstructor { Test2 test2; constructor() { test2 = new Test2(); } function add(int a, int b) returns(int){ //Simply add the two arguments and return return a+b; } } contract Test2 { constructor() { Test3 test3 = new Test3(); } function substract(int a, int b) returns(int){ //Simply add the two arguments and return return a-b; } } contract Test3 { function multiply(int a, int b) returns(int){ //Simply add the two arguments and return return a*b; } }
Simply add the two arguments and return
function substract(int a, int b) returns(int){
1,810,739
./full_match/137/0x1F5BCC2239649A698D89952959900492d8c41678/sources/home/roel/work/stamkracht/dutchdefi/src/contracts/Strategies/MaticAaveStrategy.sol
Repeatedly supplies and borrows {want} following the configured {borrowRate} and {borrowDepth} _amount amount of {want} to leverage/
function _leverage(uint256 _amount) internal { for (uint i = 0; i < borrowDepth; i++) { ILendingPool(lendingPool).deposit(want, _amount, address(this), 0); _amount = _amount.mul(borrowRate).div(100); ILendingPool(lendingPool).borrow(want, _amount, INTEREST_RATE_MODE, 0, address(this)); } reserves = reserves.add(_amount); }
3,763,705
pragma solidity 0.6.2; pragma experimental ABIEncoderV2; import 'RLP.sol'; import 'StorageStructure.sol'; /// @title CertiÐApp Smart Contract /// @author Soham Zemse from The EraSwap Team /// @notice This contract accepts certificates signed by multiple authorised signers contract CertiDApp is StorageStructure { using RLP for bytes; using RLP for RLP.RLPItem; /// @notice Sets up the CertiDApp manager address when deployed constructor() public { _changeManager(msg.sender); } /// @notice Used by present manager to change the manager wallet address /// @param _newManagerAddress Address of next manager wallet function changeManager(address _newManagerAddress) public onlyManager { _changeManager(_newManagerAddress); } /// @notice Used by manager to for to update KYC / verification status of Certifying Authorities /// @param _authorityAddress Wallet address of certifying authority /// @param _data RLP encoded KYC details of certifying authority function updateCertifyingAuthority( address _authorityAddress, bytes memory _data, AuthorityStatus _status ) public onlyManager { if(_data.length > 0) { certifyingAuthorities[_authorityAddress].data = _data; } certifyingAuthorities[_authorityAddress].status = _status; emit AuthorityStatusUpdated(_authorityAddress, _status); } /// @notice Used by Certifying Authorities to change their wallet (in case of theft). /// Migrating prevents any new certificate registrations signed by the old wallet. /// Already registered certificates would be valid. /// @param _newAuthorityAddress Next wallet address of the same certifying authority function migrateCertifyingAuthority( address _newAuthorityAddress ) public onlyAuthorisedCertifier { require( certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised , 'cannot migrate to an already authorised address' ); certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated; emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated); certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({ data: certifyingAuthorities[msg.sender].data, status: AuthorityStatus.Authorised }); emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised); emit AuthorityMigrated(msg.sender, _newAuthorityAddress); } /// @notice Used to submit a signed certificate to smart contract for adding it to storage. /// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. function registerCertificate( bytes memory _signedCertificate ) public returns ( bytes32 ) { (Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true); /// @notice Signers in this transaction bytes memory _newSigners = _certificateObj.signers; /// @notice If certificate already registered then signers can be updated. /// Initializing _updatedSigners with existing signers on blockchain if any. /// More signers would be appended to this in next 'for' loop. bytes memory _updatedSigners = certificates[_certificateHash].signers; /// @notice Check with every the new signer if it is not already included in storage. /// This is helpful when a same certificate is submitted again with more signatures, /// the contract will consider only new signers in that case. for(uint256 i = 0; i < _newSigners.length; i += 20) { address _signer; assembly { _signer := mload(add(_newSigners, add(0x14, i))) } if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) { _updatedSigners = abi.encodePacked(_updatedSigners, _signer); emit Certified( _certificateHash, _signer ); } } /// @notice check whether the certificate is freshly being registered. /// For new certificates, directly proceed with adding it. /// For existing certificates only update the signers if there are any new. if(certificates[_certificateHash].signers.length > 0) { require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers'); certificates[_certificateHash].signers = _updatedSigners; } else { certificates[_certificateHash] = _certificateObj; } return _certificateHash; } /// @notice Used by contract to seperate signers from certificate data. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. /// @param _allowedSignersOnly Should it consider only KYC approved signers ? /// @return _certificateObj Seperation of certificate data and signers (computed from signatures) /// @return _certificateHash Unique identifier of the certificate data function parseSignedCertificate( bytes memory _signedCertificate, bool _allowedSignersOnly ) public view returns ( Certificate memory _certificateObj, bytes32 _certificateHash ) { RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList(); _certificateObj.data = _certificateRLP[0].toRlpBytes(); _certificateHash = keccak256(abi.encodePacked( PERSONAL_PREFIX, _getBytesStr(_certificateObj.data.length), _certificateObj.data )); /// @notice loop through every signature and use eliptic curves cryptography to recover the /// address of the wallet used for signing the certificate. for(uint256 i = 1; i < _certificateRLP.length; i += 1) { bytes memory _signature = _certificateRLP[i].toBytes(); bytes32 _r; bytes32 _s; uint8 _v; assembly { let _pointer := add(_signature, 0x20) _r := mload(_pointer) _s := mload(add(_pointer, 0x20)) _v := byte(0, mload(add(_pointer, 0x40))) if lt(_v, 27) { _v := add(_v, 27) } } require(_v == 27 || _v == 28, 'invalid recovery value'); address _signer = ecrecover(_certificateHash, _v, _r, _s); require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique'); if(_allowedSignersOnly) { require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised'); } /// @dev packing every signer address into a single bytes value _certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer); } } /// @notice Used to change the manager /// @param _newManagerAddress Address of next manager wallet function _changeManager(address _newManagerAddress) private { manager = _newManagerAddress; emit ManagerUpdated(_newManagerAddress); } /// @notice Used to check whether an address exists in packed addresses bytes /// @param _signer Address of the signer wallet /// @param _packedSigners Bytes string of addressed packed together /// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string function _checkUniqueSigner( address _signer, bytes memory _packedSigners ) private pure returns (bool){ if(_packedSigners.length == 0) return true; require(_packedSigners.length % 20 == 0, 'invalid packed signers length'); address _tempSigner; /// @notice loop through every packed signer and check if signer exists in the packed signers for(uint256 i = 0; i < _packedSigners.length; i += 20) { assembly { _tempSigner := mload(add(_packedSigners, add(0x14, i))) } if(_tempSigner == _signer) return false; } return true; } /// @notice Used to get a number's utf8 representation /// @param i Integer /// @return utf8 representation of i function _getBytesStr(uint i) private pure returns (bytes memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return bstr; } } pragma solidity 0.6.2; import 'StorageStructure.sol'; /** * https://eips.ethereum.org/EIPS/eip-897 * Credits: OpenZeppelin Labs */ contract Proxy is StorageStructure { string public version; address public implementation; uint256 public constant proxyType = 2; /** * @dev This event will be emitted every time the implementation gets upgraded * @param version representing the version name of the upgraded implementation * @param implementation representing the address of the upgraded implementation */ event Upgraded(string version, address indexed implementation); /** * @dev constructor that sets the manager address */ constructor() public { manager = msg.sender; } /** * @dev Upgrades the implementation address * @param _newImplementation address of the new implementation */ function upgradeTo( string calldata _version, address _newImplementation ) external onlyManager { require(implementation != _newImplementation); _setImplementation(_version, _newImplementation); } /** * @dev Fallback function allowing to perform a delegatecall * to the given implementation. This function will return * whatever the implementation call returns */ fallback () external { address _impl = implementation; require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Sets the address of the current implementation * @param _newImp address of the new implementation */ function _setImplementation(string memory _version, address _newImp) internal { version = _version; implementation = _newImp; emit Upgraded(version, implementation); } } /** * Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol */ pragma solidity ^0.6.2; library RLP { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if(item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if(byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint result; uint memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } pragma solidity 0.6.2; /// @title Storage Structure for CertiÐApp Certificate Contract /// @dev This contract is intended to be inherited in Proxy and Implementation contracts. contract StorageStructure { enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended } struct Certificate { bytes data; bytes signers; } struct CertifyingAuthority { bytes data; AuthorityStatus status; } mapping(bytes32 => Certificate) public certificates; mapping(address => CertifyingAuthority) public certifyingAuthorities; mapping(bytes32 => bytes32) extraData; address public manager; bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n"; event ManagerUpdated( address _newManager ); event Certified( bytes32 indexed _certificateHash, address indexed _certifyingAuthority ); event AuthorityStatusUpdated( address indexed _certifyingAuthority, AuthorityStatus _newStatus ); event AuthorityMigrated( address indexed _oldAddress, address indexed _newAddress ); modifier onlyManager() { require(msg.sender == manager, 'only manager can call'); _; } modifier onlyAuthorisedCertifier() { require( certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised , 'only authorised certifier can call' ); _; } } pragma solidity 0.6.2; pragma experimental ABIEncoderV2; import 'RLP.sol'; import 'StorageStructure.sol'; /// @title CertiÐApp Smart Contract /// @author Soham Zemse from The EraSwap Team /// @notice This contract accepts certificates signed by multiple authorised signers contract CertiDApp is StorageStructure { using RLP for bytes; using RLP for RLP.RLPItem; /// @notice Sets up the CertiDApp manager address when deployed constructor() public { _changeManager(msg.sender); } /// @notice Used by present manager to change the manager wallet address /// @param _newManagerAddress Address of next manager wallet function changeManager(address _newManagerAddress) public onlyManager { _changeManager(_newManagerAddress); } /// @notice Used by manager to for to update KYC / verification status of Certifying Authorities /// @param _authorityAddress Wallet address of certifying authority /// @param _data RLP encoded KYC details of certifying authority function updateCertifyingAuthority( address _authorityAddress, bytes memory _data, AuthorityStatus _status ) public onlyManager { if(_data.length > 0) { certifyingAuthorities[_authorityAddress].data = _data; } certifyingAuthorities[_authorityAddress].status = _status; emit AuthorityStatusUpdated(_authorityAddress, _status); } /// @notice Used by Certifying Authorities to change their wallet (in case of theft). /// Migrating prevents any new certificate registrations signed by the old wallet. /// Already registered certificates would be valid. /// @param _newAuthorityAddress Next wallet address of the same certifying authority function migrateCertifyingAuthority( address _newAuthorityAddress ) public onlyAuthorisedCertifier { require( certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised , 'cannot migrate to an already authorised address' ); certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated; emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated); certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({ data: certifyingAuthorities[msg.sender].data, status: AuthorityStatus.Authorised }); emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised); emit AuthorityMigrated(msg.sender, _newAuthorityAddress); } /// @notice Used to submit a signed certificate to smart contract for adding it to storage. /// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. function registerCertificate( bytes memory _signedCertificate ) public returns ( bytes32 ) { (Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true); /// @notice Signers in this transaction bytes memory _newSigners = _certificateObj.signers; /// @notice If certificate already registered then signers can be updated. /// Initializing _updatedSigners with existing signers on blockchain if any. /// More signers would be appended to this in next 'for' loop. bytes memory _updatedSigners = certificates[_certificateHash].signers; /// @notice Check with every the new signer if it is not already included in storage. /// This is helpful when a same certificate is submitted again with more signatures, /// the contract will consider only new signers in that case. for(uint256 i = 0; i < _newSigners.length; i += 20) { address _signer; assembly { _signer := mload(add(_newSigners, add(0x14, i))) } if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) { _updatedSigners = abi.encodePacked(_updatedSigners, _signer); emit Certified( _certificateHash, _signer ); } } /// @notice check whether the certificate is freshly being registered. /// For new certificates, directly proceed with adding it. /// For existing certificates only update the signers if there are any new. if(certificates[_certificateHash].signers.length > 0) { require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers'); certificates[_certificateHash].signers = _updatedSigners; } else { certificates[_certificateHash] = _certificateObj; } return _certificateHash; } /// @notice Used by contract to seperate signers from certificate data. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. /// @param _allowedSignersOnly Should it consider only KYC approved signers ? /// @return _certificateObj Seperation of certificate data and signers (computed from signatures) /// @return _certificateHash Unique identifier of the certificate data function parseSignedCertificate( bytes memory _signedCertificate, bool _allowedSignersOnly ) public view returns ( Certificate memory _certificateObj, bytes32 _certificateHash ) { RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList(); _certificateObj.data = _certificateRLP[0].toRlpBytes(); _certificateHash = keccak256(abi.encodePacked( PERSONAL_PREFIX, _getBytesStr(_certificateObj.data.length), _certificateObj.data )); /// @notice loop through every signature and use eliptic curves cryptography to recover the /// address of the wallet used for signing the certificate. for(uint256 i = 1; i < _certificateRLP.length; i += 1) { bytes memory _signature = _certificateRLP[i].toBytes(); bytes32 _r; bytes32 _s; uint8 _v; assembly { let _pointer := add(_signature, 0x20) _r := mload(_pointer) _s := mload(add(_pointer, 0x20)) _v := byte(0, mload(add(_pointer, 0x40))) if lt(_v, 27) { _v := add(_v, 27) } } require(_v == 27 || _v == 28, 'invalid recovery value'); address _signer = ecrecover(_certificateHash, _v, _r, _s); require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique'); if(_allowedSignersOnly) { require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised'); } /// @dev packing every signer address into a single bytes value _certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer); } } /// @notice Used to change the manager /// @param _newManagerAddress Address of next manager wallet function _changeManager(address _newManagerAddress) private { manager = _newManagerAddress; emit ManagerUpdated(_newManagerAddress); } /// @notice Used to check whether an address exists in packed addresses bytes /// @param _signer Address of the signer wallet /// @param _packedSigners Bytes string of addressed packed together /// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string function _checkUniqueSigner( address _signer, bytes memory _packedSigners ) private pure returns (bool){ if(_packedSigners.length == 0) return true; require(_packedSigners.length % 20 == 0, 'invalid packed signers length'); address _tempSigner; /// @notice loop through every packed signer and check if signer exists in the packed signers for(uint256 i = 0; i < _packedSigners.length; i += 20) { assembly { _tempSigner := mload(add(_packedSigners, add(0x14, i))) } if(_tempSigner == _signer) return false; } return true; } /// @notice Used to get a number's utf8 representation /// @param i Integer /// @return utf8 representation of i function _getBytesStr(uint i) private pure returns (bytes memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return bstr; } } pragma solidity 0.6.2; import 'StorageStructure.sol'; /** * https://eips.ethereum.org/EIPS/eip-897 * Credits: OpenZeppelin Labs */ contract Proxy is StorageStructure { string public version; address public implementation; uint256 public constant proxyType = 2; /** * @dev This event will be emitted every time the implementation gets upgraded * @param version representing the version name of the upgraded implementation * @param implementation representing the address of the upgraded implementation */ event Upgraded(string version, address indexed implementation); /** * @dev constructor that sets the manager address */ constructor() public { manager = msg.sender; } /** * @dev Upgrades the implementation address * @param _newImplementation address of the new implementation */ function upgradeTo( string calldata _version, address _newImplementation ) external onlyManager { require(implementation != _newImplementation); _setImplementation(_version, _newImplementation); } /** * @dev Fallback function allowing to perform a delegatecall * to the given implementation. This function will return * whatever the implementation call returns */ fallback () external { address _impl = implementation; require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Sets the address of the current implementation * @param _newImp address of the new implementation */ function _setImplementation(string memory _version, address _newImp) internal { version = _version; implementation = _newImp; emit Upgraded(version, implementation); } } /** * Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol */ pragma solidity ^0.6.2; library RLP { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if(item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if(byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint result; uint memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } pragma solidity 0.6.2; /// @title Storage Structure for CertiÐApp Certificate Contract /// @dev This contract is intended to be inherited in Proxy and Implementation contracts. contract StorageStructure { enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended } struct Certificate { bytes data; bytes signers; } struct CertifyingAuthority { bytes data; AuthorityStatus status; } mapping(bytes32 => Certificate) public certificates; mapping(address => CertifyingAuthority) public certifyingAuthorities; mapping(bytes32 => bytes32) extraData; address public manager; bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n"; event ManagerUpdated( address _newManager ); event Certified( bytes32 indexed _certificateHash, address indexed _certifyingAuthority ); event AuthorityStatusUpdated( address indexed _certifyingAuthority, AuthorityStatus _newStatus ); event AuthorityMigrated( address indexed _oldAddress, address indexed _newAddress ); modifier onlyManager() { require(msg.sender == manager, 'only manager can call'); _; } modifier onlyAuthorisedCertifier() { require( certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised , 'only authorised certifier can call' ); _; } } pragma solidity 0.6.2; pragma experimental ABIEncoderV2; import 'RLP.sol'; import 'StorageStructure.sol'; /// @title CertiÐApp Smart Contract /// @author Soham Zemse from The EraSwap Team /// @notice This contract accepts certificates signed by multiple authorised signers contract CertiDApp is StorageStructure { using RLP for bytes; using RLP for RLP.RLPItem; /// @notice Sets up the CertiDApp manager address when deployed constructor() public { _changeManager(msg.sender); } /// @notice Used by present manager to change the manager wallet address /// @param _newManagerAddress Address of next manager wallet function changeManager(address _newManagerAddress) public onlyManager { _changeManager(_newManagerAddress); } /// @notice Used by manager to for to update KYC / verification status of Certifying Authorities /// @param _authorityAddress Wallet address of certifying authority /// @param _data RLP encoded KYC details of certifying authority function updateCertifyingAuthority( address _authorityAddress, bytes memory _data, AuthorityStatus _status ) public onlyManager { if(_data.length > 0) { certifyingAuthorities[_authorityAddress].data = _data; } certifyingAuthorities[_authorityAddress].status = _status; emit AuthorityStatusUpdated(_authorityAddress, _status); } /// @notice Used by Certifying Authorities to change their wallet (in case of theft). /// Migrating prevents any new certificate registrations signed by the old wallet. /// Already registered certificates would be valid. /// @param _newAuthorityAddress Next wallet address of the same certifying authority function migrateCertifyingAuthority( address _newAuthorityAddress ) public onlyAuthorisedCertifier { require( certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised , 'cannot migrate to an already authorised address' ); certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated; emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated); certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({ data: certifyingAuthorities[msg.sender].data, status: AuthorityStatus.Authorised }); emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised); emit AuthorityMigrated(msg.sender, _newAuthorityAddress); } /// @notice Used to submit a signed certificate to smart contract for adding it to storage. /// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. function registerCertificate( bytes memory _signedCertificate ) public returns ( bytes32 ) { (Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true); /// @notice Signers in this transaction bytes memory _newSigners = _certificateObj.signers; /// @notice If certificate already registered then signers can be updated. /// Initializing _updatedSigners with existing signers on blockchain if any. /// More signers would be appended to this in next 'for' loop. bytes memory _updatedSigners = certificates[_certificateHash].signers; /// @notice Check with every the new signer if it is not already included in storage. /// This is helpful when a same certificate is submitted again with more signatures, /// the contract will consider only new signers in that case. for(uint256 i = 0; i < _newSigners.length; i += 20) { address _signer; assembly { _signer := mload(add(_newSigners, add(0x14, i))) } if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) { _updatedSigners = abi.encodePacked(_updatedSigners, _signer); emit Certified( _certificateHash, _signer ); } } /// @notice check whether the certificate is freshly being registered. /// For new certificates, directly proceed with adding it. /// For existing certificates only update the signers if there are any new. if(certificates[_certificateHash].signers.length > 0) { require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers'); certificates[_certificateHash].signers = _updatedSigners; } else { certificates[_certificateHash] = _certificateObj; } return _certificateHash; } /// @notice Used by contract to seperate signers from certificate data. /// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard. /// @param _allowedSignersOnly Should it consider only KYC approved signers ? /// @return _certificateObj Seperation of certificate data and signers (computed from signatures) /// @return _certificateHash Unique identifier of the certificate data function parseSignedCertificate( bytes memory _signedCertificate, bool _allowedSignersOnly ) public view returns ( Certificate memory _certificateObj, bytes32 _certificateHash ) { RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList(); _certificateObj.data = _certificateRLP[0].toRlpBytes(); _certificateHash = keccak256(abi.encodePacked( PERSONAL_PREFIX, _getBytesStr(_certificateObj.data.length), _certificateObj.data )); /// @notice loop through every signature and use eliptic curves cryptography to recover the /// address of the wallet used for signing the certificate. for(uint256 i = 1; i < _certificateRLP.length; i += 1) { bytes memory _signature = _certificateRLP[i].toBytes(); bytes32 _r; bytes32 _s; uint8 _v; assembly { let _pointer := add(_signature, 0x20) _r := mload(_pointer) _s := mload(add(_pointer, 0x20)) _v := byte(0, mload(add(_pointer, 0x40))) if lt(_v, 27) { _v := add(_v, 27) } } require(_v == 27 || _v == 28, 'invalid recovery value'); address _signer = ecrecover(_certificateHash, _v, _r, _s); require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique'); if(_allowedSignersOnly) { require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised'); } /// @dev packing every signer address into a single bytes value _certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer); } } /// @notice Used to change the manager /// @param _newManagerAddress Address of next manager wallet function _changeManager(address _newManagerAddress) private { manager = _newManagerAddress; emit ManagerUpdated(_newManagerAddress); } /// @notice Used to check whether an address exists in packed addresses bytes /// @param _signer Address of the signer wallet /// @param _packedSigners Bytes string of addressed packed together /// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string function _checkUniqueSigner( address _signer, bytes memory _packedSigners ) private pure returns (bool){ if(_packedSigners.length == 0) return true; require(_packedSigners.length % 20 == 0, 'invalid packed signers length'); address _tempSigner; /// @notice loop through every packed signer and check if signer exists in the packed signers for(uint256 i = 0; i < _packedSigners.length; i += 20) { assembly { _tempSigner := mload(add(_packedSigners, add(0x14, i))) } if(_tempSigner == _signer) return false; } return true; } /// @notice Used to get a number's utf8 representation /// @param i Integer /// @return utf8 representation of i function _getBytesStr(uint i) private pure returns (bytes memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return bstr; } } pragma solidity 0.6.2; import 'StorageStructure.sol'; /** * https://eips.ethereum.org/EIPS/eip-897 * Credits: OpenZeppelin Labs */ contract Proxy is StorageStructure { string public version; address public implementation; uint256 public constant proxyType = 2; /** * @dev This event will be emitted every time the implementation gets upgraded * @param version representing the version name of the upgraded implementation * @param implementation representing the address of the upgraded implementation */ event Upgraded(string version, address indexed implementation); /** * @dev constructor that sets the manager address */ constructor() public { manager = msg.sender; } /** * @dev Upgrades the implementation address * @param _newImplementation address of the new implementation */ function upgradeTo( string calldata _version, address _newImplementation ) external onlyManager { require(implementation != _newImplementation); _setImplementation(_version, _newImplementation); } /** * @dev Fallback function allowing to perform a delegatecall * to the given implementation. This function will return * whatever the implementation call returns */ fallback () external { address _impl = implementation; require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Sets the address of the current implementation * @param _newImp address of the new implementation */ function _setImplementation(string memory _version, address _newImp) internal { version = _version; implementation = _newImp; emit Upgraded(version, implementation); } } /** * Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol */ pragma solidity ^0.6.2; library RLP { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if(item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if(byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint result; uint memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } pragma solidity 0.6.2; /// @title Storage Structure for CertiÐApp Certificate Contract /// @dev This contract is intended to be inherited in Proxy and Implementation contracts. contract StorageStructure { enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended } struct Certificate { bytes data; bytes signers; } struct CertifyingAuthority { bytes data; AuthorityStatus status; } mapping(bytes32 => Certificate) public certificates; mapping(address => CertifyingAuthority) public certifyingAuthorities; mapping(bytes32 => bytes32) extraData; address public manager; bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n"; event ManagerUpdated( address _newManager ); event Certified( bytes32 indexed _certificateHash, address indexed _certifyingAuthority ); event AuthorityStatusUpdated( address indexed _certifyingAuthority, AuthorityStatus _newStatus ); event AuthorityMigrated( address indexed _oldAddress, address indexed _newAddress ); modifier onlyManager() { require(msg.sender == manager, 'only manager can call'); _; } modifier onlyAuthorisedCertifier() { require( certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised , 'only authorised certifier can call' ); _; } }
return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; }
6,458,758
./full_match/5/0x213816e69A21320D086a40Af97A5151445e8bFDE/sources/contracts/DeedRenting.sol
returns true if the address can manage Deed Provisioning/
function isProvisioningManager( address _address, uint256 _deedId ) public view override returns (bool) { for (uint i = 0; i < leases[_deedId].length;i++) { uint256 leaseId = leases[_deedId][i]; DeedLease storage lease = deedLeases[leaseId]; if (lease.leaseStartDate <= block.timestamp && lease.leaseEndDate > block.timestamp) { return lease.tenant == _address; } } return deed.balanceOf(_address, _deedId) > 0; }
7,060,080
./full_match/80001/0xD98b30b1C64524fDA9Cc427d61871264620281eA/sources/Aviculture.sol
See {IERC1155-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public payable virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); }
5,648,888
./partial_match/1/0x4F1982dcbB37021eA9F8Ed5dFa1C5a4b73f92665/sources/contracts/proxy/ForwardTarget.sol
Storage initialization of cloned contract This is used to initialize the storage of the forwarded contract, and should (typically) copy or repeat any work that would normally be done in the constructor of the proxied contract. Implementations of ForwardTarget should override this function, and chain to super.initialize(_self). _self The address of the original contract instance (the one being forwarded to)./
function initialize(address _self) public virtual onlyConstruction { address _implAddress = address(ForwardTarget(_self).implementation()); require( _implAddress != address(0), "initialization failure: nothing to implement" ); setImplementation(_implAddress); }
15,925,949
./full_match/1/0x820A4AeeDA79fD49b82dA730cdA9B952FB649D39/sources/contracts/EtherFreakers.sol
Birth a new freaker, given enough energy. to Recipient's address/ Roughly pick species 0 (1x) -> fortune / offense 1 (2x) -> fortune / defense 2 (2x) -> fortune / agility 3 (3x) -> offense / defense 4 (3x) -> defense / offense 5 (4x) -> agility / offense 6 (4x) -> agility / defense 7 (1x) -> defense / agility pick stamina: [0, 9] pick fortune, agility, offense, defense based on species: [1, 10] primary = 300% max secondary = 200% max
function birthTo(address payable to) payable public { uint256 middle = middlePrice(); require(msg.value > middle * 1005 / 1000, "Not enough energy"); uint128 freakerId = numTokens++; uint8 speciesDie = uint8(_randomishIntLessThan("species", 20)); uint8 species = ( (speciesDie < 1 ? 0 : (speciesDie < 3 ? 1 : (speciesDie < 5 ? 2 : (speciesDie < 8 ? 3 : (speciesDie < 11 ? 4 : (speciesDie < 15 ? 5 : (speciesDie < 19 ? 6 : 7)))))))); uint8 stamina = uint8(_randomishIntLessThan("stamina", 10)); uint8 fortune = uint8(_randomishIntLessThan("fortune", species < 3 ? 30 : 10) + 1); uint8 agility = uint8(_randomishIntLessThan("agility", (species == 5 || species == 6 ? 30 : (species == 2 || species == 7 ? 20 : 10))) + 1); uint8 offense = uint8(_randomishIntLessThan("offense", (species == 3 ? 30 : (species == 0 || species == 4 || species == 5 ? 20 : 10))) + 1); uint8 defense = uint8(_randomishIntLessThan("defense", (species == 4 || species == 7 ? 30 : (species == 1 || species == 4 || species == 6 ? 20 : 10))) + 1); Freaker memory freaker = Freaker({ species: species, stamina: stamina, fortune: fortune, agility: agility, offense: offense, defense: defense }); freakers[freakerId] = freaker; uint128 value = uint128(msg.value); uint128 half = value / 2; _dissipateEnergyIntoPool(half); energyBalances[freakerId] = EnergyBalance({ basic: half, index: freakerIndex }); totalFortune += fortune; birthCertificates.push(msg.value); emit Born(to, value, freakerId, freaker); _safeMint(to, freakerId, ""); }
3,066,549
/** *Submitted for verification at Etherscan.io on 2020-11-01 */ pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity >=0.6.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping(address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor() internal { _addMinter(_msgSender()); } modifier onlyMinter() { require( isMinter(_msgSender()), "MinterRole: caller does not have the Minter role" ); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract CanTransferRole is Context { using Roles for Roles.Role; event CanTransferAdded(address indexed account); event CanTransferRemoved(address indexed account); Roles.Role private _canTransfer; constructor() internal { _addCanTransfer(_msgSender()); } modifier onlyCanTransfer() { require( canTransfer(_msgSender()), "CanTransferRole: caller does not have the CanTransfer role" ); _; } function canTransfer(address account) public view returns (bool) { return _canTransfer.has(account); } function addCanTransfer(address account) public onlyCanTransfer { _addCanTransfer(account); } function renounceCanTransfer() public { _removeCanTransfer(_msgSender()); } function _addCanTransfer(address account) internal { _canTransfer.add(account); emit CanTransferAdded(account); } function _removeCanTransfer(address account) internal { _canTransfer.remove(account); emit CanTransferRemoved(account); } } contract ToshiCash is Ownable, MinterRole, CanTransferRole { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); mapping(address => uint256) private _balances; string public name = "ToshiCash"; string public symbol = "ToshiCash"; uint8 public decimals = 18; uint256 public totalSupply; uint256 public totalClaimed; uint256 public totalMinted; constructor() public { } function addClaimed(uint256 amount) internal { totalClaimed = totalClaimed.add(amount); } function addMinted(uint256 amount) internal { totalMinted = totalMinted.add(amount); } /** * @dev Claiming is white-listed to specific minter addresses for now to limit transfers. */ function claim(address to, uint256 amount) public onlyCanTransfer { transfer(to, amount); addClaimed(amount); } /** * @dev Transferring is white-listed to specific minter addresses for now. */ function transfer(address to, uint256 amount) public returns (bool) { require( amount <= _balances[msg.sender], "ToshiCash: Cannot transfer more than balance" ); _balances[msg.sender] = _balances[msg.sender].sub(amount); _balances[to] = _balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } /** * @dev Transferring is white-listed to specific minter addresses for now. */ function transferFrom( address from, address to, uint256 amount ) public onlyCanTransfer returns (bool) { require( amount <= _balances[from], "ToshiCash: Cannot transfer more than balance" ); _balances[from] = _balances[from].sub(amount); _balances[to] = _balances[to].add(amount); emit Transfer(from, to, amount); return true; } /** * @dev Gets the balance of the specified address. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Minting is white-listed to specific minter addresses for now. */ function mint(address to, uint256 amount) public onlyMinter { _mint(to, amount); addMinted(amount); } /** * @dev Burning is white-listed to specific minter addresses for now. */ function burn(address from, uint256 value) public onlyCanTransfer { require( _balances[from] >= value, "ToshiCash: Cannot burn more than the address balance" ); _burn(from, value); } /** * @dev Internal function that creates an amount of the token and assigns it to an account. * This encapsulates the modification of balances such that the proper events are emitted. * @param to The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address to, uint256 amount) internal { require(to != address(0), "ToshiCash: mint to the zero address"); totalSupply = totalSupply.add(amount); _balances[to] = _balances[to].add(amount); emit Transfer(address(0), to, amount); } /** * @dev Internal function that destroys an amount of the token of a given address. * @param from The account whose tokens will be destroyed. * @param amount The amount that will be destroyed. */ function _burn(address from, uint256 amount) internal { require(from != address(0), "ToshiCash: burn from the zero address"); totalSupply = totalSupply.sub(amount); _balances[from] = _balances[from].sub(amount); emit Transfer(from, address(0), amount); } }
Transferring is white-listed to specific minter addresses for now./
function transferFrom( address from, address to, uint256 amount ) public onlyCanTransfer returns (bool) { require( amount <= _balances[from], "ToshiCash: Cannot transfer more than balance" ); _balances[from] = _balances[from].sub(amount); _balances[to] = _balances[to].add(amount); emit Transfer(from, to, amount); return true; }
518,513
./full_match/1/0x2ee2bf09A6e559047D26df6F690435E746072e73/sources/browser/rooktest.sol
This interfaces defines the functions of the KeeperDAO liquidity pool that our contract needs to know about. The only function we need is the borrow function, which allows us to take flash loans from the liquidity pool.
interface LiquidityPool { function borrow( address _token, uint256 _amount, bytes calldata _data ) external; }
2,922,320
./full_match/42220/0x6ea01ea80FeB4313C3329e6e9fcA751CCb2cF323/sources/out/ManagedPoolFactory_flat.sol
Interface for ExternalWeightedMath, a contract-wrapper for Weighted Math, Joins and Exits./
interface IExternalWeightedMath { function calculateInvariant(uint256[] memory normalizedWeights, uint256[] memory balances) external pure returns (uint256); function calcOutGivenIn( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountIn ) external pure returns (uint256); function calcInGivenOut( uint256 balanceIn, uint256 weightIn, uint256 balanceOut, uint256 weightOut, uint256 amountOut ) external pure returns (uint256); function calcBptOutGivenExactTokensIn( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcBptOutGivenExactTokenIn( uint256 balance, uint256 normalizedWeight, uint256 amountIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcTokenInGivenExactBptOut( uint256 balance, uint256 normalizedWeight, uint256 bptAmountOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcAllTokensInGivenExactBptOut( uint256[] memory balances, uint256 bptAmountOut, uint256 totalBPT ) external pure returns (uint256[] memory); function calcBptInGivenExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory amountsOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcBptInGivenExactTokenOut( uint256 balance, uint256 normalizedWeight, uint256 amountOut, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcTokenOutGivenExactBptIn( uint256 balance, uint256 normalizedWeight, uint256 bptAmountIn, uint256 bptTotalSupply, uint256 swapFeePercentage ) external pure returns (uint256); function calcTokensOutGivenExactBptIn( uint256[] memory balances, uint256 bptAmountIn, uint256 totalBPT ) external pure returns (uint256[] memory); function calcBptOutAddToken(uint256 totalSupply, uint256 normalizedWeight) external pure returns (uint256); function joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, uint256 totalSupply, uint256 swapFeePercentage, bytes memory userData ) external pure returns (uint256, uint256[] memory); function joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 totalSupply, uint256 swapFeePercentage, bytes memory userData ) external pure returns (uint256, uint256[] memory); function joinAllTokensInForExactBPTOut( uint256[] memory balances, uint256 totalSupply, bytes memory userData ) external pure returns (uint256 bptAmountOut, uint256[] memory amountsIn); function exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 totalSupply, uint256 swapFeePercentage, bytes memory userData ) external pure returns (uint256, uint256[] memory); function exitExactBPTInForTokensOut( uint256[] memory balances, uint256 totalSupply, bytes memory userData ) external pure returns (uint256 bptAmountIn, uint256[] memory amountsOut); function exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, uint256 totalSupply, uint256 swapFeePercentage, bytes memory userData ) external pure returns (uint256, uint256[] memory); }
16,352,655
./full_match/4/0xA1Ca72cC58E97F5b25785A05BDdC2CcA6736175D/sources/SnakesHaveLegs.sol
From The HashMarks https:etherscan.io/address/0xc2c747e0f7004f9e8817db2ca4997657a7746928codeF7L612
function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if( ) return false; lastChar = char; } return true; }
701,740
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.4.22 <0.9.0; interface IEthLocker { function initDispatcher(address targetAddr) external; function lockEth(uint256 amount, string memory accountId) external; function unlockEth(bytes memory proofData, uint64 proofBlockHeight) external; function burnResult(bytes memory proofData, uint64 proofBlockHeight) external view returns (address); // In case of loss function deposit() external payable; // For investments function setReserveRatio(uint16 ratio) external; function setMinHarvest(uint16 ratio) external; function depositToStrategy(address strategyAddr, uint256 amount) external; function depositAllToStrategy(address strategyAddr) external; function withdrawFromStrategy(address strategyAddr, uint256 amount) external; function withdrawAllFromStrategy(address strategyAddr) external; // Rewards function setRewardsRatio(uint16 ratio) external; function transferRewards(address relayRegistryAddr) external; function harvest(address strategyAddr) external; function harvestAll() external; }
In case of loss For investments Rewards
interface IEthLocker { function initDispatcher(address targetAddr) external; function lockEth(uint256 amount, string memory accountId) external; function unlockEth(bytes memory proofData, uint64 proofBlockHeight) external; function burnResult(bytes memory proofData, uint64 proofBlockHeight) external view returns (address); function deposit() external payable; function setReserveRatio(uint16 ratio) external; function setMinHarvest(uint16 ratio) external; function depositToStrategy(address strategyAddr, uint256 amount) external; function depositAllToStrategy(address strategyAddr) external; function withdrawFromStrategy(address strategyAddr, uint256 amount) external; function withdrawAllFromStrategy(address strategyAddr) external; function setRewardsRatio(uint16 ratio) external; function transferRewards(address relayRegistryAddr) external; function harvest(address strategyAddr) external; function harvestAll() external; pragma solidity >=0.4.22 <0.9.0; }
12,665,532
./partial_match/1/0x48b95265749775310B77418Ff6f9675396ABE1e8/sources/@yield-protocol/yieldspace-tv/src/Pool/Pool.sol
/ Buy base with fyToken. The trader needs to have transferred in the necessary amount of fyTokens in advance. to Wallet receiving the base being bought. baseOut Amount of base being bought that will be deposited in `to` wallet. max This has been deprecated and was left in for backwards compatibility. return fyTokenIn Amount of fyToken that will be taken from caller. Calculate trade and cache values Checks
function buyBase( address to, uint128 baseOut, uint128 max ) external virtual override returns (uint128 fyTokenIn) { uint128 fyTokenBalance = _getFYTokenBalance(); Cache memory cache = _getCache(); uint128 sharesOut = _wrapPreview(baseOut).u128(); fyTokenIn = _buyBasePreview(sharesOut, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee)); if (fyTokenBalance - cache.fyTokenCached < fyTokenIn) { revert NotEnoughFYTokenIn(fyTokenBalance - cache.fyTokenCached, fyTokenIn); } cache.sharesCached - sharesOut, cache.fyTokenCached + fyTokenIn, cache.sharesCached, cache.fyTokenCached ); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); }
4,008,286
./partial_match/1/0xF2d93df6fB89e51756d915004211a0a29755BB2b/sources/Include.sol
Contract initializer. called once by the factory at time of deployment/
function __Governable_init_unchained(address governor_) virtual internal initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); }
10,999,747
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import '@openzeppelin/contracts/security/Pausable.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import '@openzeppelin/contracts/utils/math/Math.sol'; /* * @title Staking for Pixelvault ERC721 tokens * * @author Niftydude */ contract ComicStaking is Ownable, IERC721Receiver, Pausable, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; IERC20 public immutable rewardToken; IERC721 public immutable stakedTokenContract; uint256 constant MAX_REWARD_CHANGES = 2000; uint128 public rewardPerBlock; uint128 public lockupPeriod = 2592000; // 30 days struct Stake { uint128 lockupExpires; uint128 lastClaimedBlock; } struct RewardChanged { uint128 block; uint128 rewardPerBlock; } RewardChanged[] rewardChanges; event Staked(address indexed account, uint256[] tokenIds); event Unstaked(address indexed account, uint256[] tokenIds); event RewardsClaimed(address indexed account, uint256 amount); event RewardsChanged(uint128 indexed rewardPerBlock); event LockupPeriodChanged(uint128 indexed lockupPeriod); mapping(uint256 => Stake) public stakes; mapping(address => EnumerableSet.UintSet) private stakedTokens; constructor(address _rewardTokenContract, address _stakedTokenContract, uint128 _rewardPerBlock) { rewardToken = IERC20(_rewardTokenContract); stakedTokenContract = IERC721(_stakedTokenContract); rewardPerBlock = _rewardPerBlock; rewardChanges.push(RewardChanged(uint128(block.number), _rewardPerBlock)); } /** * @notice pause staking, unstaking and claiming rewards */ function pause() external onlyOwner { _pause(); } /** * @notice unpause staking, unstaking and claiming rewards */ function unpause() external onlyOwner { _unpause(); } /** * @notice set ERC20 reward amount per block * * @param _rewardPerBlock the reward amount */ function setRewardsPerBlock(uint128 _rewardPerBlock) external onlyOwner { require(rewardChanges.length < MAX_REWARD_CHANGES, "Set rewards: Max reward changes reached"); rewardPerBlock = _rewardPerBlock; rewardChanges.push(RewardChanged(uint128(block.number), _rewardPerBlock)); emit RewardsChanged(_rewardPerBlock); } /** * @notice set lockup period in seconds. * unstaking or claiming rewards not allowed until lockup period expired * * @param _lockupPeriod length of the lockup period in seconds */ function setLockupPeriod(uint128 _lockupPeriod) external onlyOwner { lockupPeriod = _lockupPeriod; emit LockupPeriodChanged(_lockupPeriod); } /** * @notice withdraw reward tokens owned by staking contract * * @param to the token ids to unstake * @param amount the amount of tokens to withdraw */ function withdraw(address to, uint256 amount) external onlyOwner { require( rewardToken.balanceOf(address(this)) >= amount, "Withdraw: balance exceeded"); rewardToken.transfer(to, amount); } /** * @notice stake given token ids for specified user * * @param tokenIds the token ids to stake */ function stake(uint256[] calldata tokenIds) external whenNotPaused nonReentrant { require(tokenIds.length <= 40 && tokenIds.length > 0, "Stake: amount prohibited"); for (uint256 i; i < tokenIds.length; i++) { require(stakedTokenContract.ownerOf(tokenIds[i]) == msg.sender, "Stake: sender not owner"); stakedTokenContract.safeTransferFrom(msg.sender, address(this), tokenIds[i]); stakes[tokenIds[i]] = Stake(uint128(block.timestamp + lockupPeriod), uint128(block.number)); stakedTokens[msg.sender].add(tokenIds[i]); } emit Staked(msg.sender, tokenIds); } /** * @notice unstake given token ids and claim rewards * * @param tokenIds the token ids to unstake */ function unstake(uint256[] calldata tokenIds) external whenNotPaused nonReentrant { require(tokenIds.length <= 40 && tokenIds.length > 0, "Unstake: amount prohibited"); uint256 rewards; for (uint256 i; i < tokenIds.length; i++) { require( stakedTokens[msg.sender].contains(tokenIds[i]), "Unstake: token not staked" ); require( stakes[tokenIds[i]].lockupExpires < block.timestamp, "Unstake: lockup period not expired" ); rewards += calculateRewards(tokenIds[i]); stakedTokens[msg.sender].remove(tokenIds[i]); delete stakes[tokenIds[i]]; stakedTokenContract.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } rewardToken.transfer(msg.sender, rewards); emit Unstaked(msg.sender, tokenIds); emit RewardsClaimed(msg.sender, rewards); } /** * @notice unstake given token ids and forfeit rewards * * @param tokenIds the token ids to unstake */ function exitWithoutRewards(uint256[] calldata tokenIds) external whenNotPaused nonReentrant { require(tokenIds.length <= 40 && tokenIds.length > 0, "Unstake: amount prohibited"); for (uint256 i; i < tokenIds.length; i++) { require( stakedTokens[msg.sender].contains(tokenIds[i]), "Unstake: token not staked" ); stakedTokens[msg.sender].remove(tokenIds[i]); delete stakes[tokenIds[i]]; stakedTokenContract.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } emit Unstaked(msg.sender, tokenIds); } /** * @notice claim rewards for given token ids * * @param tokenIds the token ids to claim for */ function claimRewards(uint256[] calldata tokenIds) external whenNotPaused { require(tokenIds.length > 0, "ClaimRewards: missing token ids"); uint256 rewards; for (uint256 i; i < tokenIds.length; i++) { require( stakedTokens[msg.sender].contains(tokenIds[i]), "ClaimRewards: token not staked" ); require( stakes[tokenIds[i]].lockupExpires < block.timestamp, "ClaimRewards: lockup period not expired" ); rewards += calculateRewards(tokenIds[i]); stakes[tokenIds[i]].lastClaimedBlock = uint128(block.number); } rewardToken.transfer(msg.sender, rewards); emit RewardsClaimed(msg.sender, rewards); } /** * @notice calculate rewards for all staken token ids of a given account * * @param account the account to calculate for */ function calculateRewardsByAccount(address account) external view returns (uint256) { uint256 rewards; for (uint256 i; i < stakedTokens[account].length(); i++) { rewards += calculateRewards(stakedTokens[account].at(i)); } return rewards; } /** * @notice calculate rewards for given token id * * @param tokenID the token id to calculate for */ function calculateRewards(uint256 tokenID) public view returns (uint256) { require(stakes[tokenID].lastClaimedBlock != 0, "token not staked"); uint256 rewards; uint256 blocksPassed; uint128 lastClaimedBlock = stakes[tokenID].lastClaimedBlock; uint256 from; uint256 last; for(uint256 i=0; i < rewardChanges.length; i++) { bool hasNext = i+1 < rewardChanges.length; from = rewardChanges[i].block >= lastClaimedBlock ? rewardChanges[i].block : lastClaimedBlock; last = hasNext ? (rewardChanges[i+1].block >= lastClaimedBlock ? rewardChanges[i+1].block : from ) : block.number; blocksPassed = last - from; rewards += rewardChanges[i].rewardPerBlock * blocksPassed; } return rewards; } /** * @notice return all staked token ids for a given account * * @param account the account to return token ids for */ function stakedTokensOf(address account) external view returns (uint256[] memory) { uint256[] memory tokenIds = new uint256[](stakedTokens[account].length()); for (uint256 i; i < tokenIds.length; i++) { tokenIds[i] = stakedTokens[account].at(i); } return tokenIds; } function onERC721Received(address operator, address, uint256, bytes memory) public view override returns (bytes4) { require(operator == address(this), "Operator not staking contract"); return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute. return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
calculate rewards for given token id tokenID the token id to calculate for/
function calculateRewards(uint256 tokenID) public view returns (uint256) { require(stakes[tokenID].lastClaimedBlock != 0, "token not staked"); uint256 rewards; uint256 blocksPassed; uint128 lastClaimedBlock = stakes[tokenID].lastClaimedBlock; uint256 from; uint256 last; for(uint256 i=0; i < rewardChanges.length; i++) { bool hasNext = i+1 < rewardChanges.length; from = rewardChanges[i].block >= lastClaimedBlock ? rewardChanges[i].block : lastClaimedBlock; last = hasNext ? (rewardChanges[i+1].block >= lastClaimedBlock ? rewardChanges[i+1].block : from ) : block.number; blocksPassed = last - from; rewards += rewardChanges[i].rewardPerBlock * blocksPassed; } return rewards; }
550,770
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract AOC01 is ERC20 { constructor(uint256 initialSupply) ERC20("AdventOfCode01", "AOC01") { _mint(msg.sender, initialSupply); } function decimals() public pure override returns (uint8) { return 0; } /* * Burns all coins in the users wallet * then solves part 1 of AOC 2021 Day 1 based on the input data * and mints the respective amount of coints for the user. */ function part1(uint256[] memory input) public { _burn(msg.sender, balanceOf(msg.sender)); uint256 solution = 0; uint256 i; for (i = 1; i < input.length; i++) { if (input[i] > input[i - 1]) { solution = solution + 1; } } _mint(msg.sender, solution); } /* * Burns all coins in the users wallet * then solves part 2 of AOC 2021 Day 1 based on the input data * and mints the respective amount of coints for the user. */ function part2(uint256[] calldata input) public { uint256 i; uint256[] memory aggregated; aggregated = new uint[](input.length - 2); for (i = 0; i < input.length - 2; i++) { aggregated[i] = input[i] + input[i+1] + input[i+2]; } part1(aggregated); } }
Burns all coins in the users wallet then solves part 1 of AOC 2021 Day 1 based on the input data and mints the respective amount of coints for the user./
function part1(uint256[] memory input) public { _burn(msg.sender, balanceOf(msg.sender)); uint256 solution = 0; uint256 i; for (i = 1; i < input.length; i++) { if (input[i] > input[i - 1]) { solution = solution + 1; } } _mint(msg.sender, solution); }
6,398,726
./partial_match/1/0xe0ce4a91f9EbA6539947ec2Ef8Fe92cE4aB3D272/sources/Vaulted.sol
Get the trusted balance of a particular account (the account's trust). Only the account with a trusted balance greater than cipher (0) can claim from its trust. _account The address of the account for which to retrieve the trust/
function account(address _account) public view returns (uint256) { return _vault.trust[_account]; }
4,190,941
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC1155/IERC1155.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/Context.sol@v4.5.0 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File contracts/NFTMarketplace.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Contract module which provides access control * * the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * mapped to * `onlyOwner` */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract NFTMarket is ReentrancyGuard, Pausable, Ownable { IERC1155 xPhunk; // instance of the xPhunk contract uint256 listingFee = 20; // 2% address payable treasury; struct Offer { bool isForSale; uint phunkIndex; address seller; uint minValue; // in ether address onlySellTo; } struct Bid { bool hasBid; uint phunkIndex; address bidder; uint value; } // A record of phunks that are offered for sale at a specific minimum value, and perhaps to a specific person mapping (uint => Offer) public phunksOfferedForSale; // A record of the highest phunk bid mapping (uint => Bid) public phunkBids; // A record of pending ETH withdrawls by address mapping (address => uint) public pendingWithdrawals; event PhunkOffered(uint indexed phunkIndex, uint minValue, address indexed toAddress); event PhunkBidEntered(uint indexed phunkIndex, uint value, address indexed fromAddress); event PhunkBidWithdrawn(uint indexed phunkIndex, uint value, address indexed fromAddress); event PhunkBought(uint indexed phunkIndex, uint value, address indexed fromAddress, address indexed toAddress); event PhunkNoLongerForSale(uint indexed phunkIndex); /* Initializes contract with an instance of xPhunk contract, and sets deployer as owner */ constructor(address _treasury, address _xPhunkAddress) { treasury = payable(_treasury); xPhunk = IERC1155(_xPhunkAddress); } function pause() public whenNotPaused onlyOwner { _pause(); } function unpause() public whenPaused onlyOwner { _unpause(); } /* Updates the listing Fee of the contract */ function updateListingFee(uint _listingFee) public payable { require(treasury == msg.sender, "Only marketplace owner can update listing Fee."); listingFee = _listingFee; } /* Returns the listing Fee of the contract */ function getListingFee() public view returns (uint256) { return listingFee; } /* Returns the xPhunk contract address currently being used */ function phunksAddress() public view returns (address) { return address(xPhunk); } /* Allows the owner of the contract to set a new xPhunk contract address */ function setxPhunkAddress(address newPhunksAddress) public onlyOwner { xPhunk = IERC1155(newPhunksAddress); } /* Returns the sale price for the offered phunk */ function getOfferedPrice(uint256 phunkIndex) external view returns (uint) { Offer memory offer = phunksOfferedForSale[phunkIndex]; if (!offer.isForSale) { return 0; } return offer.minValue; } /** Returns the pending withdrawal amount for the phunk sale */ function getPendingWithdrawal() external view returns (uint pendingWithdrawal) { return pendingWithdrawals[msg.sender]; } /* Returns the highest bid for the phunk */ function getHighestBid(uint256 phunkIndex) external view returns (uint) { Bid memory bid = phunkBids[phunkIndex]; if (!bid.hasBid) { return 0; } return bid.value; } /* Returns the highest bidder for the phunk */ function getHighestBidder(uint256 phunkIndex) external view returns (address) { Bid memory bid = phunkBids[phunkIndex]; if (!bid.hasBid) { return address(0); } return bid.bidder; } /* Allows the owner of a xPhunk to stop offering it for sale */ function phunkNoLongerForSale(uint phunkIndex) public nonReentrant() { if (xPhunk.balanceOf(msg.sender, phunkIndex) == 0) revert('you are not the owner of this token'); phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, msg.sender, 0, address(0x0)); emit PhunkNoLongerForSale(phunkIndex); } /* Allows a xPhunks owner to offer it for sale */ function offerPhunkForSale(uint phunkIndex, uint minSalePriceInWei) public whenNotPaused nonReentrant() { if (xPhunk.balanceOf(msg.sender, phunkIndex) == 0) revert('you are not the owner of this token'); phunksOfferedForSale[phunkIndex] = Offer(true, phunkIndex, msg.sender, minSalePriceInWei, address(0x0)); emit PhunkOffered(phunkIndex, minSalePriceInWei, address(0x0)); } /* Allows a xPhunks owner to offer it for sale to a specific address */ function offerPhunkForSaleToAddress(uint phunkIndex, uint minSalePriceInWei, address toAddress) public whenNotPaused nonReentrant() { if (xPhunk.balanceOf(msg.sender, phunkIndex) == 0) revert('you are not the owner of this token'); phunksOfferedForSale[phunkIndex] = Offer(true, phunkIndex, msg.sender, minSalePriceInWei, toAddress); emit PhunkOffered(phunkIndex, minSalePriceInWei, toAddress); } /* Allows users to buy a xPhunks offered for sale */ function buyPhunk(uint phunkIndex) payable public whenNotPaused nonReentrant() { Offer memory offer = phunksOfferedForSale[phunkIndex]; if (!offer.isForSale) revert('phunk is not for sale'); // phunk not actually for sale if (offer.onlySellTo != address(0x0) && offer.onlySellTo != msg.sender) revert(); if (msg.value != offer.minValue) revert('not enough ether'); // Didn't send enough ETH address seller = offer.seller; if (seller == msg.sender) revert('seller == msg.sender'); if (xPhunk.balanceOf(seller, phunkIndex) == 0) revert('seller no longer owner of phunk'); // Seller no longer owner of phunk phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, msg.sender, 0, address(0x0)); xPhunk.safeTransferFrom(seller, msg.sender, phunkIndex, 1, ""); pendingWithdrawals[seller] += msg.value; emit PhunkBought(phunkIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid memory bid = phunkBids[phunkIndex]; if (bid.bidder == msg.sender) { // Kill bid and refund value pendingWithdrawals[msg.sender] += bid.value; phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0); } } /* Allows users to retrieve ETH from sales */ function withdraw() public nonReentrant() { uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; // transfer the listing price to the market owner(loyalti feature) uint256 listingPrice = (amount * listingFee) / 1000; payable(treasury).transfer(listingPrice); // transfer sell price to the seller payable(msg.sender).transfer(amount - listingPrice); } /* Allows users to enter bids for any xPhunks */ function enterBidForPhunk(uint phunkIndex) payable public whenNotPaused nonReentrant() { if (xPhunk.balanceOf(msg.sender, phunkIndex) != 0) revert('you already own this phunk'); if (msg.value == 0) revert('cannot enter bid of zero'); Bid memory existing = phunkBids[phunkIndex]; if (msg.value <= existing.value) revert('your bid is too low'); if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } phunkBids[phunkIndex] = Bid(true, phunkIndex, msg.sender, msg.value); emit PhunkBidEntered(phunkIndex, msg.value, msg.sender); } /* Allows xPhunks owners to accept bids for their Phunks */ function acceptBidForPhunk(uint phunkIndex, uint minPrice) public whenNotPaused nonReentrant() { if (xPhunk.balanceOf(msg.sender, phunkIndex) == 0) revert('you do not own this token'); address seller = msg.sender; Bid memory bid = phunkBids[phunkIndex]; if (bid.value == 0) revert('cannot enter bid of zero'); if (bid.value < minPrice) revert('your bid is too low'); address bidder = bid.bidder; if (seller == bidder) revert('you already own this token'); phunksOfferedForSale[phunkIndex] = Offer(false, phunkIndex, bidder, 0, address(0x0)); uint amount = bid.value; phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0); xPhunk.safeTransferFrom(msg.sender, bidder, phunkIndex, 1, ""); pendingWithdrawals[seller] += amount; emit PhunkBought(phunkIndex, bid.value, seller, bidder); } /* Allows bidders to withdraw their bids */ function withdrawBidForPhunk(uint phunkIndex) public nonReentrant() { Bid memory bid = phunkBids[phunkIndex]; if (bid.bidder != msg.sender) revert('the bidder is not message sender'); emit PhunkBidWithdrawn(phunkIndex, bid.value, msg.sender); uint amount = bid.value; phunkBids[phunkIndex] = Bid(false, phunkIndex, address(0x0), 0); // Refund the bid money payable(msg.sender).transfer(amount); } function withdrawAll() public onlyOwner() { uint256 balance = address(this).balance; payable(owner()).transfer(balance); } }
Returns the pending withdrawal amount for the phunk sale /
function getPendingWithdrawal() external view returns (uint pendingWithdrawal) { return pendingWithdrawals[msg.sender]; }
14,931,872
//SPDX-License-Identifier: WTFPL pragma solidity ^0.7.6; import "hardhat/console.sol"; contract ZMSToken { // public modifier makes a variable readable from outside the contract. string public name = "Zymosis Boozing Society Token"; string public symbol = "ZMS"; // fixed amount of tokens uint256 public totalSupply = 9000000000000000000000; // 9000 uint8 public decimals = 18; address public owner; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor() { // assign totalSupply to the address which deploys this contract. balanceOf[msg.sender] = totalSupply; owner = msg.sender; } function transfer(address _to, uint256 _value) public returns (bool success) { // check that the transaction sender has enough tokens, otherwise reverts require(balanceOf[msg.sender] >= _value, "NOT_ENOUGH_TOKENS"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success) { // check that the value transferred is smaller or equal to the balance of the address to be transferred from require(_value <= balanceOf[_from], "NOT_ENOUGH_TOKENS"); require(_value <= allowance[_from][msg.sender], "NOT_ENOUGH_ALLOWANCE"); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } }
check that the transaction sender has enough tokens, otherwise reverts
function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value, "NOT_ENOUGH_TOKENS"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; }
15,836,670
pragma solidity ^0.4.23; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "./ERC721HoldingsBasic.sol"; /** * @title Holdings of ERC-721 Non-Fungible Token Standard, basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721HoldingsBasicToken is ERC721HoldingsBasic { using SafeMath for uint256; using AddressUtils for address; ERC721 public tokens; struct Holder { uint256 id; address origin; } // Mapping from token ID to Holder mapping (uint256 => Holder) internal tokenHolder; // Mapping from token ID to approved Holder mapping (uint256 => Holder) internal tokenHolderApprovals; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from holder to number of held token mapping (address => mapping (uint256 => uint256)) internal heldTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyTokenOwnerOf(uint256 _tokenId) { require(tokenOwnerOf(_tokenId) == msg.sender); _; } /** * @dev Guarantees msg.sender is holder owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Guarantees that the holder token exists * @param _holder ID to query the existance of * @param _holderOrigin address of the holder's origin */ modifier onlyIfExists(uint256 _holder, address _holderOrigin) { require(_ownerOf(_holder, _holderOrigin) != address(0)); _; } /** * @dev Checks msg.sender can transfer a token * @dev Token should exist and msg.sender is an owner, approved, or operator * @param _to uint256 ID of the holder to receive the token ID * @param _toOrigin address of the holder's origin * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _to, address _toOrigin, uint256 _tokenId) { require(exists(_tokenId)); require(isApprovedOrOwner(msg.sender, _tokenId) || isHolderApprovedFor(msg.sender, _to, _toOrigin, _tokenId)); _; } /** * @dev Constructor to create the ERC721HoldingsBasicToken contract * @param _nftAddress The ERC721 contract address of the tokens that will be held */ constructor(address _nftAddress) public { require(_nftAddress != address(0)); tokens = ERC721(_nftAddress); } /** * @dev Gets the origin contract of tokens stored by the contract * @return address representing the origin tokens contract */ function tokenAddress() public view returns (address) { return address(tokens); } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function tokenOwnerOf(uint256 _tokenId) public view returns (address) { return tokens.ownerOf(_tokenId); } /** * @dev Gets the owner of holder for the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the holder at origin */ function ownerOf(uint256 _tokenId) public view returns (address) { Holder memory holder = tokenHolder[_tokenId]; return _ownerOf(holder.id, holder.origin); } /** * @dev Gets the balance of the specified holder * @param _holder ID to query the balance of * @param _holderOrigin address of the holder's origin * @return uint256 representing the amount held by the given holder */ function balanceOf(uint256 _holder, address _holderOrigin) public view returns (uint256) { require(_holderOrigin != address(0)); return heldTokensCount[_holderOrigin][_holder]; } /** * @dev Gets the holder of the specified token ID * @param _tokenId uint256 ID of the token to query the holder of * @return holder ID currently marked as the holder of the given token ID * @return holder's origin contract address */ function holderOf(uint256 _tokenId) public view returns (uint256, address) { Holder memory holder = tokenHolder[_tokenId]; require(holder.origin != address(0)); return (holder.id, holder.origin); } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { return tokenHolder[_tokenId].origin != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Approve specific holdings to be transfered once to a specific holder * @param _to uint256 ID of the holder to be approved for the given token ID * @param _toOrigin address of the holder's origin * @param _tokenId uint256 ID of the token to be approved */ function approveHolder(uint256 _to, address _toOrigin, uint256 _tokenId) public { require(_toOrigin != address(0) || _to == 0); require(_to != tokenHolder[_tokenId].id || _toOrigin != tokenHolder[_tokenId].origin); address owner = ownerOf(_tokenId); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (tokenHolderApprovals[_tokenId].origin != address(0) || _toOrigin != address(0)) { tokenHolderApprovals[_tokenId] = Holder(_to, _toOrigin); emit HolderApproval(owner, _to, _toOrigin, _tokenId); } } /** * @dev Gets the approved holder for a token ID, or zero if no approved holder is set * @param _tokenId uint256 ID of the token to query the approval of * @return uint256 token ID of the holder * @return address holder origin */ function getApprovedHolder(uint256 _tokenId) public view returns (uint256, address) { Holder memory approved = tokenHolderApprovals[_tokenId]; return (approved.id, approved.origin); } /** * @dev Transfers the ownership of a given token ID to another address * @dev Requires the msg sender to be the owner, approved, or operator * @param _owner current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _owner, uint256 _to, address _toOrigin, uint256 _tokenId) public onlyIfExists(_to, _toOrigin) canTransfer(_to, _toOrigin, _tokenId) { require(_owner != address(0)); clearApproval(_owner, _tokenId); Holder memory from = tokenHolder[_tokenId]; removeTokenFrom(from.id, from.origin, _tokenId); addTokenTo(_to, _toOrigin, _tokenId); emit Transfer(from.id, from.origin, _to, _toOrigin, _tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _spender || isOwnerOrApprovedForAll(_spender, _tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is an operator of the owner, or is the owner of the token */ function isOwnerOrApprovedForAll(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || isApprovedForAll(owner, _spender); } /** * @dev Returns whether the given spender can transfer a given token ID to holder * @param _spender address of the spender to query * @param _to uint256 ID of the holder to receive the token ID * @param _toOrigin address of the holder's origin * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isHolderApprovedFor(address _spender, uint256 _to, address _toOrigin, uint256 _tokenId) internal view returns (bool) { // Is transfer to holder approved and holder owner is _spender Holder memory approved = tokenHolderApprovals[_tokenId]; return approved.id == _to && approved.origin == _toOrigin && _ownerOf(_to, _toOrigin) == _spender; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The holder ID that will hold the minted token * @param _toOrigin address of the holder's origin * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(uint256 _to, address _toOrigin, uint256 _tokenId) internal onlyIfExists(_to, _toOrigin) { addTokenTo(_to, _toOrigin, _tokenId); emit Transfer(0, address(0), _to, _toOrigin, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); Holder memory holder = tokenHolder[_tokenId]; removeTokenFrom(holder.id, holder.origin, _tokenId); emit Transfer(holder.id, holder.origin, 0, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } if (tokenHolderApprovals[_tokenId].origin != address(0)) { tokenHolderApprovals[_tokenId] = Holder(0, address(0)); emit HolderApproval(_owner, 0, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given holder * @param _to uint256 ID representing the new holder of the given token ID * @param _toOrigin address of the new holder's origin * @param _tokenId uint256 ID of the token to be added to the tokens list of the given holder ID */ function addTokenTo(uint256 _to, address _toOrigin, uint256 _tokenId) internal { require(tokenHolder[_tokenId].origin == address(0)); tokenHolder[_tokenId] = Holder(_to, _toOrigin); heldTokensCount[_toOrigin][_to] = heldTokensCount[_toOrigin][_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given holder ID * @param _from uint256 ID representing the previous holder of the given token ID * @param _fromOrigin address of the previous holder's origin * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given holder ID */ function removeTokenFrom(uint256 _from, address _fromOrigin, uint256 _tokenId) internal { require(tokenHolder[_tokenId].origin != address(0)); require(tokenHolder[_tokenId].id == _from && tokenHolder[_tokenId].origin == _fromOrigin); heldTokensCount[_fromOrigin][_from] = heldTokensCount[_fromOrigin][_from].sub(1); tokenHolder[_tokenId] = Holder(0, address(0)); } /** * @dev Gets the owner of token with ID at sepcific origin * @param _id ID to query the existance of * @param _origin address of the holder's origin * @return owner address currently marked as the owner */ function _ownerOf(uint256 _id, address _origin) internal view returns (address) { require(_origin != address(0)); return ERC721(_origin).ownerOf(_id); } }
Gets the owner of token with ID at sepcific origin _id ID to query the existance of _origin address of the holder's origin return owner address currently marked as the owner/
function _ownerOf(uint256 _id, address _origin) internal view returns (address) { require(_origin != address(0)); return ERC721(_origin).ownerOf(_id); }
12,729,798
pragma solidity 0.4.26; import "./ISovrynSwapNetwork.sol"; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/ISovrynSwapFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/ISmartToken.sol"; import "./sovrynswapx/interfaces/ISovrynSwapX.sol"; // interface of older converters for backward compatibility contract ILegacyConverter { function change( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn ) public returns (uint256); } /** * @dev The SovrynSwapNetwork contract is the main entry point for SovrynSwap token conversions. * It also allows for the conversion of any token in the SovrynSwap Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the SovrynSwap Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract SovrynSwapNetwork is ISovrynSwapNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping(address => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new SovrynSwapNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = _path[i - 2]; IERC20Token anchor = _path[i - 1]; IERC20Token targetToken = _path[i]; converter = IConverter(IConverterAnchor(anchor).owner()); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (targetToken == anchor) { // buy the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.add(amount); } else if (sourceToken == anchor) { // sell the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the sovrynSwap network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = _path[_path.length - 1]; ISovrynSwapX sovrynSwapX = ISovrynSwapX(addressOf(SOVRYNSWAP_X)); // verify that the destination token is BNT require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee); // grant SovrynSwapX allowance ensureAllowance(targetToken, sovrynSwapX, amount); // transfer the resulting amount to SovrynSwapX sovrynSwapX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the SovrynSwapNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * SovrynSwapX contract directly by specifying the conversion id * * @param _path conversion path * @param _sovrynSwapX address of the SovrynSwapX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion( IERC20Token[] _path, ISovrynSwapX _sovrynSwapX, uint256 _conversionId, uint256 _minReturn, address _beneficiary ) public returns (uint256) { // verify that the source token is the SovrynSwapX token require(_path[0] == _sovrynSwapX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from SovrynSwapX contract uint256 amount = _sovrynSwapX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } // older converter // if the source token is the smart token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)( stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary ); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken( IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount ) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, this, _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken( ConversionStep[] _data, uint256 _amount, address _beneficiary ) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(targetToken).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData( IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled ) private view returns (ConversionStep[]) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; address bntToken = addressOf(BNT_TOKEN); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(anchor.owner()); IERC20Token targetToken = _conversionPath[i + 2]; // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ anchor: // set the converter anchor anchor, converter: // set the converter converter, sourceToken: // set the source/target tokens _conversionPath[i], targetToken: targetToken, beneficiary: // requires knowledge about the next step, so initialize in the next phase address(0), isV28OrHigherConverter: // set flags isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = this; // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = data[i + 1].converter; // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = this; } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = this; } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { address reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return IERC20Token(ETH_RESERVE_ADDRESS); return IERC20Token(getConverterEtherTokenAddress(_converter)); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using assembly code since older converter versions have different return values function getReturn( address _dest, address _sourceToken, address _targetToken, uint256 _amount ) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using assembly code to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bool success; uint256[1] memory ret; bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); assembly { success := staticcall( 5000, // isV28OrHigher consumes 190 gas, but just for extra safety _converter, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) } return success && ret[0] != 0; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } }
validates msg.value and prepares the conversion source token for the conversion _sourceToken source token of the first conversion step _anchor converter anchor of the first conversion step _amount amount to convert from, in the source token/ ETH validate msg.value EtherToken converter - deposit the ETH into the EtherToken note that it can still be a non ETH converter if the path is wrong but such conversion will simply revert EtherToken claim the tokens - if the source token is ETH reserve, this call will fail since in that case the transaction must be sent with msg.value ETH converter - withdraw the ETH other ERC20 token newer converter - transfer the tokens from the sender directly to the converter otherwise claim the tokens
function handleSourceToken( IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount ) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); if (msg.value > 0) { require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } else if (etherTokens[_sourceToken]) { safeTransferFrom(_sourceToken, msg.sender, this, _amount); if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } else { if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } }
12,943,192
./full_match/40/0x34bc1b87f60e0a30c0e24FD7Abada70436c71406/sources/contracts/interfaces/IWrapToken.sol
Interface for WrapToken
interface IWrapToken is IERC20 { function originToken() external view returns(address); function depositAllowance(address owner, address spender) external view returns (uint256); function depositApprove(address spender, uint256 amount) external; function depositFrom(address from, address to, uint256 amount) external returns(uint256 actualAmount); function withdraw(address to, uint256 amount) external returns(uint256 actualAmount); pragma solidity ^0.8.4; }
9,551,859
./partial_match/1/0x5f1F5b4BFAa78E4e1F8063b71E96656bAF965Db7/sources/KongEntropyDirectMint.sol
primaryPublicKeyHash Hash of the primary public key. tertiaryPublicKeyX The x-coordinate of the tertiary public key. tertiaryPublicKeyY The y-coordinate of the tertiary public key. to Recipient. blockNumber Block number of the signed blockhash. rs The array containing the r & s values fo the signature./ Verify that the primary key hash is registered and associated with a non-zero tertiary key hash. Verify that the hash of the provided tertiary key coincides with the stored hash of the tertiary key. Verify that no signature has been submitted before for this key. Get Kong amount; Divide internal representation by 10 17 for cost scaling. Perform work in proportion to scaledKongAmount.
function submitEntropy( bytes32 primaryPublicKeyHash, uint256 tertiaryPublicKeyX, uint256 tertiaryPublicKeyY, address to, uint256 blockNumber, uint256[2] memory rs ) public { bytes32 tertiaryPublicKeyHash = RegisterInterface(_regAddress).getTertiaryKeyHash(primaryPublicKeyHash); require(tertiaryPublicKeyHash != 0, 'Found no registration.'); bytes32 hashedKey = sha256(abi.encodePacked(tertiaryPublicKeyX, tertiaryPublicKeyY)); require(tertiaryPublicKeyHash == hashedKey, 'Provided key does not hash to expected value.'); require(_mintedKeys[primaryPublicKeyHash] == false, 'Has already been minted.'); uint scaledKongAmount = RegisterInterface(_regAddress).getKongAmount(primaryPublicKeyHash) / uint(10 ** 17); bytes32 powHash = blockhash(block.number); for (uint i=0; i < scaledKongAmount; i++) { powHash = keccak256(abi.encodePacked(powHash)); } require(_validateSignature(messageHash, rs, tertiaryPublicKeyX, tertiaryPublicKeyY), 'Invalid signature.'); }
15,523,972
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "../core/State.sol"; import "../events/ProtocolSettingsEvents.sol"; import "../openzeppelin/SafeERC20.sol"; import "../mixins/ProtocolTokenUser.sol"; import "../modules/interfaces/ProtocolSwapExternalInterface.sol"; import "../mixins/ModuleCommonFunctionalities.sol"; import "../swaps/ISwapsImpl.sol"; import "../governance/IFeeSharingProxy.sol"; import "../feeds/IPriceFeeds.sol"; /** * @title Protocol Settings contract. * * @notice This contract code comes from bZx. bZx is a protocol for tokenized * margin trading and lending https://bzx.network similar to the dYdX protocol. * * This contract contains functions to customize protocol settings. * */ contract ProtocolSettings is State, ProtocolTokenUser, ProtocolSettingsEvents, ModuleCommonFunctionalities { using SafeERC20 for IERC20; using SafeMath for uint256; /** * @notice Empty public constructor. * */ constructor() public {} /** * @notice Fallback function is to react to receiving value (rBTC). * */ function() external { revert("fallback not allowed"); } /** * @notice Set function selectors on target contract. * * @param target The address of the target contract. * */ function initialize(address target) external onlyOwner { address prevModuleContractAddress = logicTargets[this.setPriceFeedContract.selector]; _setTarget(this.setPriceFeedContract.selector, target); _setTarget(this.setSwapsImplContract.selector, target); _setTarget(this.setLoanPool.selector, target); _setTarget(this.setSupportedTokens.selector, target); _setTarget(this.setLendingFeePercent.selector, target); _setTarget(this.setTradingFeePercent.selector, target); _setTarget(this.setBorrowingFeePercent.selector, target); _setTarget(this.setSwapExternalFeePercent.selector, target); _setTarget(this.setAffiliateFeePercent.selector, target); _setTarget(this.setAffiliateTradingTokenFeePercent.selector, target); _setTarget(this.setLiquidationIncentivePercent.selector, target); _setTarget(this.setMaxDisagreement.selector, target); _setTarget(this.setSourceBuffer.selector, target); _setTarget(this.setMaxSwapSize.selector, target); _setTarget(this.setFeesController.selector, target); _setTarget(this.withdrawFees.selector, target); _setTarget(this.withdrawLendingFees.selector, target); _setTarget(this.withdrawTradingFees.selector, target); _setTarget(this.withdrawBorrowingFees.selector, target); _setTarget(this.withdrawProtocolToken.selector, target); _setTarget(this.depositProtocolToken.selector, target); _setTarget(this.getLoanPoolsList.selector, target); _setTarget(this.isLoanPool.selector, target); _setTarget(this.setSovrynSwapContractRegistryAddress.selector, target); _setTarget(this.setWrbtcToken.selector, target); _setTarget(this.setProtocolTokenAddress.selector, target); _setTarget(this.setRolloverBaseReward.selector, target); _setTarget(this.setRebatePercent.selector, target); _setTarget(this.setSpecialRebates.selector, target); _setTarget(this.setSovrynProtocolAddress.selector, target); _setTarget(this.setSOVTokenAddress.selector, target); _setTarget(this.setLockedSOVAddress.selector, target); _setTarget(this.setMinReferralsToPayoutAffiliates.selector, target); _setTarget(this.getSpecialRebates.selector, target); _setTarget(this.getProtocolAddress.selector, target); _setTarget(this.getSovTokenAddress.selector, target); _setTarget(this.getLockedSOVAddress.selector, target); _setTarget(this.getFeeRebatePercent.selector, target); _setTarget(this.togglePaused.selector, target); _setTarget(this.isProtocolPaused.selector, target); _setTarget(this.getSwapExternalFeePercent.selector, target); _setTarget(this.setTradingRebateRewardsBasisPoint.selector, target); _setTarget(this.getTradingRebateRewardsBasisPoint.selector, target); _setTarget(this.getDedicatedSOVRebate.selector, target); _setTarget(this.setRolloverFlexFeePercent.selector, target); emit ProtocolModuleContractReplaced(prevModuleContractAddress, target, "ProtocolSettings"); } /** * setting wrong address will break inter module functions calling * should be set once */ function setSovrynProtocolAddress(address newProtocolAddress) external onlyOwner whenNotPaused { address oldProtocolAddress = protocolAddress; protocolAddress = newProtocolAddress; emit SetProtocolAddress(msg.sender, oldProtocolAddress, newProtocolAddress); } function setSOVTokenAddress(address newSovTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(newSovTokenAddress), "newSovTokenAddress not a contract"); address oldTokenAddress = sovTokenAddress; sovTokenAddress = newSovTokenAddress; emit SetSOVTokenAddress(msg.sender, oldTokenAddress, newSovTokenAddress); } function setLockedSOVAddress(address newLockedSOVAddress) external onlyOwner whenNotPaused { require(Address.isContract(newLockedSOVAddress), "newLockSOVAddress not a contract"); address oldLockedSOVAddress = lockedSOVAddress; lockedSOVAddress = newLockedSOVAddress; emit SetLockedSOVAddress(msg.sender, oldLockedSOVAddress, newLockedSOVAddress); } /** * @notice Set the basis point of trading rebate rewards (SOV), max value is 9999 (99.99% liquid, 0.01% vested). * * @param newBasisPoint Basis point value. */ function setTradingRebateRewardsBasisPoint(uint256 newBasisPoint) external onlyOwner whenNotPaused { require(newBasisPoint <= 9999, "value too high"); uint256 oldBasisPoint = tradingRebateRewardsBasisPoint; tradingRebateRewardsBasisPoint = newBasisPoint; emit SetTradingRebateRewardsBasisPoint(msg.sender, oldBasisPoint, newBasisPoint); } /** * @notice Update the minimum number of referrals to get affiliates rewards. * * @param newMinReferrals The new minimum number of referrals. * */ function setMinReferralsToPayoutAffiliates(uint256 newMinReferrals) external onlyOwner whenNotPaused { uint256 oldMinReferrals = minReferralsToPayout; minReferralsToPayout = newMinReferrals; emit SetMinReferralsToPayoutAffiliates(msg.sender, oldMinReferrals, newMinReferrals); } /** * @notice Set the address of the Price Feed instance. * * @param newContract The address of the Price Feed new instance. * */ function setPriceFeedContract(address newContract) external onlyOwner whenNotPaused { address oldContract = priceFeeds; priceFeeds = newContract; emit SetPriceFeedContract(msg.sender, oldContract, newContract); } /** * @notice Set the address of the asset swapper instance. * * @param newContract The address of the asset swapper new instance. * */ function setSwapsImplContract(address newContract) external onlyOwner whenNotPaused { address oldContract = swapsImpl; swapsImpl = newContract; emit SetSwapsImplContract(msg.sender, oldContract, newContract); } /** * @notice Set a list of loan pools and its tokens. * * @param pools The array of addresses of new loan pool instances. * @param assets The array of addresses of the corresponding underlying tokens. * */ function setLoanPool(address[] calldata pools, address[] calldata assets) external onlyOwner whenNotPaused { require(pools.length == assets.length, "count mismatch"); for (uint256 i = 0; i < pools.length; i++) { require(pools[i] != assets[i], "pool == asset"); require(pools[i] != address(0), "pool == 0"); require( assets[i] != address(0) || loanPoolToUnderlying[pools[i]] != address(0), "pool not exists" ); if (assets[i] == address(0)) { underlyingToLoanPool[loanPoolToUnderlying[pools[i]]] = address(0); loanPoolToUnderlying[pools[i]] = address(0); loanPoolsSet.removeAddress(pools[i]); } else { loanPoolToUnderlying[pools[i]] = assets[i]; underlyingToLoanPool[assets[i]] = pools[i]; loanPoolsSet.addAddress(pools[i]); } emit SetLoanPool(msg.sender, pools[i], assets[i]); } } /** * @notice Set a list of supported tokens by populating the * storage supportedTokens mapping. * * @param addrs The array of addresses of the tokens. * @param toggles The array of flags indicating whether * the corresponding token is supported or not. * */ function setSupportedTokens(address[] calldata addrs, bool[] calldata toggles) external onlyOwner whenNotPaused { require(addrs.length == toggles.length, "count mismatch"); for (uint256 i = 0; i < addrs.length; i++) { supportedTokens[addrs[i]] = toggles[i]; emit SetSupportedTokens(msg.sender, addrs[i], toggles[i]); } } /** * @notice Set the value of lendingFeePercent storage variable. * * @param newValue The new value for lendingFeePercent. * */ function setLendingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = lendingFeePercent; lendingFeePercent = newValue; emit SetLendingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of tradingFeePercent storage variable. * * @param newValue The new value for tradingFeePercent. * */ function setTradingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = tradingFeePercent; tradingFeePercent = newValue; emit SetTradingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of borrowingFeePercent storage variable. * * @param newValue The new value for borrowingFeePercent. * */ function setBorrowingFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = borrowingFeePercent; borrowingFeePercent = newValue; emit SetBorrowingFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of swapExtrernalFeePercent storage variable * * @param newValue the new value for swapExternalFeePercent */ function setSwapExternalFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = swapExtrernalFeePercent; swapExtrernalFeePercent = newValue; emit SetSwapExternalFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of affiliateFeePercent storage variable. * * @param newValue The new value for affiliateFeePercent. * */ function setAffiliateFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = affiliateFeePercent; affiliateFeePercent = newValue; emit SetAffiliateFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of affiliateTradingTokenFeePercent storage variable. * * @param newValue The new value for affiliateTradingTokenFeePercent. * */ function setAffiliateTradingTokenFeePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = affiliateTradingTokenFeePercent; affiliateTradingTokenFeePercent = newValue; emit SetAffiliateTradingTokenFeePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of liquidationIncentivePercent storage variable. * * @param newValue The new value for liquidationIncentivePercent. * */ function setLiquidationIncentivePercent(uint256 newValue) external onlyOwner whenNotPaused { require(newValue <= 10**20, "value too high"); uint256 oldValue = liquidationIncentivePercent; liquidationIncentivePercent = newValue; emit SetLiquidationIncentivePercent(msg.sender, oldValue, newValue); } /** * @notice Set the value of the maximum swap spread. * * @param newValue The new value for maxDisagreement. * */ function setMaxDisagreement(uint256 newValue) external onlyOwner whenNotPaused { maxDisagreement = newValue; } /** * @notice Set the value of the maximum source buffer. * * @dev To avoid rounding issues on the swap rate a small buffer is implemented. * * @param newValue The new value for the maximum source buffer. * */ function setSourceBuffer(uint256 newValue) external onlyOwner whenNotPaused { sourceBuffer = newValue; } /** * @notice Set the value of the swap size limit. * * @param newValue The new value for the maximum swap size. * */ function setMaxSwapSize(uint256 newValue) external onlyOwner whenNotPaused { uint256 oldValue = maxSwapSize; maxSwapSize = newValue; emit SetMaxSwapSize(msg.sender, oldValue, newValue); } /** * @notice Set the address of the feesController instance. * * @dev The fee sharing proxy must be the feesController of the * protocol contract. This allows the fee sharing proxy * to withdraw the fees. * * @param newController The new address of the feesController. * */ function setFeesController(address newController) external onlyOwner whenNotPaused { address oldController = feesController; feesController = newController; emit SetFeesController(msg.sender, oldController, newController); } /** * @notice The feesController calls this function to withdraw fees * from three sources: lending, trading and borrowing. * The fees (except SOV) will be converted to wRBTC. * For SOV, it will be deposited directly to feeSharingProxy from the protocol. * * @param tokens The array of address of the token instance. * @param receiver The address of the withdrawal recipient. * * @return The withdrawn total amount in wRBTC * */ function withdrawFees(address[] calldata tokens, address receiver) external whenNotPaused returns (uint256 totalWRBTCWithdrawn) { require(msg.sender == feesController, "unauthorized"); for (uint256 i = 0; i < tokens.length; i++) { uint256 lendingBalance = lendingFeeTokensHeld[tokens[i]]; if (lendingBalance > 0) { lendingFeeTokensHeld[tokens[i]] = 0; lendingFeeTokensPaid[tokens[i]] = lendingFeeTokensPaid[tokens[i]].add( lendingBalance ); } uint256 tradingBalance = tradingFeeTokensHeld[tokens[i]]; if (tradingBalance > 0) { tradingFeeTokensHeld[tokens[i]] = 0; tradingFeeTokensPaid[tokens[i]] = tradingFeeTokensPaid[tokens[i]].add( tradingBalance ); } uint256 borrowingBalance = borrowingFeeTokensHeld[tokens[i]]; if (borrowingBalance > 0) { borrowingFeeTokensHeld[tokens[i]] = 0; borrowingFeeTokensPaid[tokens[i]] = borrowingFeeTokensPaid[tokens[i]].add( borrowingBalance ); } uint256 tempAmount = lendingBalance.add(tradingBalance).add(borrowingBalance); if (tempAmount == 0) { continue; } uint256 amountConvertedToWRBTC; if (tokens[i] == address(sovTokenAddress)) { IERC20(tokens[i]).approve(feesController, tempAmount); IFeeSharingProxy(feesController).transferTokens( address(sovTokenAddress), uint96(tempAmount) ); amountConvertedToWRBTC = 0; } else { if (tokens[i] == address(wrbtcToken)) { amountConvertedToWRBTC = tempAmount; IERC20(address(wrbtcToken)).safeTransfer(receiver, amountConvertedToWRBTC); } else { IERC20(tokens[i]).approve(protocolAddress, tempAmount); (amountConvertedToWRBTC, ) = ProtocolSwapExternalInterface(protocolAddress) .swapExternal( tokens[i], // source token address address(wrbtcToken), // dest token address feesController, // set feeSharingProxy as receiver protocolAddress, // protocol as the sender tempAmount, // source token amount 0, // reqDestToken 0, // minReturn "" // loan data bytes ); /// Will revert if disagreement found. IPriceFeeds(priceFeeds).checkPriceDisagreement( tokens[i], address(wrbtcToken), tempAmount, amountConvertedToWRBTC, maxDisagreement ); } totalWRBTCWithdrawn = totalWRBTCWithdrawn.add(amountConvertedToWRBTC); } emit WithdrawFees( msg.sender, tokens[i], receiver, lendingBalance, tradingBalance, borrowingBalance, amountConvertedToWRBTC ); } return totalWRBTCWithdrawn; } /** * @notice The feesController calls this function to withdraw fees * accrued from lending operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawLendingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = lendingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } lendingFeeTokensHeld[token] = balance.sub(withdrawAmount); lendingFeeTokensPaid[token] = lendingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawLendingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The feesController calls this function to withdraw fees * accrued from trading operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawTradingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = tradingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } tradingFeeTokensHeld[token] = balance.sub(withdrawAmount); tradingFeeTokensPaid[token] = tradingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawTradingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The feesController calls this function to withdraw fees * accrued from borrowing operations. * * @param token The address of the token instance. * @param receiver The address of the withdrawal recipient. * @param amount The amount of fees to get, ignored if greater than balance. * * @return Whether withdrawal was successful. * */ function withdrawBorrowingFees( address token, address receiver, uint256 amount ) external whenNotPaused returns (bool) { require(msg.sender == feesController, "unauthorized"); uint256 withdrawAmount = amount; uint256 balance = borrowingFeeTokensHeld[token]; if (withdrawAmount > balance) { withdrawAmount = balance; } if (withdrawAmount == 0) { return false; } borrowingFeeTokensHeld[token] = balance.sub(withdrawAmount); borrowingFeeTokensPaid[token] = borrowingFeeTokensPaid[token].add(withdrawAmount); IERC20(token).safeTransfer(receiver, withdrawAmount); emit WithdrawBorrowingFees(msg.sender, token, receiver, withdrawAmount); return true; } /** * @notice The owner calls this function to withdraw protocol tokens. * * @dev Wrapper for ProtocolTokenUser::_withdrawProtocolToken internal function. * * @param receiver The address of the withdrawal recipient. * @param amount The amount of tokens to get. * * @return The protocol token address. * @return Withdrawal success (true/false). * */ function withdrawProtocolToken(address receiver, uint256 amount) external onlyOwner whenNotPaused returns (address, bool) { return _withdrawProtocolToken(receiver, amount); } /** * @notice The owner calls this function to deposit protocol tokens. * * @param amount The tokens of fees to send. * */ function depositProtocolToken(uint256 amount) external onlyOwner whenNotPaused { /// @dev Update local balance protocolTokenHeld = protocolTokenHeld.add(amount); /// @dev Send the tokens IERC20(protocolTokenAddress).safeTransferFrom(msg.sender, address(this), amount); } /** * @notice Get a list of loan pools. * * @param start The offset. * @param count The limit. * * @return The array of loan pools. * */ function getLoanPoolsList(uint256 start, uint256 count) external view returns (bytes32[] memory) { return loanPoolsSet.enumerate(start, count); } /** * @notice Check whether a token is a pool token. * * @dev By querying its underlying token. * * @param loanPool The token address to check. * */ function isLoanPool(address loanPool) external view returns (bool) { return loanPoolToUnderlying[loanPool] != address(0); } /** * @notice Set the contract registry address of the SovrynSwap network. * * @param registryAddress the address of the registry contract. * */ function setSovrynSwapContractRegistryAddress(address registryAddress) external onlyOwner whenNotPaused { require(Address.isContract(registryAddress), "registryAddress not a contract"); address oldSovrynSwapContractRegistryAddress = sovrynSwapContractRegistryAddress; sovrynSwapContractRegistryAddress = registryAddress; emit SetSovrynSwapContractRegistryAddress( msg.sender, oldSovrynSwapContractRegistryAddress, sovrynSwapContractRegistryAddress ); } /** * @notice Set the wrBTC contract address. * * @param wrbtcTokenAddress The address of the wrBTC contract. * */ function setWrbtcToken(address wrbtcTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(wrbtcTokenAddress), "wrbtcTokenAddress not a contract"); address oldwrbtcToken = address(wrbtcToken); wrbtcToken = IWrbtcERC20(wrbtcTokenAddress); emit SetWrbtcToken(msg.sender, oldwrbtcToken, wrbtcTokenAddress); } /** * @notice Set the protocol token contract address. * * @param _protocolTokenAddress The address of the protocol token contract. * */ function setProtocolTokenAddress(address _protocolTokenAddress) external onlyOwner whenNotPaused { require(Address.isContract(_protocolTokenAddress), "_protocolTokenAddress not a contract"); address oldProtocolTokenAddress = protocolTokenAddress; protocolTokenAddress = _protocolTokenAddress; emit SetProtocolTokenAddress(msg.sender, oldProtocolTokenAddress, _protocolTokenAddress); } /** * @notice Set rollover base reward. It should be denominated in wrBTC. * * @param baseRewardValue The base reward. * */ function setRolloverBaseReward(uint256 baseRewardValue) external onlyOwner whenNotPaused { require(baseRewardValue > 0, "Base reward is zero"); uint256 oldValue = rolloverBaseReward; rolloverBaseReward = baseRewardValue; emit SetRolloverBaseReward(msg.sender, oldValue, rolloverBaseReward); } /** * @notice Set the fee rebate percent. * * @param rebatePercent The fee rebate percent. * */ function setRebatePercent(uint256 rebatePercent) external onlyOwner whenNotPaused { require(rebatePercent <= 10**20, "Fee rebate is too high"); uint256 oldRebatePercent = feeRebatePercent; feeRebatePercent = rebatePercent; emit SetRebatePercent(msg.sender, oldRebatePercent, rebatePercent); } /** * @notice Set the special fee rebate percent for specific pair * * @param specialRebatesPercent The new special fee rebate percent. * */ function setSpecialRebates( address sourceToken, address destToken, uint256 specialRebatesPercent ) external onlyOwner whenNotPaused { // Set max special rebates to 1000% require(specialRebatesPercent <= 1000e18, "Special fee rebate is too high"); uint256 oldSpecialRebatesPercent = specialRebates[sourceToken][destToken]; specialRebates[sourceToken][destToken] = specialRebatesPercent; emit SetSpecialRebates( msg.sender, sourceToken, destToken, oldSpecialRebatesPercent, specialRebatesPercent ); } /** * @notice Get a rebate percent of specific pairs. * * @param sourceTokenAddress The source of pairs. * @param destTokenAddress The dest of pairs. * * @return The percent rebates of the pairs. * */ function getSpecialRebates(address sourceTokenAddress, address destTokenAddress) external view returns (uint256 specialRebatesPercent) { return specialRebates[sourceTokenAddress][destTokenAddress]; } function getProtocolAddress() external view returns (address) { return protocolAddress; } function getSovTokenAddress() external view returns (address) { return sovTokenAddress; } function getLockedSOVAddress() external view returns (address) { return lockedSOVAddress; } function getFeeRebatePercent() external view returns (uint256) { return feeRebatePercent; } function togglePaused(bool paused) external onlyOwner { require(paused != pause, "Can't toggle"); pause = paused; emit TogglePaused(msg.sender, !paused, paused); } function isProtocolPaused() external view returns (bool) { return pause; } function getSwapExternalFeePercent() external view returns (uint256) { return swapExtrernalFeePercent; } /** * @notice Get the basis point of trading rebate rewards. * * @return The basis point value. */ function getTradingRebateRewardsBasisPoint() external view returns (uint256) { return tradingRebateRewardsBasisPoint; } /** * @dev Get how much SOV that is dedicated to pay the trading rebate rewards. * @notice If SOV balance is less than the fees held, it will return 0. * * @return total dedicated SOV. */ function getDedicatedSOVRebate() public view returns (uint256) { uint256 sovProtocolBalance = IERC20(sovTokenAddress).balanceOf(address(this)); uint256 sovFees = lendingFeeTokensHeld[sovTokenAddress].add(tradingFeeTokensHeld[sovTokenAddress]).add( borrowingFeeTokensHeld[sovTokenAddress] ); return sovProtocolBalance >= sovFees ? sovProtocolBalance.sub(sovFees) : 0; } /** * @notice Set rolloverFlexFeePercent (max value is 1%) * * @param newRolloverFlexFeePercent uint256 value of new rollover flex fee percentage (0.1 ether = 0.1%) */ function setRolloverFlexFeePercent(uint256 newRolloverFlexFeePercent) external onlyOwner whenNotPaused { require(newRolloverFlexFeePercent <= 1e18, "value too high"); uint256 oldRolloverFlexFeePercent = rolloverFlexFeePercent; rolloverFlexFeePercent = newRolloverFlexFeePercent; emit SetRolloverFlexFeePercent( msg.sender, oldRolloverFlexFeePercent, newRolloverFlexFeePercent ); } }
The owner calls this function to deposit protocol tokens. amount The tokens of fees to send. /
function depositProtocolToken(uint256 amount) external onlyOwner whenNotPaused { protocolTokenHeld = protocolTokenHeld.add(amount); IERC20(protocolTokenAddress).safeTransferFrom(msg.sender, address(this), amount);
1,801,171